Skip to content

Build your personal knowledge base with Trilium Notes

fix(tabs): keep the splits when a tab moves to its own window

Elian Doran16df701bb563
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index e3cde2e1e7..2258cb846d 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -8,7 +8,7 @@ import bundleService from "../services/bundle.js";
import froca from "../services/froca.js";
import { initLocale, t } from "../services/i18n.js";
import keyboardActionsService from "../services/keyboard_actions.js";
-import linkService, { type ViewScope } from "../services/link.js";
+import linkService, { type HashPane, type ViewScope } from "../services/link.js";
import type LoadResults from "../services/load_results.js";
import type { CreateNoteOpts } from "../services/note_create.js";
import options from "../services/options.js";
@@ -76,6 +76,13 @@ export interface NoteCommandData extends CommandData {
notePath?: string | null;
hoistedNoteId?: string | null;
viewScope?: ViewScope;
+ /**
+ * Panes to open beside `notePath`, in order — how a tab moved or copied into a window of its own
+ * takes its splits along. Honoured only while booting a detached window.
+ */
+ splits?: HashPane[] | null;
+ /** Index into `[main pane, ...splits]` of the pane to focus. Defaults to the main pane. */
+ activeSplit?: number;
}
export interface ExecuteCommandData<T> extends CommandData {
diff --git a/apps/client/src/components/entrypoints.ts b/apps/client/src/components/entrypoints.ts
index e17976103e..e932f49f20 100644
--- a/apps/client/src/components/entrypoints.ts
+++ b/apps/client/src/components/entrypoints.ts
@@ -136,8 +136,8 @@ export default class Entrypoints extends Component {
utils.reloadFrontendApp("Switching to mobile version");
}
- async openInWindowCommand({ notePath, hoistedNoteId, viewScope }: NoteCommandData) {
- const target = { notePath, hoistedNoteId, viewScope };
+ async openInWindowCommand({ notePath, hoistedNoteId, viewScope, splits, activeSplit }: NoteCommandData) {
+ const target = { notePath, hoistedNoteId, viewScope, splits, activeSplit };
if (window.electronApi) {
window.electronApi.window.createExtraWindow(linkService.calculateHash(target));
diff --git a/apps/client/src/components/tab_manager.spec.ts b/apps/client/src/components/tab_manager.spec.ts
index 2efe84da33..441c7f74cf 100644
--- a/apps/client/src/components/tab_manager.spec.ts
+++ b/apps/client/src/components/tab_manager.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import TabManager from "./tab_manager.js";
+import TabManager, { buildNoteContextStatesFromUrl } from "./tab_manager.js";
describe("TabManager tab placement", () => {
it("opens a blank tab at the end of the row, regardless of which tab is active", async () => {
@@ -56,6 +56,98 @@ describe("TabManager tab placement", () => {
});
});
+describe("moving a tab with splits into a window of its own", () => {
+ it("captures every pane of the tab, in order, and which one is focused", async () => {
+ const tm = new TabManager();
+ const [main, other] = await openEmptyTabs(tm, 2);
+ const split1 = await tm.openEmptyTab(null, "root", main.ntxId);
+ const split2 = await tm.openEmptyTab(null, "root", main.ntxId);
+
+ main.notePath = "root/aaaaaaaaaaaa";
+ split1.notePath = "root/bbbbbbbbbbbb";
+ split1.viewScope = { viewMode: "source" };
+ split2.notePath = "root/cccccccccccc";
+ split2.hoistedNoteId = "h1";
+ other.notePath = "root/dddddddddddd"; // a neighbouring tab must not come along
+ main.lastActiveNtxId = split2.ntxId; // the last of the three panes had the focus
+
+ expect(tm.captureTabAsWindowTarget(main.ntxId ?? "")).toEqual({
+ notePath: "root/aaaaaaaaaaaa",
+ hoistedNoteId: "root",
+ viewScope: {},
+ splits: [
+ { notePath: "root/bbbbbbbbbbbb", hoistedNoteId: "root", viewScope: { viewMode: "source" } },
+ { notePath: "root/cccccccccccc", hoistedNoteId: "h1", viewScope: {} }
+ ],
+ activeSplit: 2
+ });
+ });
+
+ it("falls back to the main pane, and gives up once the tab is gone", async () => {
+ const tm = new TabManager();
+ const [main] = await openEmptyTabs(tm, 1);
+ await tm.openEmptyTab(null, "root", main.ntxId);
+ main.lastActiveNtxId = "vanished"; // remembered pane was closed since
+
+ expect(tm.captureTabAsWindowTarget(main.ntxId ?? "")).toMatchObject({ activeSplit: 0 });
+
+ // the tear-off fires from dragMove, so a second call for an already-removed tab is expected
+ expect(tm.captureTabAsWindowTarget("gone")).toBeNull();
+ });
+});
+
+describe("buildNoteContextStatesFromUrl", () => {
+ it("rebuilds the panes as one tab, with the focused one active", () => {
+ const states = buildNoteContextStatesFromUrl({
+ notePath: "root/aaaaaaaaaaaa",
+ splits: [
+ { notePath: "root/bbbbbbbbbbbb", viewScope: { viewMode: "source" } },
+ { notePath: null, hoistedNoteId: "h1" }
+ ],
+ activeSplit: 1
+ }, "main1");
+
+ expect(states).toMatchObject([
+ { notePath: "root/aaaaaaaaaaaa", ntxId: "main1", mainNtxId: null, active: false },
+ {
+ notePath: "root/bbbbbbbbbbbb",
+ mainNtxId: "main1",
+ active: true,
+ hoistedNoteId: "root",
+ viewScope: { viewMode: "source" }
+ },
+ // a pane torn off empty stays empty rather than falling back to root
+ { notePath: null, mainNtxId: "main1", active: false, hoistedNoteId: "h1" }
+ ]);
+ // the splits get ids of their own, and the tab remembers which of them held the focus
+ expect(new Set(states.map((s) => s.ntxId)).size).toBe(3);
+ expect(states[0].lastActiveNtxId).toBe(states[1].ntxId);
+ });
+
+ it("opens root for a bare address, and ignores an active index pointing nowhere", () => {
+ expect(buildNoteContextStatesFromUrl({}, "main1")).toMatchObject([
+ { notePath: "root", ntxId: "main1", mainNtxId: null, active: true }
+ ]);
+
+ // activeSplit arrives from the address bar, so it may be out of range in either direction
+ const states = buildNoteContextStatesFromUrl(
+ { notePath: "root/aaaaaaaaaaaa", splits: [{ notePath: "root/bbbb" }], activeSplit: 9 },
+ "main1"
+ );
+ expect(states.map((s) => s.active)).toEqual([false, true]);
+ expect(buildNoteContextStatesFromUrl({ activeSplit: -3 }, "main1")[0].active).toBe(true);
+ });
+
+ it("focuses a pane with a note, since an empty one would leave the window with none", () => {
+ const states = buildNoteContextStatesFromUrl(
+ { notePath: null, splits: [{ notePath: "root/bbbbbbbbbbbb" }], activeSplit: 0 },
+ "main1"
+ );
+
+ expect(states.map((s) => s.active)).toEqual([false, true]);
+ });
+});
+
function openEmptyTabs(tm: TabManager, count: number) {
return Promise.all(Array.from({ length: count }, () => tm.openEmptyTab()));
}
diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.ts
index 11e5e42fd3..d4688f1604 100644
--- a/apps/client/src/components/tab_manager.ts
+++ b/apps/client/src/components/tab_manager.ts
@@ -9,7 +9,7 @@ import appContext from "./app_context.js";
import Mutex from "../utils/mutex.js";
import linkService from "../services/link.js";
import { partitionPinnedFirst } from "../services/tab_pinning.js";
-import type { EventData } from "./app_context.js";
+import type { EventData, NoteCommandData } from "./app_context.js";
import type FNote from "../entities/fnote.js";
/** Where a newly created tab is inserted in the row: appended to the end, or right after the active tab. */
@@ -20,7 +20,7 @@ interface TabState {
position: number;
}
-interface NoteContextState {
+export interface NoteContextState {
ntxId: string;
mainNtxId: string | null;
notePath: string | null;
@@ -102,13 +102,9 @@ export default class TabManager extends Component {
if (filteredNoteContexts.length === 0) {
parsedFromUrl.ntxId = parsedFromUrl.ntxId || NoteContext.generateNtxId(); // generate already here, so that we later know which one to activate
- filteredNoteContexts.push({
- notePath: parsedFromUrl.notePath || "root",
- ntxId: parsedFromUrl.ntxId,
- active: true,
- hoistedNoteId: parsedFromUrl.hoistedNoteId || "root",
- viewScope: parsedFromUrl.viewScope || {}
- });
+ filteredNoteContexts.push(
+ ...buildNoteContextStatesFromUrl(parsedFromUrl, parsedFromUrl.ntxId)
+ );
} else if (!filteredNoteContexts.find((tab: NoteContextState) => tab.active)) {
filteredNoteContexts[0].active = true;
}
@@ -133,7 +129,9 @@ export default class TabManager extends Component {
// if there's a notePath in the URL, make sure it's open and active
// (useful, for e.g., opening clipped notes from clipper or opening link in an extra window)
- if (parsedFromUrl.notePath) {
+ // Splits are skipped: the panes were just built from this very URL, with the
+ // intended one focused, so switching would only pull focus back to the first pane.
+ if (parsedFromUrl.notePath && !parsedFromUrl.splits?.length) {
await appContext.tabManager.switchToNoteContext(
parsedFromUrl.ntxId,
parsedFromUrl.notePath,
@@ -744,18 +742,57 @@ export default class TabManager extends Component {
}
async moveTabToNewWindowCommand({ ntxId }: { ntxId: string }) {
- const { notePath, hoistedNoteId, viewScope } = this.getNoteContextById(ntxId);
+ // capture before removing: closing the tab takes its split panes down with it
+ const target = this.captureTabAsWindowTarget(ntxId);
- const removed = await this.removeNoteContext(ntxId);
-
- if (removed) {
- this.triggerCommand("openInWindow", { notePath, hoistedNoteId, viewScope });
+ if (target && await this.removeNoteContext(ntxId)) {
+ this.triggerCommand("openInWindow", target);
}
}
async copyTabToNewWindowCommand({ ntxId }: { ntxId: string }) {
- const { notePath, hoistedNoteId, viewScope } = this.getNoteContextById(ntxId);
- this.triggerCommand("openInWindow", { notePath, hoistedNoteId, viewScope });
+ const target = this.captureTabAsWindowTarget(ntxId);
+
+ if (target) {
+ this.triggerCommand("openInWindow", target);
+ }
+ }
+
+ /** Every pane of one tab — its main context and the splits beside it — in row order. */
+ getTabPanes(mainNtxId: string | null) {
+ return this.noteContexts.filter((nc) =>
+ nc.ntxId === mainNtxId || nc.mainNtxId === mainNtxId);
+ }
+
+ /**
+ * Describes a whole tab — every split pane in order, and which of them is focused — as a target
+ * for `openInWindow`.
+ *
+ * Returns `null` when the tab is already gone. The tear-off drag fires from `dragMove`,
+ * which can deliver several events before the first removal completes, so a second call for
+ * the same tab is expected rather than exceptional.
+ */
+ captureTabAsWindowTarget(ntxId: string): NoteCommandData | null {
+ const mainContext = this.noteContexts.find((nc) => nc.ntxId === ntxId);
+
+ if (!mainContext) {
+ return null;
+ }
+
+ const panes = this.getTabPanes(ntxId);
+ const splits = panes.filter((nc) => nc.ntxId !== mainContext.ntxId);
+
+ return {
+ notePath: mainContext.notePath,
+ hoistedNoteId: mainContext.hoistedNoteId,
+ viewScope: mainContext.viewScope,
+ splits: splits.map((nc) => ({
+ notePath: nc.notePath,
+ hoistedNoteId: nc.hoistedNoteId,
+ viewScope: nc.viewScope
+ })),
+ activeSplit: Math.max(panes.indexOf(getFocusedPane(mainContext, panes)), 0)
+ };
}
async reopenLastTabCommand() {
@@ -889,3 +926,61 @@ export default class TabManager extends Component {
}
}
}
+
+/**
+ * The pane holding the focus within a tab: the one remembered as last active if it is still open,
+ * otherwise the main pane — the same choice activating the tab would make.
+ */
+function getFocusedPane(mainContext: NoteContext, panes: NoteContext[]) {
+ return panes.find((nc) => nc.ntxId === mainContext.lastActiveNtxId) ?? mainContext;
+}
+
+/**
+ * Turns the navigation state parsed out of the address into the contexts to open at boot: the main
+ * pane, plus the split panes that a tab moved into a window of its own brought along with it.
+ */
+export function buildNoteContextStatesFromUrl(
+ parsed: NoteCommandData,
+ mainNtxId: string
+): NoteContextState[] {
+ const panes = [
+ {
+ notePath: parsed.notePath,
+ hoistedNoteId: parsed.hoistedNoteId,
+ viewScope: parsed.viewScope
+ },
+ ...(parsed.splits ?? [])
+ ];
+ // a bare boot with nothing in the address lands on root, but a pane torn off empty stays empty
+ const notePaths = panes.map((pane) => pane.notePath || (panes.length === 1 ? "root" : null));
+ const activeIdx = pickActivePane(notePaths, parsed.activeSplit ?? 0);
+
+ const states: NoteContextState[] = panes.map((pane, idx) => ({
+ notePath: notePaths[idx],
+ ntxId: idx === 0 ? mainNtxId : NoteContext.generateNtxId(),
+ mainNtxId: idx === 0 ? null : mainNtxId,
+ active: idx === activeIdx,
+ hoistedNoteId: pane.hoistedNoteId || "root",
+ viewScope: pane.viewScope || {}
+ }));
+
+ // so that leaving the tab and coming back returns to the pane that was focused
+ states[0].lastActiveNtxId = states[activeIdx].ntxId;
+
+ return states;
+}
+
+/**
+ * Which pane opens focused. The index comes off the address bar, so it is clamped into range; and
+ * because a pane holding no note never takes the focus anyway (`openContextWithNote` activates only
+ * once a note is set), an empty one hands over to the first pane that has one.
+ */
+function pickActivePane(notePaths: (string | null)[], requested: number) {
+ const clamped = Math.min(Math.max(requested, 0), notePaths.length - 1);
+
+ if (notePaths[clamped]) {
+ return clamped;
+ }
+
+ return Math.max(notePaths.findIndex((notePath) => !!notePath), 0);
+}
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.ts
index d47e390f6b..fa4dd8d364 100644
--- a/apps/client/src/services/link.spec.ts
+++ b/apps/client/src/services/link.spec.ts
@@ -223,6 +223,91 @@ describe("calculateExtraWindowUrl", () => {
});
});
+describe("split panes in the hash", () => {
+ const A = "root/aaaaaaaaaaaa";
+ const B = "root/bbbbbbbbbbbb";
+ const C = "root/cccccccccccc";
+
+ /** Wraps a bare hash in the address a detached window boots from. */
+ const asExtraWindowUrl = (hash: string) => `http://localhost:8080/?extraWindow=1${hash}`;
+
+ it("round-trips a tab's panes, keeping their order, hoisting and view scope", () => {
+ const hash = calculateHash({
+ notePath: A,
+ splits: [
+ { notePath: B, viewScope: { viewMode: "source" } },
+ { notePath: C, hoistedNoteId: "h1" }
+ ],
+ activeSplit: 1
+ });
+
+ // each pane is a hash body of its own, comma-joined and encoded as a single parameter
+ expect(hash).toBe(
+ `#${A}?splits=root%2Fbbbbbbbbbbbb%3FviewMode%3Dsource%2Croot%2Fcccccccccccc%3FhoistedNoteId%3Dh1&activeSplit=1`
+ );
+
+ expect(parseNavigationStateFromUrl(asExtraWindowUrl(hash))).toMatchObject({
+ notePath: A,
+ activeSplit: 1,
+ splits: [
+ { notePath: B, hoistedNoteId: null, viewScope: { viewMode: "source" } },
+ { notePath: C, hoistedNoteId: "h1", viewScope: { viewMode: "default" } }
+ ]
+ });
+ });
+
+ it("honours splits only when booting a detached window", () => {
+ // The same parser backs every link click inside a note. Were splits read there, any note —
+ // including an imported or synced one — could rearrange the panes of the window reading it.
+ const hash = calculateHash({ notePath: A, splits: [{ notePath: B }] });
+
+ expect(parseNavigationStateFromUrl(`http://localhost:8080/${hash}`)).toMatchObject({
+ notePath: A,
+ splits: null
+ });
+ });
+
+ it("keeps the layout of a tab whose first pane held no note", () => {
+ const hash = calculateHash({ notePath: null, splits: [{ notePath: B }] });
+
+ expect(hash).toBe("#?splits=root%2Fbbbbbbbbbbbb");
+ expect(parseNavigationStateFromUrl(asExtraWindowUrl(hash))).toMatchObject({
+ notePath: "",
+ noteId: null,
+ splits: [{ notePath: B }]
+ });
+
+ // without splits an empty note path still means "nothing to navigate to"
+ expect(parseNavigationStateFromUrl(asExtraWindowUrl("#"))).toStrictEqual({});
+ });
+
+ it("keeps empty panes, drops malformed ones and caps how many it will open", () => {
+ const parse = (splits: string) =>
+ parseNavigationStateFromUrl(asExtraWindowUrl(`#${A}?splits=${splits}`));
+
+ // an empty entry is a pane that held no note — kept, so the pane count survives
+ expect(parse(encodeURIComponent(`${B},,${C}`))).toMatchObject({
+ splits: [{ notePath: B }, { notePath: null }, { notePath: C }]
+ });
+
+ // a hand-written address shouldn't be able to open a pane on garbage, nor hundreds of them
+ expect(parse(encodeURIComponent(`${B},zz,${C}`))).toMatchObject({
+ splits: [{ notePath: B }, { notePath: C }]
+ });
+ expect(parse(encodeURIComponent(Array(20).fill(B).join(",")))).toMatchObject({
+ splits: Array(8).fill({ notePath: B })
+ });
+ });
+
+ it("ignores parameters that describe a window rather than a pane", () => {
+ const nested = encodeURIComponent(`${B}?ntxId=n1&splits=${encodeURIComponent(C)}`);
+ const parsed = parseNavigationStateFromUrl(asExtraWindowUrl(`#${A}?splits=${nested}`));
+
+ expect(parsed).toMatchObject({ splits: [{ notePath: B, viewScope: { viewMode: "default" } }] });
+ expect((parsed as any).splits[0]).not.toHaveProperty("ntxId");
+ });
+});
+
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.ts
index e6ee43d69d..cd9cdb5e8c 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -72,6 +72,28 @@ export interface ViewScope {
bookmark?: string;
}
+/**
+ * The state of a single split pane, as carried by the `splits` hash parameter when a tab is
+ * moved or copied into a window of its own.
+ */
+export interface HashPane {
+ notePath?: string | null;
+ hoistedNoteId?: string | null;
+ viewScope?: ViewScope;
+}
+
+/** A note path as it may appear in a hash: slash-separated note ids. */
+const NOTE_PATH_PATTERN = /^[_a-z0-9]{4,}(\/[_a-z0-9]{4,})*$/i;
+
+/**
+ * How many extra panes a hash is allowed to carry. Well beyond any layout a user would build by
+ * hand, but low enough that a hand-written address can't ask the app to open hundreds of panes.
+ */
+const MAX_SPLIT_PANES_IN_HASH = 8;
+
+/** Hash parameters that belong to a pane's view scope rather than to the window as a whole. */
+const VIEW_SCOPE_PARAMS = ["viewMode", "attachmentId", "bookmark"];
+
interface CreateLinkOptions {
title?: string;
showTooltip?: boolean;
@@ -198,13 +220,17 @@ async function createLink(notePath: string | undefined, options: CreateLinkOptio
return $container;
}
-export function calculateHash({ notePath, ntxId, hoistedNoteId, viewScope = {} }: NoteCommandData) {
+export function calculateHash(
+ { notePath, ntxId, hoistedNoteId, viewScope = {}, splits, activeSplit }: NoteCommandData
+) {
notePath = notePath || "";
const params = [
ntxId ? { ntxId } : null,
hoistedNoteId && hoistedNoteId !== "root" ? { hoistedNoteId } : null,
viewScope.viewMode && viewScope.viewMode !== "default" ? { viewMode: viewScope.viewMode } : null,
- viewScope.attachmentId ? { attachmentId: viewScope.attachmentId } : null
+ viewScope.attachmentId ? { attachmentId: viewScope.attachmentId } : null,
+ splits?.length ? { splits: splits.map(encodeSplitPane).join(",") } : null,
+ splits?.length && activeSplit ? { activeSplit: String(activeSplit) } : null
].filter((p) => !!p);
const paramStr = params
@@ -212,7 +238,8 @@ export function calculateHash({ notePath, ntxId, hoistedNoteId, viewScope = {} }
const name = Object.keys(pair)[0];
const value = (pair as Record<string, string | undefined>)[name];
- /* v8 ignore next -- the `value || ""` fallback is unreachable: every retained param pair has a truthy value (falsy ones were filtered out above) */
+ /* v8 ignore next -- `value` is never undefined: every retained pair holds a string. It
+ can be empty, but only for a `splits` list whose panes are all empty. */
return `${encodeURIComponent(name)}=${encodeURIComponent(value || "")}`;
})
.join("&");
@@ -230,6 +257,16 @@ export function calculateHash({ notePath, ntxId, hoistedNoteId, viewScope = {} }
return hash;
}
+/**
+ * Serializes one extra pane into an entry of the `splits` parameter: its own hash body, minus the
+ * leading `#`. Entries are joined with commas, which is unambiguous because neither a note path nor
+ * an encoded parameter value can contain one. A pane holding no note yields an empty entry, so that
+ * the pane count of the original tab survives the trip.
+ */
+function encodeSplitPane(pane: HashPane) {
+ return calculateHash(pane).slice(1);
+}
+
/** The subset of `window.location` needed to build a URL, which a plain `URL` also satisfies. */
interface UrlParts {
protocol: string;
@@ -270,8 +307,10 @@ export function parseNavigationStateFromUrl(url: string | undefined) {
return {};
}
+ const isExtraWindow = isExtraWindowUrl(url, hashIdx);
+
// Exclude external links that contain #
- if (hashIdx !== 0 && !url.includes("/#root") && !url.includes("/#?searchString") && !isExtraWindowUrl(url, hashIdx)) {
+ if (hashIdx !== 0 && !url.includes("/#root") && !url.includes("/#?searchString") && !isExtraWindow) {
return {};
}
@@ -285,26 +324,29 @@ export function parseNavigationStateFromUrl(url: string | undefined) {
let hoistedNoteId: string | null = null;
let searchString: string | null = null;
let openInPopup = false;
-
- if (paramString) {
- for (const pair of paramString.split("&")) {
- let [name, value] = pair.split("=");
- name = decodeURIComponent(name);
- value = decodeURIComponent(value);
-
- if (name === "ntxId") {
- ntxId = value;
- } else if (name === "hoistedNoteId") {
- hoistedNoteId = value;
- } else if (name === "searchString") {
- searchString = value; // supports triggering search from URL, e.g. #?searchString=blabla
- } else if (["viewMode", "attachmentId", "bookmark"].includes(name)) {
- (viewScope as any)[name] = value;
- } else if (name === "popup") {
- openInPopup = true;
- } else {
- console.warn(`Unrecognized hash parameter '${name}'.`);
- }
+ let splits: HashPane[] | null = null;
+ let activeSplit = 0;
+
+ for (const [name, value] of parseHashParams(paramString)) {
+ if (name === "ntxId") {
+ ntxId = value;
+ } else if (name === "hoistedNoteId") {
+ hoistedNoteId = value;
+ } else if (name === "searchString") {
+ searchString = value; // supports triggering search from URL, e.g. #?searchString=blabla
+ } else if (VIEW_SCOPE_PARAMS.includes(name)) {
+ (viewScope as any)[name] = value;
+ } else if (name === "popup") {
+ openInPopup = true;
+ } else if (name === "splits") {
+ // Splits lay out the whole window, so they are honoured only while booting a
+ // detached one. A link inside a note reaches this same parser, and no note should
+ // be able to rearrange the panes of the window it is read in.
+ splits = isExtraWindow ? parseSplitPanes(value) : null;
+ } else if (name === "activeSplit") {
+ activeSplit = Number.parseInt(value, 10) || 0;
+ } else {
+ console.warn(`Unrecognized hash parameter '${name}'.`);
}
}
@@ -312,7 +354,11 @@ export function parseNavigationStateFromUrl(url: string | undefined) {
return { searchString };
}
- if (!notePath.match(/^[_a-z0-9]{4,}(\/[_a-z0-9]{4,})*$/i)) {
+ // A hash carrying splits is one we wrote ourselves, so its main pane may hold no note —
+ // that is how a tab whose first pane was empty keeps the rest of its panes.
+ const isEmptyMainPaneWithSplits = !notePath && !!splits?.length;
+
+ if (!isEmptyMainPaneWithSplits && !NOTE_PATH_PATTERN.test(notePath)) {
return {};
}
@@ -323,10 +369,65 @@ export function parseNavigationStateFromUrl(url: string | undefined) {
hoistedNoteId,
viewScope,
searchString,
- openInPopup
+ openInPopup,
+ splits,
+ activeSplit
};
}
+/** Iterates the `name=value` pairs of a hash's parameter string, decoding both sides. */
+function parseHashParams(paramString: string | undefined) {
+ if (!paramString) {
+ return [];
+ }
+
+ return paramString.split("&").map((pair) => {
+ const [name, value] = pair.split("=");
+
+ return [decodeURIComponent(name), decodeURIComponent(value ?? "")] as const;
+ });
+}
+
+/**
+ * Parses the `splits` parameter — the panes that stood beside the main one, in order. Entries that
+ * aren't a well-formed pane are dropped rather than failing the whole hash, so a mangled address
+ * still opens what it can.
+ */
+function parseSplitPanes(value: string): HashPane[] {
+ return value
+ .split(",")
+ .slice(0, MAX_SPLIT_PANES_IN_HASH)
+ .map(parseSplitPane)
+ .filter((pane) => !!pane);
+}
+
+function parseSplitPane(entry: string): HashPane | null {
+ const [notePath, paramString] = entry.split("?");
+
+ // An empty entry is a pane that held no note; anything else has to be a real note path.
+ if (notePath && !NOTE_PATH_PATTERN.test(notePath)) {
+ return null;
+ }
+
+ const pane: HashPane = {
+ notePath: notePath || null,
+ hoistedNoteId: null,
+ viewScope: { viewMode: "default" }
+ };
+
+ for (const [name, paramValue] of parseHashParams(paramString)) {
+ if (name === "hoistedNoteId") {
+ pane.hoistedNoteId = paramValue;
+ } else if (VIEW_SCOPE_PARAMS.includes(name)) {
+ (pane.viewScope as any)[name] = paramValue;
+ }
+ // Everything else — `ntxId`, `searchString`, a nested `splits` — describes a window rather
+ // than a pane, and has no meaning this far down.
+ }
+
+ return pane;
+}
+
/**
* Interactive content that handles its own clicks opts out of link navigation by carrying this class. It is
* needed where such content sits inside a link — a media player in a collection card, whose card is itself a