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 pinning tabs and tab context menu actions on mobile https://github.com/siyuan-note/siyuan/issues/19272
Danielec5997caf1f2
diff --git a/app/electron/windowMessaging.test.js b/app/electron/windowMessaging.test.jsindex faeb89029e..10d1ef7a91 100644--- a/app/electron/windowMessaging.test.js+++ b/app/electron/windowMessaging.test.js@@ -99,7 +99,7 @@ test("主进程 handler 按发送方与内核目标接线到 dispatchWindowMessaconst closing = source.indexOf("\n });\n", opening);assert.notEqual(closing, -1);// 去掉 handler 自身的外层花括号,保留 (event, data) => {...} 的函数体- const body = source.slice(opening + 1, closing + 5).replace(/\n \}$/, "\n");+ const body = source.slice(opening + 1, closing + 5).replace(/\n {4}\}$/, "\n");const entries = ["senderWebContentsId: event.sender.id", "getKernelTarget: getWindowKernelTarget","getAllWindows: () => BrowserWindow.getAllWindows()"];entries.forEach(entry => assert.equal(body.includes(entry), true, entry));diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex b6172a3db7..d88d2501a5 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -669,12 +669,16 @@ body.mobile-topbar--merged {&__item {display: flex;align-items: center;- min-height: 48px;- margin-bottom: 8px;- padding: 4px 6px 4px 12px;+ min-height: 40px;+ margin-bottom: 5px;+ padding: 2px 4px 2px 8px;border: 1px solid var(--b3-border-color);border-radius: var(--b3-border-radius-b);background-color: var(--b3-theme-background);+ // 长按弹出菜单时避免触发文本选择+ -webkit-touch-callout: none;+ -webkit-user-select: none;+ user-select: none;&--active {border-color: var(--b3-theme-primary);@@ -682,17 +686,40 @@ body.mobile-topbar--merged {}}+ &__item-pin {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 16px;+ height: 16px;+ flex-shrink: 0;+ margin-right: 4px;+ color: var(--b3-theme-primary);++ svg {+ display: block;+ width: 13px;+ height: 13px;+ }+ }+&__item-icon {display: flex;align-items: center;justify-content: center;- width: 18px;- height: 18px;+ width: 16px;+ height: 16px;flex-shrink: 0;- margin-right: 10px;+ margin-right: 8px;color: var(--b3-theme-on-surface-light);- font-size: 18px;- line-height: 18px;+ font-size: 16px;+ // 行高与条目等高,emoji 图标才不会顶出自身盒子而与文字错位+ line-height: 40px;++ & > img,+ & > svg {+ display: block;+ }}&__item-title {@@ -701,16 +728,18 @@ body.mobile-topbar--merged {overflow: hidden;text-overflow: ellipsis;white-space: nowrap;+ // 行高不小于图标,保证文字基线与图标中心对齐+ line-height: 40px;}&__close {- width: 36px;- height: 36px;- padding: 8px;+ width: 34px;+ height: 30px;+ padding: 7px;svg {- width: 18px;- height: 18px;+ width: 16px;+ height: 16px;}}diff --git a/app/src/constants.ts b/app/src/constants.tsindex 8d70b05df9..61af9f442d 100644--- a/app/src/constants.ts+++ b/app/src/constants.ts@@ -324,6 +324,8 @@ export abstract class Constants {public static readonly MENU_AI = "ai"; // 块 AI 菜单public static readonly MENU_TAB = "tab"; // 页签右键菜单public static readonly MENU_TAB_LIST = "tabList"; // 页签切换菜单+ public static readonly MENU_MOBILE_TABS = "mobileTabs"; // 移动端页签长按菜单+ public static readonly MENU_MOBILE_TABS_OVERVIEW = "mobileTabsOverview"; // 移动端页签概览面板public static readonly MENU_INLINE_CONTEXT = "inline-context"; // 文本右键菜单public static readonly MENU_INLINE_IMG = "inline-img"; // 图片元素菜单diff --git a/app/src/mobile/tabs/MobileTabs.ts b/app/src/mobile/tabs/MobileTabs.tsindex 50b35ac7ee..2ff9558dd0 100644--- a/app/src/mobile/tabs/MobileTabs.ts+++ b/app/src/mobile/tabs/MobileTabs.ts@@ -1,6 +1,7 @@import {Constants} from "../../constants";import {getDocumentIconHTML} from "../../emoji/fileTreeIcon";import type {App} from "../../index";+import {MenuItem} from "../../menus/Menu";import {saveScroll} from "../../protyle/scroll/saveScroll";import {setStorageVal} from "../../protyle/util/compatibility";import {escapeAttr, escapeHtml} from "../../util/escape";@@ -12,6 +13,7 @@ import {loadMobileFileById, updateRecentDocSwitchTime} from "../editor";import {openModel} from "../menu/model";import {closeModel} from "../util/closePanel";import {setEmpty} from "../util/setEmpty";+import {canCloseTab, orderTabsForOverview, trimTabsToLimit} from "./mobileTabsState";const MAX_HISTORY = 32;@@ -32,6 +34,10 @@ type MobileTab = {backStack: MobileTabEntry[];forwardStack: MobileTabEntry[];activeAt: number;+ /**+ * 钉住的页签不参与超限淘汰,在概览列表中置顶+ */+ pin?: boolean;};type MobileTabsState = {@@ -87,6 +93,7 @@ const normalizeTab = (value: unknown): MobileTab | undefined => {forwardStack: Array.isArray(tab.forwardStack) ?tab.forwardStack.map(normalizeEntry).filter((item): item is MobileTabEntry => !!item).slice(-MAX_HISTORY) : [],activeAt: typeof tab.activeAt === "number" ? tab.activeAt : 0,+ pin: tab.pin === true,};};@@ -101,12 +108,30 @@ const sanitizeTab = (tab: MobileTab): MobileTab => {};};+const getTabTitle = (tab: MobileTab) => tab.current?.title || window.siyuan.languages.newTab;++const getTabIconHTML = (tab: MobileTab) => getDocumentIconHTML(+ tab.current?.icon || "",+ "mobile-tabs__item-icon",+ // 没有图标时始终使用默认 SVG 图标做占位,不跟随 useSVGDefaultIcon 设置+ true,+);++const getPinIcon = (pinned: boolean) => pinned ? "iconPin" : "iconUnpin";+export class MobileTabs {private state: MobileTabsState;private navigationEpoch = 0;private abortController?: AbortController;private activationBackStack: string[] = [];private activationForwardStack: string[] = [];+ private overviewElement?: HTMLElement;+ private overviewLongPressTimer?: number;+ private overviewLongPressTabID?: string;+ private overviewLongPressTriggered = false;+ private suppressOverviewClickUntil = 0;+ private overviewPointerX?: number;+ private overviewPointerY?: number;constructor(private readonly app: App) {const stored = window.siyuan.storage[Constants.LOCAL_MOBILE_TABS] as MobileTabsState | undefined;@@ -254,19 +279,12 @@ export class MobileTabs {}private trimTabs() {- while (this.state.tabs.length > this.maxTabs) {- const inactive = this.state.tabs- .filter((item) => item.id !== this.state.activeTabID)- .sort((a, b) => a.activeAt - b.activeAt)[0];- if (!inactive) {- break;- }- this.state.tabs.splice(this.state.tabs.indexOf(inactive), 1);- this.removeActivation(inactive.id);- if (inactive.current?.rootID) {- fetchPost("/api/storage/updateRecentDocCloseTime", {rootID: inactive.current.rootID});+ this.state.tabs = trimTabsToLimit(this.state.tabs, this.state.activeTabID, this.maxTabs, (tab) => {+ this.removeActivation(tab.id);+ if (tab.current?.rootID) {+ fetchPost("/api/storage/updateRecentDocCloseTime", {rootID: tab.current.rootID});}- }+ });}async removeMissingTabs() {@@ -685,6 +703,21 @@ export class MobileTabs {}closeAll() {+ // 钉住的页签不参与关闭全部+ const pinnedTabs = this.state.tabs.filter((tab) => !!tab.pin);+ if (pinnedTabs.length > 0) {+ const keptIDs = new Set(pinnedTabs.map((tab) => tab.id));+ this.filterEntries((_entry, entryTabID) => keptIDs.has(entryTabID));+ if (!pinnedTabs.some((tab) => tab.id === this.state.activeTabID)) {+ const nextTab = [...pinnedTabs].sort((a, b) => b.activeAt - a.activeAt)[0];+ if (nextTab) {+ void this.switchTo(nextTab.id, false);+ }+ }+ window.siyuan.menus.menu.remove();+ this.renderOverview();+ return;+ }this.cancelNavigation();this.state.tabs.forEach((tab) => {if (tab.current?.rootID) {@@ -722,13 +755,13 @@ export class MobileTabs {this.filterEntries((entry) => !roots.has(entry.rootID));}- private filterEntries(predicate: (entry: MobileTabEntry) => boolean) {+ private filterEntries(predicate: (entry: MobileTabEntry, tabID: string) => boolean) {const activeTabID = this.state.activeTabID;this.state.tabs.forEach((tab) => {- tab.backStack = tab.backStack.filter(predicate);- tab.forwardStack = tab.forwardStack.filter(predicate);+ tab.backStack = tab.backStack.filter((entry) => predicate(entry, tab.id));+ tab.forwardStack = tab.forwardStack.filter((entry) => predicate(entry, tab.id));});- this.state.tabs = this.state.tabs.filter((tab) => !tab.current || predicate(tab.current));+ this.state.tabs = this.state.tabs.filter((tab) => !tab.current || predicate(tab.current, tab.id));this.activationBackStack = this.activationBackStack.filter((tabID) =>this.state.tabs.some((tab) => tab.id === tabID));this.activationForwardStack = this.activationForwardStack.filter((tabID) =>@@ -762,26 +795,83 @@ export class MobileTabs {this.persist();}- openOverview() {- this.snapshot();+ private openTabMenu(tabID: string) {+ const tab = this.state.tabs.find((item) => item.id === tabID);+ if (!tab) {+ return;+ }+ const pinned = !!tab.pin;+ window.siyuan.menus.menu.remove();+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_MOBILE_TABS);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "close",+ icon: "iconClose",+ label: window.siyuan.languages.close,+ click: () => {+ void this.close(tabID);+ },+ }).element);+ if (this.state.tabs.length > 1) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "closeOthers",+ label: window.siyuan.languages.closeOthers,+ click: () => {+ this.closeOthers(tabID);+ },+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "closeAll",+ label: window.siyuan.languages.closeAll,+ click: () => {+ this.closeAll();+ },+ }).element);+ }+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: pinned ? "unpin" : "pin",+ icon: getPinIcon(pinned),+ label: pinned ? window.siyuan.languages.unpin : window.siyuan.languages.pin,+ click: () => {+ this.togglePin(tabID);+ },+ }).element);+ window.siyuan.menus.menu.fullscreen("bottom");+ }++ private togglePin(tabID: string) {+ const tab = this.state.tabs.find((item) => item.id === tabID);+ if (!tab) {+ return;+ }+ tab.pin = !tab.pin;+ tab.activeAt = Date.now();+ // 钉住状态随页签列表持久化this.persist();- const active = this.state.activeTabID;- const rows = this.state.tabs.map((tab) => {- const iconHTML = tab.current ? getDocumentIconHTML(- tab.current.icon || "",- "mobile-tabs__item-icon",- ) : '<svg class="mobile-tabs__item-icon"><use xlink:href="#iconFile"></use></svg>';- return `<div class="mobile-tabs__item${tab.id === active ? " mobile-tabs__item--active" : ""}" data-tab-id="${escapeAttr(tab.id)}">- ${iconHTML}- <span class="mobile-tabs__item-title">${escapeHtml(tab.current?.title || window.siyuan.languages.newTab)}</span>- <button class="b3-button b3-button--text mobile-tabs__close" data-action="close" aria-label="${escapeAttr(window.siyuan.languages.close)}">- <svg><use xlink:href="#iconClose"></use></svg>- </button>-</div>`;- }).join("");+ this.renderOverview();+ window.siyuan.menus.menu.remove();+ }++ private closeOthers(tabID: string) {+ if (!this.state.tabs.some((item) => item.id === tabID)) {+ return;+ }+ // 钉住的页签不参与关闭其他+ const keptIDs = new Set(this.state.tabs+ .filter((item) => item.id === tabID || !!item.pin)+ .map((item) => item.id));+ this.filterEntries((_entry, entryTabID) => keptIDs.has(entryTabID));+ window.siyuan.menus.menu.remove();+ this.renderOverview();+ }++ private renderOverview() {+ // 钉住的页签置顶显示,靠图钉图标区分,不额外加分组标题或分隔线+ const rows = orderTabsForOverview(this.state.tabs)+ .map((tab) => this.renderOverviewItem(tab)).join("");openModel({title: `${window.siyuan.languages.mobileTabs} ${this.state.tabs.length}`,- html: `<div class="mobile-tabs">+ html: `<div class="mobile-tabs" data-name="${escapeAttr(Constants.MENU_MOBILE_TABS_OVERVIEW)}"><div class="mobile-tabs__list">${rows || `<div class="b3-list--empty">${window.siyuan.languages.emptyContent}</div>`}</div><div class="mobile-tabs__actions"><button class="b3-button b3-button--outline" data-action="back"${this.canGoBack() ? "" : " disabled"}><svg><use xlink:href="#iconLeft"></use></svg>${window.siyuan.languages.goBack}</button>@@ -791,44 +881,119 @@ export class MobileTabs {</div></div>`,bindEvent: (element) => {- element.querySelectorAll<HTMLElement>("[data-action]").forEach((target) => {- target.addEventListener("click", (event) => {- event.stopPropagation();- const action = target.dataset.action;- const tabID = target.closest<HTMLElement>("[data-tab-id]")?.dataset.tabId;- if (action === "close" && tabID) {- void this.close(tabID);- } else if (action === "back") {- void this.goBack().then(() => closeModel());- } else if (action === "forward") {- void this.goForward().then(() => closeModel());- } else if (action === "new-doc") {- closeModel();- newFile(this.app);- } else if (action === "close-all") {- this.closeAll();- }- });- });- element.querySelectorAll<HTMLElement>("[data-tab-id]").forEach((target) => {- target.addEventListener("click", () => {- const tabID = target.dataset.tabId;- if (tabID) {- void this.switchTo(tabID);- }- });- });- requestAnimationFrame(() => {- const listElement = element.querySelector<HTMLElement>(".mobile-tabs__list");- const activeElement = listElement?.querySelector<HTMLElement>(".mobile-tabs__item--active");- if (!listElement || !activeElement) {- return;- }- const listRect = listElement.getBoundingClientRect();- const activeRect = activeElement.getBoundingClientRect();- listElement.scrollTop += activeRect.top - listRect.top - (listRect.height - activeRect.height) / 2;- });+ if (element !== this.overviewElement) {+ // 每次渲染都会替换内容,事件绑定在固定的容器上+ this.overviewElement = element;+ this.bindOverviewEvents(element);+ }},+ destroyCallback: () => {+ this.cancelOverviewLongPress();+ },+ });+ }++ private renderOverviewItem(tab: MobileTab) {+ const pinned = !!tab.pin;+ const closeHidden = !canCloseTab(pinned, window.siyuan.config.fileTree.openFilesUseCurrentTab);+ return `<div class="mobile-tabs__item${tab.id === this.state.activeTabID ? " mobile-tabs__item--active" : ""}" data-tab-id="${escapeAttr(tab.id)}">+ ${getTabIconHTML(tab)}+ <span class="mobile-tabs__item-title">${escapeHtml(getTabTitle(tab))}</span>+ <span class="mobile-tabs__item-pin${pinned ? "" : " fn__none"}" aria-hidden="${pinned ? "false" : "true"}" aria-label="${escapeAttr(window.siyuan.languages.pin)}"><svg><use xlink:href="#iconPin"></use></svg></span>+ <button class="b3-button b3-button--text mobile-tabs__close${closeHidden ? " fn__none" : ""}" data-action="close" aria-label="${escapeAttr(window.siyuan.languages.close)}">+ <svg><use xlink:href="#iconClose"></use></svg>+ </button>+</div>`;+ }++ private bindOverviewEvents(element: HTMLElement) {+ element.addEventListener("click", (event) => {+ const target = event.target as HTMLElement;+ if (this.overviewLongPressTriggered) {+ // 长按抬手时会补发 click,只忽略紧随长按的那一次+ this.overviewLongPressTriggered = false;+ if (Date.now() < this.suppressOverviewClickUntil) {+ event.preventDefault();+ event.stopPropagation();+ return;+ }+ }+ const actionElement = target.closest<HTMLElement>("[data-action]");+ if (actionElement) {+ const tabID = actionElement.closest<HTMLElement>("[data-tab-id]")?.dataset.tabId;+ if (actionElement.dataset.action === "close" && tabID) {+ void this.close(tabID);+ } else if (actionElement.dataset.action === "back") {+ void this.goBack().then(() => closeModel());+ } else if (actionElement.dataset.action === "forward") {+ void this.goForward().then(() => closeModel());+ } else if (actionElement.dataset.action === "new-doc") {+ closeModel();+ newFile(this.app);+ } else if (actionElement.dataset.action === "close-all") {+ this.closeAll();+ }+ event.stopPropagation();+ return;+ }+ const itemElement = target.closest<HTMLElement>("[data-tab-id]");+ if (itemElement) {+ void this.switchTo(itemElement.dataset.tabId);+ }});++ const processPointerMove = (event: PointerEvent) => {+ if (typeof this.overviewPointerX !== "number" || typeof this.overviewPointerY !== "number") {+ return;+ }+ if (Math.abs(event.clientX - this.overviewPointerX) > Constants.SIZE_DRAG_THRESHOLD ||+ Math.abs(event.clientY - this.overviewPointerY) > Constants.SIZE_DRAG_THRESHOLD) {+ // 滑动视为滚动列表,取消长按+ this.cancelOverviewLongPress();+ }+ };+ element.addEventListener("pointerdown", (event) => {+ if (event.button !== 0) {+ return;+ }+ const itemElement = (event.target as HTMLElement).closest<HTMLElement>("[data-tab-id]");+ if (!itemElement) {+ return;+ }+ this.cancelOverviewLongPress();+ this.overviewPointerX = event.clientX;+ this.overviewPointerY = event.clientY;+ this.overviewLongPressTabID = itemElement.dataset.tabId;+ this.overviewLongPressTimer = window.setTimeout(() => {+ const tabID = this.overviewLongPressTabID;+ this.overviewLongPressTimer = undefined;+ this.overviewLongPressTabID = undefined;+ if (!tabID) {+ return;+ }+ this.overviewLongPressTriggered = true;+ this.suppressOverviewClickUntil = Date.now() + Constants.TIMEOUT_LONGPRESS;+ this.openTabMenu(tabID);+ }, Constants.TIMEOUT_LONGPRESS);+ });+ element.addEventListener("pointermove", processPointerMove);+ element.addEventListener("pointerup", () => this.cancelOverviewLongPress());+ element.addEventListener("pointercancel", () => this.cancelOverviewLongPress());+ }++ private cancelOverviewLongPress() {+ if (this.overviewLongPressTimer) {+ clearTimeout(this.overviewLongPressTimer);+ this.overviewLongPressTimer = undefined;+ }+ this.overviewLongPressTabID = undefined;+ this.overviewPointerX = undefined;+ this.overviewPointerY = undefined;+ }++ openOverview() {+ this.snapshot();+ this.persist();+ this.renderOverview();}}diff --git a/app/src/mobile/tabs/mobileTabsState.test.ts b/app/src/mobile/tabs/mobileTabsState.test.tsnew file mode 100644index 0000000000..8bca8c1631--- /dev/null+++ b/app/src/mobile/tabs/mobileTabsState.test.ts@@ -0,0 +1,131 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ canCloseTab,+ orderTabsForOverview,+ pickEvictedTabID,+ trimTabsToLimit,+} from "./mobileTabsState";++type Tab = {+ id: string;+ pin?: boolean;+ activeAt: number;+};++const createTabs = (items: Array<{ id: string; pin?: boolean; activeAt: number }>): Tab[] => items;++describe("mobile tabs state", () => {+ it("orders pinned tabs first and keeps the relative order", () => {+ const tabs = createTabs([+ {id: "a", activeAt: 1},+ {id: "b", pin: true, activeAt: 2},+ {id: "c", activeAt: 3},+ {id: "d", pin: true, activeAt: 4},+ ]);++ assert.deepEqual(orderTabsForOverview(tabs).map((tab) => tab.id), ["b", "d", "a", "c"]);+ // 不修改入参+ assert.deepEqual(tabs.map((tab) => tab.id), ["a", "b", "c", "d"]);+ });++ it("keeps the order unchanged when no tab is pinned", () => {+ const tabs = createTabs([+ {id: "a", activeAt: 1},+ {id: "b", activeAt: 2},+ ]);++ assert.deepEqual(orderTabsForOverview(tabs).map((tab) => tab.id), ["a", "b"]);+ });++ it("keeps the order unchanged when every tab is pinned", () => {+ const tabs = createTabs([+ {id: "a", pin: true, activeAt: 1},+ {id: "b", pin: true, activeAt: 2},+ ]);++ assert.deepEqual(orderTabsForOverview(tabs).map((tab) => tab.id), ["a", "b"]);+ });++ it("handles an empty tab list", () => {+ assert.deepEqual(orderTabsForOverview([]), []);+ });++ it("hides the close button of pinned tabs only when files open in the current tab", () => {+ assert.equal(canCloseTab(false, false), true);+ assert.equal(canCloseTab(false, true), true);+ assert.equal(canCloseTab(true, false), true);+ assert.equal(canCloseTab(true, true), false);+ });++ it("never evicts pinned tabs or the active tab", () => {+ const tabs = createTabs([+ {id: "oldest", activeAt: 1},+ {id: "pinned", pin: true, activeAt: 2},+ {id: "active", activeAt: 3},+ {id: "newest", activeAt: 4},+ ]);++ assert.equal(pickEvictedTabID(tabs, "active"), "oldest");+ });++ it("evicts the least recently active unpinned tab", () => {+ const tabs = createTabs([+ {id: "a", activeAt: 30},+ {id: "b", pin: true, activeAt: 10},+ {id: "c", activeAt: 20},+ {id: "d", activeAt: 40},+ ]);++ assert.equal(pickEvictedTabID(tabs, "d"), "c");+ assert.equal(pickEvictedTabID(tabs, undefined), "c");+ });++ it("keeps every pinned tab when all of them are pinned", () => {+ const tabs = createTabs([+ {id: "a", pin: true, activeAt: 1},+ {id: "b", pin: true, activeAt: 2},+ {id: "c", pin: true, activeAt: 3},+ ]);++ assert.equal(pickEvictedTabID(tabs, "c"), undefined);+ });++ it("removes the oldest unpinned tabs until the limit is reached", () => {+ const removed: string[] = [];+ const remaining = trimTabsToLimit(createTabs([+ {id: "a", activeAt: 1},+ {id: "b", activeAt: 2},+ {id: "c", activeAt: 3},+ {id: "d", activeAt: 4},+ ]), "d", 2, (tab) => removed.push(tab.id));++ assert.deepEqual(remaining.map((tab) => tab.id), ["c", "d"]);+ assert.deepEqual(removed, ["a", "b"]);+ });++ it("allows exceeding the limit instead of evicting pinned tabs", () => {+ const removed: string[] = [];+ const remaining = trimTabsToLimit(createTabs([+ {id: "pinnedA", pin: true, activeAt: 1},+ {id: "pinnedB", pin: true, activeAt: 2},+ {id: "active", activeAt: 3},+ {id: "unpinned", activeAt: 4},+ ]), "active", 2, (tab) => removed.push(tab.id));++ // 上限为 2,钉住页签占满后不再淘汰,允许超出上限+ assert.deepEqual(remaining.map((tab) => tab.id), ["pinnedA", "pinnedB", "active"]);+ assert.deepEqual(removed, ["unpinned"]);+ });++ it("keeps the tab list untouched when it is within the limit", () => {+ const tabs = createTabs([+ {id: "a", pin: true, activeAt: 1},+ {id: "b", activeAt: 2},+ ]);+ const removed: string[] = [];++ assert.deepEqual(trimTabsToLimit(tabs, "b", 8, (tab) => removed.push(tab.id)), tabs);+ assert.deepEqual(removed, []);+ });+});diff --git a/app/src/mobile/tabs/mobileTabsState.ts b/app/src/mobile/tabs/mobileTabsState.tsnew file mode 100644index 0000000000..f96bd2add8--- /dev/null+++ b/app/src/mobile/tabs/mobileTabsState.ts@@ -0,0 +1,86 @@+/**+ * 移动端页签的钉住排序与超限淘汰规则,保持与桌面端 Wnd.removeOverCounter() 一致的语义:+ * 钉住的页签不参与自动淘汰,移除未钉住的页签后仍然超限时允许超出上限。+ */++interface IMobileTabStateLike {+ id: string;+ pin?: boolean;+ activeAt: number;+}++/**+ * 概览列表的显示顺序:钉住的页签在前,各自保持原有相对顺序+ *+ * @param tabs 页签列表+ * @returns 排序后的新数组,不修改入参+ */+export const orderTabsForOverview = <T extends IMobileTabStateLike>(tabs: readonly T[]): T[] => {+ return [+ ...tabs.filter((tab) => !!tab.pin),+ ...tabs.filter((tab) => !tab.pin),+ ];+};++/**+ * 判断页签的关闭按钮是否可用+ *+ * 在“在当前页签打开文件”模式下钉住的页签不显示关闭按钮,避免误关后在当前页签载入其他文档+ *+ * @param pinned 页签是否钉住+ * @param openFilesUseCurrentTab 是否在当前页签打开文件+ * @returns 是否显示关闭按钮+ */+export const canCloseTab = (pinned: boolean, openFilesUseCurrentTab: boolean) => {+ return !pinned || !openFilesUseCurrentTab;+};++/**+ * 挑选应被移除的页签:最久未激活的未钉住页签,当前激活的页签不参与淘汰+ *+ * @param tabs 页签列表+ * @param activeTabID 当前激活的页签 ID+ * @returns 待移除的页签 ID,没有可移除的页签时返回 undefined+ */+export const pickEvictedTabID = (tabs: readonly IMobileTabStateLike[], activeTabID?: string): string | undefined => {+ const candidates = tabs.filter((tab) => !tab.pin && tab.id !== activeTabID);+ if (candidates.length === 0) {+ return;+ }+ let oldest = candidates[0];+ for (let index = 1; index < candidates.length; index++) {+ if (candidates[index].activeAt < oldest.activeAt) {+ oldest = candidates[index];+ }+ }+ return oldest.id;+};++/**+ * 按页签上限截断列表+ *+ * @param tabs 页签列表+ * @param activeTabID 当前激活的页签 ID+ * @param maxTabs 页签上限+ * @param onRemove 移除页签时的回调+ * @returns 未超过上限的页签列表+ */+export const trimTabsToLimit = <T extends IMobileTabStateLike>(tabs: readonly T[], activeTabID: string | undefined,+ maxTabs: number,+ onRemove?: (tab: T) => void): T[] => {+ const remaining = [...tabs];+ while (remaining.length > maxTabs) {+ const evictedID = pickEvictedTabID(remaining, activeTabID);+ if (typeof evictedID === "undefined") {+ // 只剩钉住页签时保留全部页签,允许超出上限+ break;+ }+ const index = remaining.findIndex((tab) => tab.id === evictedID);+ if (index < 0) {+ break;+ }+ const evicted = remaining.splice(index, 1)[0];+ onRemove?.(evicted);+ }+ return remaining;+};