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
fix(standalone): open a note in a new window without eating the tab set
Elian Dorand17a8412e857
diff --git a/apps/client/src/components/entrypoints.spec.ts b/apps/client/src/components/entrypoints.spec.tsnew file mode 100644index 0000000000..e9ea180fe5--- /dev/null+++ b/apps/client/src/components/entrypoints.spec.ts@@ -0,0 +1,34 @@+import type { ElectronApi } from "@triliumnext/commons";+import { beforeEach, describe, expect, it, vi } from "vitest";++import Entrypoints from "./entrypoints.js";++describe("openInWindowCommand", () => {+ const entrypoints = new Entrypoints();++ beforeEach(() => {+ vi.restoreAllMocks();+ delete window.electronApi;+ });++ it("opens a browser window on the extra-window URL", async () => {+ const open = vi.spyOn(window, "open").mockReturnValue(null);++ await entrypoints.openInWindowCommand({ notePath: "root/abc123", hoistedNoteId: "root" });++ const [url] = open.mock.calls[0];+ expect(String(url)).toMatch(/[?&]extraWindow=1/);+ expect(String(url)).toMatch(/#root\/abc123$/);+ });++ it("hands only the hash to Electron, which builds the URL itself", async () => {+ const createExtraWindow = vi.fn();+ window.electronApi = { window: { createExtraWindow } } as unknown as ElectronApi;+ const open = vi.spyOn(window, "open");++ await entrypoints.openInWindowCommand({ notePath: "root/abc123", hoistedNoteId: "root" });++ expect(createExtraWindow).toHaveBeenCalledWith("#root/abc123");+ expect(open).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/components/entrypoints.ts b/apps/client/src/components/entrypoints.tsindex ea6551775f..e17976103e 100644--- a/apps/client/src/components/entrypoints.ts+++ b/apps/client/src/components/entrypoints.ts@@ -137,14 +137,12 @@ export default class Entrypoints extends Component {}async openInWindowCommand({ notePath, hoistedNoteId, viewScope }: NoteCommandData) {- const extraWindowHash = linkService.calculateHash({ notePath, hoistedNoteId, viewScope });+ const target = { notePath, hoistedNoteId, viewScope };if (window.electronApi) {- window.electronApi.window.createExtraWindow(extraWindowHash);+ window.electronApi.window.createExtraWindow(linkService.calculateHash(target));} else {- const url = `${window.location.protocol}//${window.location.host}${window.location.pathname}?extraWindow=1${extraWindowHash}`;-- window.open(url, "", "width=1000,height=800");+ window.open(linkService.calculateExtraWindowUrl(target), "", "width=1000,height=800");}}diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.tsindex 4ffadeb15a..d47e390f6b 100644--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@ -59,6 +59,7 @@ import { buildNote } from "../test/easy-froca";import froca from "./froca.js";import treeService from "./tree.js";import linkService, {+ calculateExtraWindowUrl,calculateHash,goToLinkExt,parseNavigationStateFromUrl@@ -96,6 +97,13 @@ describe("parseNavigationStateFromUrl", () => {expect(output).toMatchObject({ notePath: "root/QZGqKB7wVZF8", noteId: "QZGqKB7wVZF8" });});+ it("parses notePath when extraWindow is not the first query parameter", () => {+ // Standalone carries its environment in the query, so `extraWindow` is not necessarily+ // the parameter right after the `?`.+ const output = parseNavigationStateFromUrl(`127.0.0.1:8080/?safeMode=1&extraWindow=1#root/QZGqKB7wVZF8`);+ expect(output).toMatchObject({ notePath: "root/QZGqKB7wVZF8", noteId: "QZGqKB7wVZF8" });+ });+it("ignores external URL with internal hash anchor", () => {const output = parseNavigationStateFromUrl(`https://en.wikipedia.org/wiki/Bearded_Collie#Health`);expect(output).toMatchObject({});@@ -175,6 +183,46 @@ describe("calculateHash", () => {});});+describe("calculateExtraWindowUrl", () => {+ it("marks the window as extra and appends the target hash", () => {+ const url = calculateExtraWindowUrl({ notePath: "root/abc123" }, new URL("http://localhost:8080/"));+ expect(url).toBe("http://localhost:8080/?extraWindow=1#root/abc123");+ });++ it("keeps the deployment sub-path, so a standalone build under a prefix still resolves", () => {+ const url = calculateExtraWindowUrl({ notePath: "root/abc123" }, new URL("https://notes.test/trilium/"));+ expect(url).toBe("https://notes.test/trilium/?extraWindow=1#root/abc123");+ });++ it("carries the current query string over instead of replacing it", () => {+ // In standalone the query *is* the environment (`?safeMode`, `?startNoteId` — see+ // QUERY_TO_ENV in the standalone platform provider). A window that dropped it would boot+ // with different settings than the one it was torn from, and would apply those to every+ // other window once it inherited the database lock.+ const url = calculateExtraWindowUrl({ notePath: "root/abc123" }, new URL("http://localhost:8080/?safeMode=1"));+ const { searchParams } = new URL(url);+ expect(searchParams.get("safeMode")).toBe("1");+ expect(searchParams.get("extraWindow")).toBe("1");+ });++ it("produces a URL the receiving window can still navigate from", () => {+ const url = calculateExtraWindowUrl(+ { notePath: "root/abc123", hoistedNoteId: "h1" },+ new URL("http://localhost:8080/?safeMode=1")+ );+ expect(parseNavigationStateFromUrl(url)).toMatchObject({+ notePath: "root/abc123",+ noteId: "abc123",+ hoistedNoteId: "h1"+ });+ });++ it("omits the hash when there is no target, as when opening a blank window", () => {+ const url = calculateExtraWindowUrl({ notePath: "", hoistedNoteId: "root" }, new URL("http://localhost:8080/"));+ expect(url).toBe("http://localhost:8080/?extraWindow=1");+ });+});+describe("getNotePathFromUrl", () => {it("extracts the note path from a hash url and returns null otherwise", () => {expect(linkService.getNotePathFromUrl("https://x.test/#root/abc_123")).toBe("root/abc_123");diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex 0fd38c7b38..e6ee43d69d 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -230,6 +230,35 @@ export function calculateHash({ notePath, ntxId, hoistedNoteId, viewScope = {} }return hash;}+/** The subset of `window.location` needed to build a URL, which a plain `URL` also satisfies. */+interface UrlParts {+ protocol: string;+ host: string;+ pathname: string;+ search: string;+}++/**+ * Builds the address of a detached ("extra") window showing the given target.+ *+ * The current query string is carried over rather than replaced. On the server it holds nothing of+ * interest, but in standalone the query *is* the environment (`?safeMode`, `?startNoteId` — see+ * `QUERY_TO_ENV` in the standalone platform provider), so a window that dropped it would boot with+ * different settings than the one it was opened from, and would apply those to every other window+ * should it later inherit the database lock.+ */+export function calculateExtraWindowUrl(target: NoteCommandData, location: UrlParts = window.location) {+ const params = new URLSearchParams(location.search);+ params.set("extraWindow", "1");++ return `${location.protocol}//${location.host}${location.pathname}?${params}${calculateHash(target)}`;+}++/** Whether the query string of `url` (everything before `hashIdx`) carries the `extraWindow` marker. */+function isExtraWindowUrl(url: string, hashIdx: number) {+ return /[?&]extraWindow(?:[=&]|$)/.test(url.slice(0, hashIdx));+}+export function parseNavigationStateFromUrl(url: string | undefined) {if (!url) {return {};@@ -242,7 +271,7 @@ export function parseNavigationStateFromUrl(url: string | undefined) {}// Exclude external links that contain #- if (hashIdx !== 0 && !url.includes("/#root") && !url.includes("/#?searchString") && !url.includes("/?extraWindow")) {+ if (hashIdx !== 0 && !url.includes("/#root") && !url.includes("/#?searchString") && !isExtraWindowUrl(url, hashIdx)) {return {};}@@ -572,5 +601,6 @@ export default {getReferenceLinkTitle,getReferenceLinkTitleSync,calculateHash,+ calculateExtraWindowUrl,parseNavigationStateFromUrl};diff --git a/apps/standalone/e2e/extra_window.spec.ts b/apps/standalone/e2e/extra_window.spec.tsnew file mode 100644index 0000000000..13ebf4c71c--- /dev/null+++ b/apps/standalone/e2e/extra_window.spec.ts@@ -0,0 +1,48 @@+import test, { expect, type Page } from "@playwright/test";++import App from "../../../packages/trilium-e2e/src/support/app";++/**+ * "Open in a new window" in standalone.+ *+ * A detached window is a plain second browser window on the same origin, so it is a follower in the+ * leader election: it has no worker of its own and reaches the database through the service worker,+ * exactly like a second tab. See leader_election.ts and multi_tab.spec.ts.+ *+ * What makes it more than a second tab is `?extraWindow`, which tells the client it does not own the+ * saved tab set. The standalone bootstrap used to report every window as the main one, so a detached+ * window restored the tab set of the window it came from and then wrote its own back over it.+ */+test("a tab copied to a new window opens on the same database, as a non-main window", async ({ context }) => {+ const app = new App(await context.newPage(), context);+ await app.goto();+ await app.goToNoteInNewTab("Empty text");+ await expect(app.currentNoteSplitTitle).toHaveValue(/Empty text/);++ // Driven through the real menu rather than the command, so the window is opened from within a+ // user gesture — `window.open()` off a synthetic call is a different code path in the browser.+ const tab = await app.getTab(0);+ await tab.click({ button: "right" });+ const [extraPage] = await Promise.all([+ context.waitForEvent("page"),+ app.page.locator("#context-menu-container").getByText("Copy this tab to a new window").click()+ ]);+ await extraPage.waitForLoadState("domcontentloaded");++ expect(new URL(extraPage.url()).searchParams.get("extraWindow")).toBe("1");++ // It must come up on the leader's database rather than an empty in-memory one, which it can only+ // do by proxying its API traffic through the service worker.+ const extraWindow = new App(extraPage, context);+ await expect(extraWindow.noteTree).toContainText("Trilium Integration Test");+ await expect(extraWindow.currentNoteSplitTitle).toHaveValue(/Empty text/);++ // ...and it must know it is not the main window, or it takes over the saved tab set.+ expect(await isMainWindow(extraPage)).toBe(false);+ expect(await isMainWindow(app.page)).toBe(true);+});++/** Reads the client's own view of whether it owns the saved tab set, as the bootstrap set it. */+function isMainWindow(page: Page) {+ return page.evaluate(() => (window as unknown as { glob: { isMainWindow: boolean } }).glob.isMainWindow);+}diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.tsindex bc1772c586..26bfc0a84d 100644--- a/apps/standalone/src/lightweight/browser_routes.spec.ts+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts@@ -50,6 +50,16 @@ describe("registerRoutes (real wiring)", () => {expect(typeof data.triliumVersion).toBe("string");});+ it("marks a plain window as the main one, and `?extraWindow` as a detached one", async () => {+ const main = parseJson((await router.dispatch("GET", "http://localhost/bootstrap")).body) as Record<string, unknown>;+ expect(main.isMainWindow).toBe(true);++ // The detached window must not restore or persist `openNoteContexts`, otherwise it+ // overwrites the tab set of the window it was opened from. See TabManager.+ const extra = parseJson((await router.dispatch("GET", "http://localhost/bootstrap?extraWindow=1")).body) as Record<string, unknown>;+ expect(extra.isMainWindow).toBe(false);+ });+it("returns the setup payload when the database is not initialized", async () => {vi.spyOn(sql_init, "isDbInitialized").mockReturnValue(false);const data = parseJson((await router.dispatch("GET", "http://localhost/bootstrap")).body) as Record<string, unknown>;diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.tsindex e085911500..f7bfb04359 100644--- a/apps/standalone/src/lightweight/browser_routes.ts+++ b/apps/standalone/src/lightweight/browser_routes.ts@@ -301,7 +301,8 @@ export function registerRoutes(router: BrowserRouter): void {apiRoute("get", "/api/system-checks", () => ({ isCpuArchMismatch: false }));}-function bootstrapRoute(): BootstrapDefinition {+/** The request as `apiRoute` hands it over: the Express-like wrapper, not the raw {@link BrowserRequest}. */+function bootstrapRoute(req: { query: Record<string, string | undefined> }): BootstrapDefinition {const assetPath = ".";const isDbInitialized = sql_init.isDbInitialized();@@ -309,7 +310,9 @@ function bootstrapRoute(): BootstrapDefinition {...getSharedBootstrapItems(assetPath, isDbInitialized),isDev: import.meta.env.DEV,isStandalone: true,- isMainWindow: true,+ // A window torn off into its own popup carries `?extraWindow`, same as on the server. It has+ // to be told, or it restores the saved tab set on load and then writes its own back over it.+ isMainWindow: !req.query.extraWindow,isElectron: false,hasNativeTitleBar: false,hasBackgroundEffects: false,