Skip to content

Build your personal knowledge base with Trilium Notes

client/tab bar: add support for pinned tabs

Adorian Doran923986eca8de
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index 257d0b7893..beeb68da83 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -263,6 +263,8 @@ export type CommandMappings = {
closeOtherTabs: CommandData;
closeRightTabs: CommandData;
closeAllTabs: CommandData;
+ pinTab: CommandData;
+ unpinTab: CommandData;
reopenLastTab: CommandData;
moveTabToNewWindow: CommandData;
copyTabToNewWindow: CommandData;
@@ -498,6 +500,10 @@ type EventMappings = {
tabReorder: {
ntxIdsInOrder: string[];
};
+ tabPinStateChanged: {
+ ntxId: string | null;
+ pinned: boolean;
+ };
refreshNoteList: {
noteId: string;
};
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.ts
index 4a5a65c265..1023054d14 100644
--- a/apps/client/src/components/note_context.ts
+++ b/apps/client/src/components/note_context.ts
@@ -9,6 +9,7 @@ import type { ViewScope } from "../services/link.js";
import options from "../services/options.js";
import protectedSessionHolder from "../services/protected_session_holder.js";
import server from "../services/server.js";
+import { shouldRedirectPinnedNavigation } from "../services/tab_pinning.js";
import treeService from "../services/tree.js";
import utils from "../services/utils.js";
import { ReactWrappedWidget } from "../widgets/basic_widget.js";
@@ -68,6 +69,9 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
hoistedNoteId: string;
mainNtxId: string | null;
+ /** When true, this tab stays on its current note: navigations to a different note open a new tab instead. Only meaningful on a main context. */
+ pinned = false;
+
notePath?: string | null;
noteId?: string | null;
parentNoteId?: string | null;
@@ -131,6 +135,17 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
return;
}
+ // Pinned tabs stay on the note they were pinned to — redirect navigation to a new tab instead.
+ const { noteId: targetNoteId } = treeService.getNoteIdAndParentIdFromUrl(resolvedNotePath);
+ if (shouldRedirectPinnedNavigation(this.pinned, this.noteId, targetNoteId)) {
+ await appContext.tabManager.openContextWithNote(resolvedNotePath, {
+ activate: true,
+ viewScope: opts.viewScope,
+ hoistedNoteId: this.hoistedNoteId
+ });
+ return;
+ }
+
await this.triggerEvent("beforeNoteSwitch", { noteContext: this });
if (!opts.keepActiveDialog) {
@@ -290,7 +305,8 @@ class NoteContext extends Component implements EventListener<"entitiesReloaded">
notePath: this.notePath,
hoistedNoteId: this.hoistedNoteId,
active: this.isActive(),
- viewScope: this.viewScope
+ viewScope: this.viewScope,
+ pinned: this.pinned
};
}
diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.ts
index 3cf06a7793..c5d87b41a5 100644
--- a/apps/client/src/components/tab_manager.ts
+++ b/apps/client/src/components/tab_manager.ts
@@ -8,6 +8,7 @@ import NoteContext from "./note_context.js";
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 FNote from "../entities/fnote.js";
@@ -23,6 +24,7 @@ interface NoteContextState {
hoistedNoteId: string;
active: boolean;
viewScope: Record<string, any>;
+ pinned?: boolean;
}
export default class TabManager extends Component {
@@ -114,7 +116,8 @@ export default class TabManager extends Component {
ntxId: tab.ntxId,
mainNtxId: tab.mainNtxId,
hoistedNoteId: tab.hoistedNoteId,
- viewScope: tab.viewScope
+ viewScope: tab.viewScope,
+ pinned: tab.pinned
});
}
});
@@ -262,9 +265,12 @@ export default class TabManager extends Component {
async openEmptyTab(
ntxId: string | null = null,
hoistedNoteId: string = "root",
- mainNtxId: string | null = null
+ mainNtxId: string | null = null,
+ pinned: boolean = false
): Promise<NoteContext> {
const noteContext = new NoteContext(ntxId, hoistedNoteId, mainNtxId);
+ // set before setEmpty/newNoteContextCreated so the tab renders in its pinned state from the start
+ noteContext.pinned = pinned;
noteContext.setEmpty();
const existingNoteContext = this.children.find((nc) => nc.ntxId === noteContext.ntxId);
@@ -337,6 +343,7 @@ export default class TabManager extends Component {
mainNtxId?: string | null;
hoistedNoteId?: string | null;
viewScope?: Record<string, any> | null;
+ pinned?: boolean | null;
} = {}
): Promise<NoteContext> {
const activate = !!opts.activate;
@@ -345,7 +352,7 @@ export default class TabManager extends Component {
const hoistedNoteId = opts.hoistedNoteId || "root";
const viewScope = opts.viewScope || { viewMode: "default" };
- const noteContext = await this.openEmptyTab(ntxId, hoistedNoteId, mainNtxId);
+ const noteContext = await this.openEmptyTab(ntxId, hoistedNoteId, mainNtxId, !!opts.pinned);
if (notePath) {
await noteContext.setNote(notePath, {
// if activate is false, then send normal noteSwitched event
@@ -414,6 +421,12 @@ export default class TabManager extends Component {
return false;
}
+ if (noteContextToRemove.isMainContext() && noteContextToRemove.pinned) {
+ // pinned tabs can't be closed — they must be unpinned first. This single guard also
+ // makes Ctrl-W, middle-click and the bulk "close others/right/all" commands skip them.
+ return false;
+ }
+
if (noteContextToRemove.isMainContext()) {
const mainNoteContexts = this.getNoteContexts().filter((nc) => nc.isMainContext());
@@ -564,6 +577,44 @@ export default class TabManager extends Component {
await this.removeNoteContext(this.activeNtxId);
}
+ async pinTabCommand({ ntxId }: { ntxId: string }) {
+ await this.setTabPinned(ntxId, true);
+ }
+
+ async unpinTabCommand({ ntxId }: { ntxId: string }) {
+ await this.setTabPinned(ntxId, false);
+ }
+
+ async setTabPinned(ntxId: string | null, pinned: boolean) {
+ let mainContext: NoteContext;
+ try {
+ mainContext = this.getNoteContextById(ntxId).getMainContext();
+ } catch {
+ return;
+ }
+
+ // can't pin an empty tab (nothing to lock onto); unpinning is always allowed
+ if (pinned && mainContext.isEmpty()) {
+ return;
+ }
+
+ if (mainContext.pinned === pinned) {
+ return;
+ }
+
+ mainContext.pinned = pinned;
+ this.reorderPinnedFirst();
+
+ await this.triggerEvent("tabPinStateChanged", { ntxId: mainContext.ntxId, pinned });
+ this.tabsUpdate.scheduleUpdate();
+ }
+
+ /** Keeps pinned tabs (with their splits) grouped at the front of the context list. */
+ reorderPinnedFirst() {
+ const orderedMain = partitionPinnedFirst(this.mainNoteContexts, (nc) => nc.pinned);
+ this.children = orderedMain.flatMap((main) => main.getSubContexts());
+ }
+
beforeUnloadEvent(): boolean {
this.tabsUpdate.updateNowIfNecessary();
return true; // don't block closing the tab, this metadata is not that important
@@ -724,6 +775,17 @@ export default class TabManager extends Component {
}
async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
+ // Auto-unpin tabs whose note was deleted, otherwise they'd get stuck (pinned tabs can't be
+ // closed). Collected synchronously up-front, before the per-context handlers clear noteId.
+ const deletedPinnedNtxIds = this.mainNoteContexts
+ .filter((nc) => nc.pinned && nc.noteId && loadResults.isNoteReloaded(nc.noteId)
+ && loadResults.getEntityRow("notes", nc.noteId)?.isDeleted)
+ .map((nc) => nc.ntxId);
+
+ for (const ntxId of deletedPinnedNtxIds) {
+ await this.setTabPinned(ntxId, false);
+ }
+
const activeContext = this.getActiveContext();
if (activeContext && loadResults.isNoteReloaded(activeContext.noteId)) {
diff --git a/apps/client/src/services/tab_pinning.spec.ts b/apps/client/src/services/tab_pinning.spec.ts
new file mode 100644
index 0000000000..6e4b65025e
--- /dev/null
+++ b/apps/client/src/services/tab_pinning.spec.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+
+import { clampDragDestination, partitionPinnedFirst, shouldRedirectPinnedNavigation } from "./tab_pinning.js";
+
+describe("shouldRedirectPinnedNavigation", () => {
+ it("redirects only when a pinned tab with a note navigates to a different note", () => {
+ expect(shouldRedirectPinnedNavigation(true, "noteA", "noteB")).toBe(true);
+ });
+
+ it("allows staying on the same note (e.g. view-scope change)", () => {
+ expect(shouldRedirectPinnedNavigation(true, "noteA", "noteA")).toBe(false);
+ });
+
+ it("allows the first load when the context has no note yet", () => {
+ expect(shouldRedirectPinnedNavigation(true, null, "noteA")).toBe(false);
+ expect(shouldRedirectPinnedNavigation(true, undefined, "noteA")).toBe(false);
+ });
+
+ it("never redirects an unpinned tab", () => {
+ expect(shouldRedirectPinnedNavigation(false, "noteA", "noteB")).toBe(false);
+ expect(shouldRedirectPinnedNavigation(undefined, "noteA", "noteB")).toBe(false);
+ });
+
+ it("does not redirect when the target note cannot be resolved", () => {
+ expect(shouldRedirectPinnedNavigation(true, "noteA", null)).toBe(false);
+ expect(shouldRedirectPinnedNavigation(true, "noteA", undefined)).toBe(false);
+ });
+});
+
+describe("partitionPinnedFirst", () => {
+ const isPinned = (t: { id: string; pinned?: boolean }) => !!t.pinned;
+
+ it("moves pinned items to the front while keeping relative order in both groups", () => {
+ const items = [
+ { id: "a" },
+ { id: "b", pinned: true },
+ { id: "c" },
+ { id: "d", pinned: true }
+ ];
+
+ expect(partitionPinnedFirst(items, isPinned).map((t) => t.id)).toEqual(["b", "d", "a", "c"]);
+ });
+
+ it("is a no-op when nothing is pinned", () => {
+ const items = [{ id: "a" }, { id: "b" }, { id: "c" }];
+ expect(partitionPinnedFirst(items, isPinned).map((t) => t.id)).toEqual(["a", "b", "c"]);
+ });
+
+ it("keeps order when everything is pinned", () => {
+ const items = [{ id: "a", pinned: true }, { id: "b", pinned: true }];
+ expect(partitionPinnedFirst(items, isPinned).map((t) => t.id)).toEqual(["a", "b"]);
+ });
+
+ it("handles an empty list", () => {
+ expect(partitionPinnedFirst([], isPinned)).toEqual([]);
+ });
+});
+
+describe("clampDragDestination", () => {
+ // Layout: [pinned, pinned, normal, normal, normal] => pinnedCount = 2, total = 5
+ it("keeps a pinned tab inside the pinned zone", () => {
+ expect(clampDragDestination(4, true, 2, 5)).toBe(1); // can't leave the pinned zone
+ expect(clampDragDestination(0, true, 2, 5)).toBe(0);
+ expect(clampDragDestination(1, true, 2, 5)).toBe(1);
+ });
+
+ it("keeps an unpinned tab inside the unpinned zone", () => {
+ expect(clampDragDestination(0, false, 2, 5)).toBe(2); // can't enter the pinned zone
+ expect(clampDragDestination(3, false, 2, 5)).toBe(3);
+ expect(clampDragDestination(9, false, 2, 5)).toBe(4); // can't exceed the last index
+ });
+
+ it("handles the no-pinned-tabs case (whole row is the unpinned zone)", () => {
+ expect(clampDragDestination(0, false, 0, 3)).toBe(0);
+ expect(clampDragDestination(2, false, 0, 3)).toBe(2);
+ });
+});
diff --git a/apps/client/src/services/tab_pinning.ts b/apps/client/src/services/tab_pinning.ts
new file mode 100644
index 0000000000..6f69e724be
--- /dev/null
+++ b/apps/client/src/services/tab_pinning.ts
@@ -0,0 +1,46 @@
+/**
+ * Pure helpers for the pinned-tabs feature. Kept free of DOM/appContext dependencies so the
+ * decision logic can be unit-tested in isolation.
+ */
+
+/**
+ * Decides whether a navigation request on a context should be redirected into a new tab.
+ *
+ * A pinned tab stays on the note it was pinned to: any attempt to navigate it to a *different*
+ * note is redirected to a new tab instead. The first load (when the context has no note yet) and
+ * same-note view changes are always allowed.
+ */
+export function shouldRedirectPinnedNavigation(
+ pinned: boolean | undefined,
+ currentNoteId: string | null | undefined,
+ targetNoteId: string | null | undefined
+): boolean {
+ return !!pinned && !!currentNoteId && !!targetNoteId && currentNoteId !== targetNoteId;
+}
+
+/**
+ * Stable partition that moves pinned items to the front while preserving the relative order within
+ * the pinned and unpinned groups. This keeps pinned tabs grouped at the beginning of the tab row.
+ */
+export function partitionPinnedFirst<T>(items: T[], isPinned: (item: T) => boolean): T[] {
+ const pinned: T[] = [];
+ const unpinned: T[] = [];
+
+ for (const item of items) {
+ (isPinned(item) ? pinned : unpinned).push(item);
+ }
+
+ return [...pinned, ...unpinned];
+}
+
+/**
+ * Clamps a drag-and-drop destination index so a tab cannot cross the pinned/unpinned boundary:
+ * pinned tabs stay within `[0, pinnedCount - 1]`, unpinned tabs within `[pinnedCount, total - 1]`.
+ */
+export function clampDragDestination(destination: number, isPinned: boolean, pinnedCount: number, total: number): number {
+ if (isPinned) {
+ return Math.max(0, Math.min(destination, pinnedCount - 1));
+ }
+
+ return Math.max(pinnedCount, Math.min(destination, total - 1));
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 4fe7804c31..f0597c5fd6 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2001,6 +2001,8 @@
"close_other_tabs": "Close other tabs",
"close_right_tabs": "Close tabs to the right",
"close_all_tabs": "Close all tabs",
+ "pin_tab": "Pin tab",
+ "unpin_tab": "Unpin tab",
"reopen_last_tab": "Reopen last closed tab",
"move_tab_to_new_window": "Move this tab to a new window",
"copy_tab_to_new_window": "Copy this tab to a new window",
diff --git a/apps/client/src/widgets/tab_row.ts b/apps/client/src/widgets/tab_row.ts
index 21701de346..7c5a504f11 100644
--- a/apps/client/src/widgets/tab_row.ts
+++ b/apps/client/src/widgets/tab_row.ts
@@ -7,6 +7,7 @@ import attributeService from "../services/attributes.js";
import froca from "../services/froca.js";
import { t } from "../services/i18n.js";
import keyboardActionService from "../services/keyboard_actions.js";
+import { clampDragDestination } from "../services/tab_pinning.js";
import utils from "../services/utils.js";
import BasicWidget from "./basic_widget.js";
import { setupHorizontalScrollViaWheel } from "./widget_utils.js";
@@ -31,6 +32,7 @@ const TAB_TPL = `
<div class="note-tab-drag-handle"></div>
<div class="note-tab-icon"></div>
<div class="note-tab-title"></div>
+ <div class="note-tab-pin-indicator bx bx-pin" title="${t("tab_row.unpin_tab")}"></div>
<div class="note-tab-close bx bx-x" title="${t("tab_row.close_tab")}"></div>
</div>
</div>`;
@@ -194,6 +196,26 @@ const TAB_ROW_TPL = `
text-align: center;
}
+ .tab-row-widget .note-tab .note-tab-pin-indicator {
+ display: none;
+ flex: 0 0 22px;
+ width: 22px;
+ height: 22px;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ /* purely a visual indicator: clicks fall through to the tab so it activates, never unpins */
+ pointer-events: none;
+ }
+
+ .tab-row-widget .note-tab[pinned] .note-tab-pin-indicator {
+ display: flex;
+ }
+
+ .tab-row-widget .note-tab[pinned] .note-tab-close {
+ display: none;
+ }
+
.tab-scroll-button-left, .tab-scroll-button-right {
display: none;
flex: 0 0 ${SCROLL_BUTTON_WIDTH}px;
@@ -346,11 +368,21 @@ export default class TabRowWidget extends BasicWidget {
const ntxId = $(e.target).closest(".note-tab").attr("data-ntx-id");
+ const mainContext = appContext.tabManager.getMainNoteContexts().find((nc) => nc.ntxId === ntxId);
+ const isPinned = !!mainContext?.pinned;
+ const isEmpty = !mainContext || mainContext.isEmpty();
+
contextMenu.show<CommandNames>({
x: e.pageX,
y: e.pageY,
items: [
- { title: t("tab_row.close"), command: "closeTab", uiIcon: "bx bx-x" },
+ isPinned
+ ? { title: t("tab_row.unpin_tab"), command: "unpinTab", uiIcon: "bx bx-pin" }
+ : { title: t("tab_row.pin_tab"), command: "pinTab", uiIcon: "bx bx-pin", enabled: !isEmpty },
+
+ { kind: "separator" },
+
+ { title: t("tab_row.close"), command: "closeTab", uiIcon: "bx bx-x", enabled: !isPinned },
{ title: t("tab_row.close_other_tabs"), command: "closeOtherTabs", uiIcon: "bx bx-empty", enabled: appContext.tabManager.noteContexts.length !== 1 },
{ title: t("tab_row.close_right_tabs"), command: "closeRightTabs", uiIcon: "bx bx-empty", enabled: appContext.tabManager.noteContexts?.at(-1)?.ntxId !== ntxId },
{ title: t("tab_row.close_all_tabs"), command: "closeAllTabs", uiIcon: "bx bx-empty" },
@@ -361,7 +393,7 @@ export default class TabRowWidget extends BasicWidget {
{ kind: "separator" },
- { title: t("tab_row.move_tab_to_new_window"), command: "moveTabToNewWindow", uiIcon: "bx bx-window-open" },
+ { title: t("tab_row.move_tab_to_new_window"), command: "moveTabToNewWindow", uiIcon: "bx bx-window-open", enabled: !isPinned },
{ title: t("tab_row.copy_tab_to_new_window"), command: "copyTabToNewWindow", uiIcon: "bx bx-empty" }
],
selectMenuItemHandler: ({ command }) => {
@@ -743,13 +775,16 @@ export default class TabRowWidget extends BasicWidget {
tabEl.style.transform = `translate3d(${translateX}px, 0, 0)`;
const currentTabPositionX = originalTabPositionX + translateX;
const destinationIndexTarget = this.closest(currentTabPositionX, tabPositions);
- const destinationIndex = Math.max(0, Math.min(tabEls.length, destinationIndexTarget));
+ // keep pinned and unpinned tabs in their own zones — neither can cross the boundary
+ const pinnedCount = tabEls.filter((el) => el.hasAttribute("pinned")).length;
+ const destinationIndex = clampDragDestination(destinationIndexTarget, tabEl.hasAttribute("pinned"), pinnedCount, tabEls.length);
if (currentIndex !== destinationIndex) {
this.animateTabMove(tabEl, currentIndex, destinationIndex);
}
- if (Math.abs(moveVector.y) > 100) {
+ // pinned tabs stay put — don't trigger the drag-to-new-window tear-off
+ if (Math.abs(moveVector.y) > 100 && !tabEl.hasAttribute("pinned")) {
this.triggerCommand("moveTabToNewWindow", { ntxId: this.getTabId($(tabEl)) });
}
});
@@ -846,6 +881,9 @@ export default class TabRowWidget extends BasicWidget {
return;
}
+ // keep the pinned attribute in sync (drives the pin indicator + hidden close button)
+ $tab.attr("pinned", noteContext.getMainContext().pinned ? "" : null);
+
for (const clazz of Array.from($tab[0].classList)) {
// create copy to safely iterate over while removing classes
if (clazz !== "note-tab") {
@@ -929,4 +967,30 @@ export default class TabRowWidget extends BasicWidget {
this.updateTab($tab, noteContext);
}
}
+
+ tabPinStateChangedEvent({ ntxId, pinned }: EventData<"tabPinStateChanged">) {
+ const $tab = this.getTabById(ntxId);
+
+ if (!$tab.length) {
+ return;
+ }
+
+ $tab.attr("pinned", pinned ? "" : null);
+
+ // the model already moved the context; mirror that order in the DOM and re-layout
+ this.syncTabOrder();
+ this.layoutTabs();
+ this.setupDraggabilly();
+ }
+
+ /** Reorders the tab elements in the DOM to match the model order (pinned tabs grouped first). */
+ syncTabOrder() {
+ for (const noteContext of appContext.tabManager.getMainNoteContexts()) {
+ const tabEl = this.getTabById(noteContext.ntxId)[0];
+
+ if (tabEl) {
+ this.$containerAnchor.before(tabEl);
+ }
+ }
+ }
}