From 469c2c3ce9e1c92f391ae15b4a4a5da3f3d7a75c Mon Sep 17 00:00:00 2001 From: Jin <22962980+JYC333@users.noreply.github.com> Date: Mon, 3 Mar 2025 22:46:40 +0100 Subject: [PATCH 1/8] Revert "Revert "port tab manager to ts"" This reverts commit 3855f0e75f21c9b0b5294c8aceb1cac0b0718eab. --- src/public/app/components/app_context.ts | 10 +- src/public/app/components/entrypoints.ts | 16 +- .../{tab_manager.js => tab_manager.ts} | 308 +++++++++++------- src/public/app/menus/link_context_menu.ts | 10 +- src/public/app/services/link.ts | 14 +- src/public/app/services/tree.ts | 2 +- src/public/app/utils/mutex.ts | 2 +- .../containers/split_note_container.ts | 4 +- src/public/app/widgets/tab_row.ts | 16 +- 9 files changed, 228 insertions(+), 154 deletions(-) rename src/public/app/components/{tab_manager.js => tab_manager.ts} (71%) diff --git a/src/public/app/components/app_context.ts b/src/public/app/components/app_context.ts index 4eb8bdb6a..a8616b1c6 100644 --- a/src/public/app/components/app_context.ts +++ b/src/public/app/components/app_context.ts @@ -22,7 +22,6 @@ import type LoadResults from "../services/load_results.js"; import type { Attribute } from "../services/attribute_parser.js"; import type NoteTreeWidget from "../widgets/note_tree.js"; import type { default as NoteContext, GetTextEditorCallback } from "./note_context.js"; -import type { ContextMenuEvent } from "../menus/context_menu.js"; import type TypeWidget from "../widgets/type_widgets/type_widget.js"; import type EditableTextTypeWidget from "../widgets/type_widgets/editable_text.js"; import type FAttribute from "../entities/fattribute.js"; @@ -58,8 +57,8 @@ export interface ContextMenuCommandData extends CommandData { } export interface NoteCommandData extends CommandData { - notePath?: string; - hoistedNoteId?: string; + notePath?: string | null; + hoistedNoteId?: string | null; viewScope?: ViewScope; } @@ -328,7 +327,7 @@ type EventMappings = { ntxId: string | null; }; contextsReopenedEvent: { - mainNtxId: string; + mainNtxId: string | null; tabPosition: number; }; noteDetailRefreshed: { @@ -342,7 +341,7 @@ type EventMappings = { newNoteContextCreated: { noteContext: NoteContext; }; - noteContextRemovedEvent: { + noteContextRemoved: { ntxIds: string[]; }; exportSvg: { @@ -368,7 +367,6 @@ type EventMappings = { textTypeWidget: EditableTextTypeWidget; text: string; }; - }; export type EventListener = { diff --git a/src/public/app/components/entrypoints.ts b/src/public/app/components/entrypoints.ts index d4c8b600e..0ad2c76ed 100644 --- a/src/public/app/components/entrypoints.ts +++ b/src/public/app/components/entrypoints.ts @@ -66,12 +66,13 @@ export default class Entrypoints extends Component { } async toggleNoteHoistingCommand({ noteId = appContext.tabManager.getActiveContextNoteId() }) { - if (!noteId) { + const activeNoteContext = appContext.tabManager.getActiveContext(); + + if (!activeNoteContext || !noteId) { return; } const noteToHoist = await froca.getNote(noteId); - const activeNoteContext = appContext.tabManager.getActiveContext(); if (noteToHoist?.noteId === activeNoteContext.hoistedNoteId) { await activeNoteContext.unhoist(); @@ -83,6 +84,11 @@ export default class Entrypoints extends Component { async hoistNoteCommand({ noteId }: { noteId: string }) { const noteContext = appContext.tabManager.getActiveContext(); + if (!noteContext) { + logError("hoistNoteCommand: noteContext is null"); + return; + } + if (noteContext.hoistedNoteId !== noteId) { await noteContext.setHoistedNoteId(noteId); } @@ -174,7 +180,11 @@ export default class Entrypoints extends Component { } async runActiveNoteCommand() { - const { ntxId, note } = appContext.tabManager.getActiveContext(); + const noteContext = appContext.tabManager.getActiveContext(); + if (!noteContext) { + return; + } + const { ntxId, note } = noteContext; // ctrl+enter is also used elsewhere, so make sure we're running only when appropriate if (!note || note.type !== "code") { diff --git a/src/public/app/components/tab_manager.js b/src/public/app/components/tab_manager.ts similarity index 71% rename from src/public/app/components/tab_manager.js rename to src/public/app/components/tab_manager.ts index 46a0f9d96..b441c7819 100644 --- a/src/public/app/components/tab_manager.js +++ b/src/public/app/components/tab_manager.ts @@ -4,23 +4,40 @@ import server from "../services/server.js"; import options from "../services/options.js"; import froca from "../services/froca.js"; import treeService from "../services/tree.js"; -import utils from "../services/utils.js"; 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 type { EventData } from "./app_context.js"; +import type FNote from "../entities/fnote.js"; + +interface TabState { + contexts: NoteContext[]; + position: number; +} + +interface NoteContextState { + ntxId: string; + mainNtxId: string | null; + notePath: string | null; + hoistedNoteId: string; + active: boolean; + viewScope: Record; +} export default class TabManager extends Component { + public children: NoteContext[]; + public mutex: Mutex; + public activeNtxId: string | null; + public recentlyClosedTabs: TabState[]; + public tabsUpdate: SpacedUpdate; + constructor() { super(); - /** @property {NoteContext[]} */ this.children = []; this.mutex = new Mutex(); - this.activeNtxId = null; - - // elements are arrays of {contexts, position}, storing note contexts for each tab (one main context + subcontexts [splits]), and the original position of the tab this.recentlyClosedTabs = []; this.tabsUpdate = new SpacedUpdate(async () => { @@ -28,7 +45,9 @@ export default class TabManager extends Component { return; } - const openNoteContexts = this.noteContexts.map((nc) => nc.getPojoState()).filter((t) => !!t); + const openNoteContexts = this.noteContexts + .map((nc) => nc.getPojoState()) + .filter((t) => !!t); await server.put("options", { openNoteContexts: JSON.stringify(openNoteContexts) @@ -38,13 +57,11 @@ export default class TabManager extends Component { appContext.addBeforeUnloadListener(this); } - /** @returns {NoteContext[]} */ - get noteContexts() { + get noteContexts(): NoteContext[] { return this.children; } - /** @type {NoteContext[]} */ - get mainNoteContexts() { + get mainNoteContexts(): NoteContext[] { return this.noteContexts.filter((nc) => !nc.mainNtxId); } @@ -53,11 +70,12 @@ export default class TabManager extends Component { const noteContextsToOpen = (appContext.isMainWindow && options.getJson("openNoteContexts")) || []; // preload all notes at once - await froca.getNotes([...noteContextsToOpen.flatMap((tab) => [treeService.getNoteIdFromUrl(tab.notePath), tab.hoistedNoteId])], true); + await froca.getNotes([...noteContextsToOpen.flatMap((tab: NoteContextState) => + [treeService.getNoteIdFromUrl(tab.notePath), tab.hoistedNoteId])], true); - const filteredNoteContexts = noteContextsToOpen.filter((openTab) => { + const filteredNoteContexts = noteContextsToOpen.filter((openTab: NoteContextState) => { const noteId = treeService.getNoteIdFromUrl(openTab.notePath); - if (!(noteId in froca.notes)) { + if (noteId && !(noteId in froca.notes)) { // note doesn't exist so don't try to open tab for it return false; } @@ -80,9 +98,10 @@ export default class TabManager extends Component { ntxId: parsedFromUrl.ntxId, active: true, hoistedNoteId: parsedFromUrl.hoistedNoteId || "root", - viewScope: parsedFromUrl.viewScope || {} + viewScope: parsedFromUrl.viewScope || {}, + mainNtxId: null }); - } else if (!filteredNoteContexts.find((tab) => tab.active)) { + } else if (!filteredNoteContexts.find((tab: NoteContextState) => tab.active)) { filteredNoteContexts[0].active = true; } @@ -101,21 +120,30 @@ 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) { - await appContext.tabManager.switchToNoteContext(parsedFromUrl.ntxId, parsedFromUrl.notePath, parsedFromUrl.viewScope, parsedFromUrl.hoistedNoteId); + await appContext.tabManager.switchToNoteContext( + parsedFromUrl.ntxId, + parsedFromUrl.notePath, + parsedFromUrl.viewScope, + parsedFromUrl.hoistedNoteId + ); } else if (parsedFromUrl.searchString) { await appContext.triggerCommand("searchNotes", { searchString: parsedFromUrl.searchString }); } - } catch (e) { - logError(`Loading note contexts '${options.get("openNoteContexts")}' failed: ${e.message} ${e.stack}`); + } catch (e: unknown) { + if (e instanceof Error) { + logError(`Loading note contexts '${options.get("openNoteContexts")}' failed: ${e.message} ${e.stack}`); + } else { + logError(`Loading note contexts '${options.get("openNoteContexts")}' failed: ${String(e)}`); + } // try to recover await this.openEmptyTab(); } } - noteSwitchedEvent({ noteContext }) { + noteSwitchedEvent({ noteContext }: EventData<"noteSwitched">) { if (noteContext.isActive()) { this.setCurrentNavigationStateToHash(); } @@ -135,10 +163,10 @@ export default class TabManager extends Component { const activeNoteContext = this.getActiveContext(); this.updateDocumentTitle(activeNoteContext); - this.triggerEvent("activeNoteChanged"); // trigger this even in on popstate event + this.triggerEvent("activeNoteChangedEvent", {}); // trigger this even in on popstate event } - calculateHash() { + calculateHash(): string { const activeNoteContext = this.getActiveContext(); if (!activeNoteContext) { return ""; @@ -152,21 +180,15 @@ export default class TabManager extends Component { }); } - /** @returns {NoteContext[]} */ - getNoteContexts() { + getNoteContexts(): NoteContext[] { return this.noteContexts; } - /** - * Main context is essentially a tab (children are splits), so this returns tabs. - * @returns {NoteContext[]} - */ - getMainNoteContexts() { + getMainNoteContexts(): NoteContext[] { return this.noteContexts.filter((nc) => nc.isMainContext()); } - /** @returns {NoteContext} */ - getNoteContextById(ntxId) { + getNoteContextById(ntxId: string | null): NoteContext { const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId); if (!noteContext) { @@ -176,58 +198,47 @@ export default class TabManager extends Component { return noteContext; } - /** - * Get active context which represents the visible split with focus. Active context can, but doesn't have to be "main". - * - * @returns {NoteContext} - */ - getActiveContext() { + getActiveContext(): NoteContext | null { return this.activeNtxId ? this.getNoteContextById(this.activeNtxId) : null; } - /** - * Get active main context which corresponds to the active tab. - * - * @returns {NoteContext} - */ - getActiveMainContext() { + getActiveMainContext(): NoteContext | null { return this.activeNtxId ? this.getNoteContextById(this.activeNtxId).getMainContext() : null; } - /** @returns {string|null} */ - getActiveContextNotePath() { + getActiveContextNotePath(): string | null { const activeContext = this.getActiveContext(); - return activeContext ? activeContext.notePath : null; + return activeContext?.notePath ?? null; } - /** @returns {FNote} */ - getActiveContextNote() { + getActiveContextNote(): FNote | null { const activeContext = this.getActiveContext(); return activeContext ? activeContext.note : null; } - /** @returns {string|null} */ - getActiveContextNoteId() { + getActiveContextNoteId(): string | null { const activeNote = this.getActiveContextNote(); - return activeNote ? activeNote.noteId : null; } - /** @returns {string|null} */ - getActiveContextNoteType() { + getActiveContextNoteType(): string | null { const activeNote = this.getActiveContextNote(); - return activeNote ? activeNote.type : null; } - /** @returns {string|null} */ - getActiveContextNoteMime() { - const activeNote = this.getActiveContextNote(); + getActiveContextNoteMime(): string | null { + const activeNote = this.getActiveContextNote(); return activeNote ? activeNote.mime : null; } - async switchToNoteContext(ntxId, notePath, viewScope = {}, hoistedNoteId = null) { - const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId) || (await this.openEmptyTab()); + async switchToNoteContext( + ntxId: string | null, + notePath: string, + viewScope: Record = {}, + hoistedNoteId: string | null = null + ) { + const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId) || + await this.openEmptyTab(); await this.activateNoteContext(noteContext.ntxId); @@ -242,20 +253,21 @@ export default class TabManager extends Component { async openAndActivateEmptyTab() { const noteContext = await this.openEmptyTab(); - await this.activateNoteContext(noteContext.ntxId); - - await noteContext.setEmpty(); + noteContext.setEmpty(); } - async openEmptyTab(ntxId = null, hoistedNoteId = "root", mainNtxId) { + async openEmptyTab( + ntxId: string | null = null, + hoistedNoteId: string = "root", + mainNtxId: string | null = null + ): Promise { const noteContext = new NoteContext(ntxId, hoistedNoteId, mainNtxId); const existingNoteContext = this.children.find((nc) => nc.ntxId === noteContext.ntxId); if (existingNoteContext) { await existingNoteContext.setHoistedNoteId(hoistedNoteId); - return existingNoteContext; } @@ -266,29 +278,40 @@ export default class TabManager extends Component { return noteContext; } - async openInNewTab(targetNoteId, hoistedNoteId = null) { - const noteContext = await this.openEmptyTab(null, hoistedNoteId || this.getActiveContext().hoistedNoteId); + async openInNewTab(targetNoteId: string, hoistedNoteId: string | null = null) { + const noteContext = await this.openEmptyTab( + null, + hoistedNoteId || this.getActiveContext()?.hoistedNoteId + ); await noteContext.setNote(targetNoteId); } - async openInSameTab(targetNoteId, hoistedNoteId = null) { + async openInSameTab(targetNoteId: string, hoistedNoteId: string | null = null) { const activeContext = this.getActiveContext(); + if (!activeContext) return; + await activeContext.setHoistedNoteId(hoistedNoteId || activeContext.hoistedNoteId); await activeContext.setNote(targetNoteId); } - /** - * If the requested notePath is within current note hoisting scope then keep the note hoisting also for the new tab. - */ - async openTabWithNoteWithHoisting(notePath, opts = {}) { + async openTabWithNoteWithHoisting( + notePath: string, + opts: { + activate?: boolean | null; + ntxId?: string | null; + mainNtxId?: string | null; + hoistedNoteId?: string | null; + viewScope?: Record | null; + } = {} + ): Promise { const noteContext = this.getActiveContext(); let hoistedNoteId = "root"; if (noteContext) { const resolvedNotePath = await treeService.resolveNotePath(notePath, noteContext.hoistedNoteId); - if (resolvedNotePath.includes(noteContext.hoistedNoteId) || resolvedNotePath.includes("_hidden")) { + if (resolvedNotePath?.includes(noteContext.hoistedNoteId) || resolvedNotePath?.includes("_hidden")) { hoistedNoteId = noteContext.hoistedNoteId; } } @@ -298,7 +321,16 @@ export default class TabManager extends Component { return this.openContextWithNote(notePath, opts); } - async openContextWithNote(notePath, opts = {}) { + async openContextWithNote( + notePath: string | null, + opts: { + activate?: boolean | null; + ntxId?: string | null; + mainNtxId?: string | null; + hoistedNoteId?: string | null; + viewScope?: Record | null; + } = {} + ): Promise { const activate = !!opts.activate; const ntxId = opts.ntxId || null; const mainNtxId = opts.mainNtxId || null; @@ -315,10 +347,10 @@ export default class TabManager extends Component { }); } - if (activate) { + if (activate && noteContext.notePath) { this.activateNoteContext(noteContext.ntxId, false); - await this.triggerEvent("noteSwitchedAndActivated", { + await this.triggerEvent("noteSwitchedAndActivatedEvent", { noteContext, notePath: noteContext.notePath // resolved note path }); @@ -327,21 +359,24 @@ export default class TabManager extends Component { return noteContext; } - async activateOrOpenNote(noteId) { + async activateOrOpenNote(noteId: string) { for (const noteContext of this.getNoteContexts()) { if (noteContext.note && noteContext.note.noteId === noteId) { this.activateNoteContext(noteContext.ntxId); - return; } } // if no tab with this note has been found we'll create new tab - await this.openContextWithNote(noteId, { activate: true }); } - async activateNoteContext(ntxId, triggerEvent = true) { + async activateNoteContext(ntxId: string | null, triggerEvent: boolean = true) { + if (!ntxId) { + logError("activateNoteContext: ntxId is null"); + return; + } + if (ntxId === this.activeNtxId) { return; } @@ -359,11 +394,7 @@ export default class TabManager extends Component { this.setCurrentNavigationStateToHash(); } - /** - * @param ntxId - * @returns {Promise} true if note context has been removed, false otherwise - */ - async removeNoteContext(ntxId) { + async removeNoteContext(ntxId: string | null) { // removing note context is an async process which can take some time, if users presses CTRL-W quickly, two // close events could interleave which would then lead to attempting to activate already removed context. return await this.mutex.runExclusively(async () => { @@ -373,7 +404,7 @@ export default class TabManager extends Component { noteContextToRemove = this.getNoteContextById(ntxId); } catch { // note context not found - return false; + return; } if (noteContextToRemove.isMainContext()) { @@ -383,7 +414,7 @@ export default class TabManager extends Component { if (noteContextToRemove.isEmpty()) { // this is already the empty note context, no point in closing it and replacing with another // empty tab - return false; + return; } await this.openEmptyTab(); @@ -399,7 +430,7 @@ export default class TabManager extends Component { const noteContextsToRemove = noteContextToRemove.getSubContexts(); const ntxIdsToRemove = noteContextsToRemove.map((nc) => nc.ntxId); - await this.triggerEvent("beforeNoteContextRemove", { ntxIds: ntxIdsToRemove }); + await this.triggerEvent("beforeNoteContextRemove", { ntxIds: ntxIdsToRemove.filter((id) => id !== null) }); if (!noteContextToRemove.isMainContext()) { const siblings = noteContextToRemove.getMainContext().getSubContexts(); @@ -421,12 +452,10 @@ export default class TabManager extends Component { } this.removeNoteContexts(noteContextsToRemove); - - return true; }); } - removeNoteContexts(noteContextsToRemove) { + removeNoteContexts(noteContextsToRemove: NoteContext[]) { const ntxIdsToRemove = noteContextsToRemove.map((nc) => nc.ntxId); const position = this.noteContexts.findIndex((nc) => ntxIdsToRemove.includes(nc.ntxId)); @@ -435,12 +464,12 @@ export default class TabManager extends Component { this.addToRecentlyClosedTabs(noteContextsToRemove, position); - this.triggerEvent("noteContextRemoved", { ntxIds: ntxIdsToRemove }); + this.triggerEvent("noteContextRemoved", { ntxIds: ntxIdsToRemove.filter((id) => id !== null) }); this.tabsUpdate.scheduleUpdate(); } - addToRecentlyClosedTabs(noteContexts, position) { + addToRecentlyClosedTabs(noteContexts: NoteContext[], position: number) { if (noteContexts.length === 1 && noteContexts[0].isEmpty()) { return; } @@ -448,26 +477,42 @@ export default class TabManager extends Component { this.recentlyClosedTabs.push({ contexts: noteContexts, position: position }); } - tabReorderEvent({ ntxIdsInOrder }) { - const order = {}; + tabReorderEvent({ ntxIdsInOrder }: { ntxIdsInOrder: string[] }) { + const order: Record = {}; let i = 0; for (const ntxId of ntxIdsInOrder) { for (const noteContext of this.getNoteContextById(ntxId).getSubContexts()) { - order[noteContext.ntxId] = i++; + if (noteContext.ntxId) { + order[noteContext.ntxId] = i++; + } } } - this.children.sort((a, b) => (order[a.ntxId] < order[b.ntxId] ? -1 : 1)); + this.children.sort((a, b) => { + if (!a.ntxId || !b.ntxId) return 0; + return (order[a.ntxId] ?? 0) < (order[b.ntxId] ?? 0) ? -1 : 1; + }); this.tabsUpdate.scheduleUpdate(); } - noteContextReorderEvent({ ntxIdsInOrder, oldMainNtxId, newMainNtxId }) { + noteContextReorderEvent({ + ntxIdsInOrder, + oldMainNtxId, + newMainNtxId + }: { + ntxIdsInOrder: string[]; + oldMainNtxId?: string; + newMainNtxId?: string; + }) { const order = Object.fromEntries(ntxIdsInOrder.map((v, i) => [v, i])); - this.children.sort((a, b) => (order[a.ntxId] < order[b.ntxId] ? -1 : 1)); + this.children.sort((a, b) => { + if (!a.ntxId || !b.ntxId) return 0; + return (order[a.ntxId] ?? 0) < (order[b.ntxId] ?? 0) ? -1 : 1; + }); if (oldMainNtxId && newMainNtxId) { this.children.forEach((c) => { @@ -485,7 +530,8 @@ export default class TabManager extends Component { } async activateNextTabCommand() { - const activeMainNtxId = this.getActiveMainContext().ntxId; + const activeMainNtxId = this.getActiveMainContext()?.ntxId; + if (!activeMainNtxId) return; const oldIdx = this.mainNoteContexts.findIndex((nc) => nc.ntxId === activeMainNtxId); const newActiveNtxId = this.mainNoteContexts[oldIdx === this.mainNoteContexts.length - 1 ? 0 : oldIdx + 1].ntxId; @@ -494,7 +540,8 @@ export default class TabManager extends Component { } async activatePreviousTabCommand() { - const activeMainNtxId = this.getActiveMainContext().ntxId; + const activeMainNtxId = this.getActiveMainContext()?.ntxId; + if (!activeMainNtxId) return; const oldIdx = this.mainNoteContexts.findIndex((nc) => nc.ntxId === activeMainNtxId); const newActiveNtxId = this.mainNoteContexts[oldIdx === 0 ? this.mainNoteContexts.length - 1 : oldIdx - 1].ntxId; @@ -503,12 +550,13 @@ export default class TabManager extends Component { } async closeActiveTabCommand() { - await this.removeNoteContext(this.activeNtxId); + if (this.activeNtxId) { + await this.removeNoteContext(this.activeNtxId); + } } - beforeUnloadEvent() { + beforeUnloadEvent(): boolean { this.tabsUpdate.updateNowIfNecessary(); - return true; // don't block closing the tab, this metadata is not that important } @@ -518,35 +566,39 @@ export default class TabManager extends Component { async closeAllTabsCommand() { for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) { - await this.removeNoteContext(ntxIdToRemove); - } - } - - async closeOtherTabsCommand({ ntxId }) { - for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) { - if (ntxIdToRemove !== ntxId) { + if (ntxIdToRemove) { await this.removeNoteContext(ntxIdToRemove); } } } - async closeRightTabsCommand({ ntxId }) { + async closeOtherTabsCommand({ ntxId }: { ntxId: string }) { + for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) { + if (ntxIdToRemove && ntxIdToRemove !== ntxId) { + await this.removeNoteContext(ntxIdToRemove); + } + } + } + + async closeRightTabsCommand({ ntxId }: { ntxId: string }) { const ntxIds = this.mainNoteContexts.map((nc) => nc.ntxId); const index = ntxIds.indexOf(ntxId); if (index !== -1) { const idsToRemove = ntxIds.slice(index + 1); for (const ntxIdToRemove of idsToRemove) { - await this.removeNoteContext(ntxIdToRemove); + if (ntxIdToRemove) { + await this.removeNoteContext(ntxIdToRemove); + } } } } - async closeTabCommand({ ntxId }) { + async closeTabCommand({ ntxId }: { ntxId: string }) { await this.removeNoteContext(ntxId); } - async moveTabToNewWindowCommand({ ntxId }) { + async moveTabToNewWindowCommand({ ntxId }: { ntxId: string }) { const { notePath, hoistedNoteId } = this.getNoteContextById(ntxId); const removed = await this.removeNoteContext(ntxId); @@ -556,17 +608,16 @@ export default class TabManager extends Component { } } - async copyTabToNewWindowCommand({ ntxId }) { + async copyTabToNewWindowCommand({ ntxId }: { ntxId: string }) { const { notePath, hoistedNoteId } = this.getNoteContextById(ntxId); this.triggerCommand("openInWindow", { notePath, hoistedNoteId }); } async reopenLastTabCommand() { - let closeLastEmptyTab = null; - - await this.mutex.runExclusively(async () => { + const closeLastEmptyTab: NoteContext | undefined = await this.mutex.runExclusively(async () => { + let closeLastEmptyTab if (this.recentlyClosedTabs.length === 0) { - return; + return closeLastEmptyTab; } if (this.noteContexts.length === 1 && this.noteContexts[0].isEmpty()) { @@ -575,6 +626,8 @@ export default class TabManager extends Component { } const lastClosedTab = this.recentlyClosedTabs.pop(); + if (!lastClosedTab) return closeLastEmptyTab; + const noteContexts = lastClosedTab.contexts; for (const noteContext of noteContexts) { @@ -589,25 +642,26 @@ export default class TabManager extends Component { ...this.noteContexts.slice(-noteContexts.length), ...this.noteContexts.slice(lastClosedTab.position, -noteContexts.length) ]; - await this.noteContextReorderEvent({ ntxIdsInOrder: ntxsInOrder.map((nc) => nc.ntxId) }); + this.noteContextReorderEvent({ ntxIdsInOrder: ntxsInOrder.map((nc) => nc.ntxId).filter((id) => id !== null) }); let mainNtx = noteContexts.find((nc) => nc.isMainContext()); if (mainNtx) { // reopened a tab, need to reorder new tab widget in tab row - await this.triggerEvent("contextsReopened", { + await this.triggerEvent("contextsReopenedEvent", { mainNtxId: mainNtx.ntxId, tabPosition: ntxsInOrder.filter((nc) => nc.isMainContext()).findIndex((nc) => nc.ntxId === mainNtx.ntxId) }); } else { // reopened a single split, need to reorder the pane widget in split note container - await this.triggerEvent("contextsReopened", { - ntxId: ntxsInOrder[lastClosedTab.position].ntxId, + await this.triggerEvent("contextsReopenedEvent", { + mainNtxId: ntxsInOrder[lastClosedTab.position].ntxId, // this is safe since lastClosedTab.position can never be 0 in this case - afterNtxId: ntxsInOrder[lastClosedTab.position - 1].ntxId + tabPosition: lastClosedTab.position - 1 }); } const noteContextToActivate = noteContexts.length === 1 ? noteContexts[0] : noteContexts.find((nc) => nc.isMainContext()); + if (!noteContextToActivate) return closeLastEmptyTab; await this.activateNoteContext(noteContextToActivate.ntxId); @@ -615,6 +669,7 @@ export default class TabManager extends Component { noteContext: noteContextToActivate, notePath: noteContextToActivate.notePath }); + return closeLastEmptyTab; }); if (closeLastEmptyTab) { @@ -626,7 +681,9 @@ export default class TabManager extends Component { this.tabsUpdate.scheduleUpdate(); } - async updateDocumentTitle(activeNoteContext) { + async updateDocumentTitle(activeNoteContext: NoteContext | null) { + if (!activeNoteContext) return; + const titleFragments = [ // it helps to navigate in history if note title is included in the title await activeNoteContext.getNavigationTitle(), @@ -636,7 +693,7 @@ export default class TabManager extends Component { document.title = titleFragments.join(" - "); } - async entitiesReloadedEvent({ loadResults }) { + async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) { const activeContext = this.getActiveContext(); if (activeContext && loadResults.isNoteReloaded(activeContext.noteId)) { @@ -646,7 +703,6 @@ export default class TabManager extends Component { async frocaReloadedEvent() { const activeContext = this.getActiveContext(); - if (activeContext) { await this.updateDocumentTitle(activeContext); } diff --git a/src/public/app/menus/link_context_menu.ts b/src/public/app/menus/link_context_menu.ts index 6456c6519..cef67b7da 100644 --- a/src/public/app/menus/link_context_menu.ts +++ b/src/public/app/menus/link_context_menu.ts @@ -22,13 +22,19 @@ function getItems(): MenuItem[] { function handleLinkContextMenuItem(command: string | undefined, notePath: string, viewScope = {}, hoistedNoteId: string | null = null) { if (!hoistedNoteId) { - hoistedNoteId = appContext.tabManager.getActiveContext().hoistedNoteId; + hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId ?? null; } if (command === "openNoteInNewTab") { appContext.tabManager.openContextWithNote(notePath, { hoistedNoteId, viewScope }); } else if (command === "openNoteInNewSplit") { - const subContexts = appContext.tabManager.getActiveContext().getSubContexts(); + const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts(); + + if (!subContexts) { + logError("subContexts is null"); + return; + } + const { ntxId } = subContexts[subContexts.length - 1]; appContext.triggerCommand("openNewNoteSplit", { ntxId, notePath, hoistedNoteId, viewScope }); diff --git a/src/public/app/services/link.ts b/src/public/app/services/link.ts index c57ec5494..bc3baf924 100644 --- a/src/public/app/services/link.ts +++ b/src/public/app/services/link.ts @@ -288,11 +288,15 @@ function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDownEvent const noteContext = ntxId ? appContext.tabManager.getNoteContextById(ntxId) : appContext.tabManager.getActiveContext(); - noteContext.setNote(notePath, { viewScope }).then(() => { - if (noteContext !== appContext.tabManager.getActiveContext()) { - appContext.tabManager.activateNoteContext(noteContext.ntxId); - } - }); + if (noteContext) { + noteContext.setNote(notePath, { viewScope }).then(() => { + if (noteContext !== appContext.tabManager.getActiveContext()) { + appContext.tabManager.activateNoteContext(noteContext.ntxId); + } + }); + } else { + appContext.tabManager.openContextWithNote(notePath, { viewScope, activate: true }); + } } } else if (hrefLink) { const withinEditLink = $link?.hasClass("ck-link-actions__preview"); diff --git a/src/public/app/services/tree.ts b/src/public/app/services/tree.ts index e7c94ca0e..ff4c34210 100644 --- a/src/public/app/services/tree.ts +++ b/src/public/app/services/tree.ts @@ -138,7 +138,7 @@ function getParentProtectedStatus(node: Fancytree.FancytreeNode) { return hoistedNoteService.isHoistedNode(node) ? false : node.getParent().data.isProtected; } -function getNoteIdFromUrl(urlOrNotePath: string | undefined) { +function getNoteIdFromUrl(urlOrNotePath: string | null | undefined) { if (!urlOrNotePath) { return null; } diff --git a/src/public/app/utils/mutex.ts b/src/public/app/utils/mutex.ts index 76ea57b0d..197e2f134 100644 --- a/src/public/app/utils/mutex.ts +++ b/src/public/app/utils/mutex.ts @@ -16,7 +16,7 @@ export default class Mutex { return newPromise; } - async runExclusively(cb: () => Promise) { + async runExclusively(cb: () => Promise) { const unlock = await this.lock(); try { diff --git a/src/public/app/widgets/containers/split_note_container.ts b/src/public/app/widgets/containers/split_note_container.ts index 61f82b793..9b828120b 100644 --- a/src/public/app/widgets/containers/split_note_container.ts +++ b/src/public/app/widgets/containers/split_note_container.ts @@ -63,7 +63,7 @@ export default class SplitNoteContainer extends FlexContainer { hoistedNoteId?: string; viewScope?: any; }) { - const mainNtxId = appContext.tabManager.getActiveMainContext().ntxId; + const mainNtxId = appContext.tabManager.getActiveMainContext()?.ntxId; if (!mainNtxId) { logError("empty mainNtxId!"); @@ -76,7 +76,7 @@ export default class SplitNoteContainer extends FlexContainer { ntxId = mainNtxId; } - hoistedNoteId = hoistedNoteId || appContext.tabManager.getActiveContext().hoistedNoteId; + hoistedNoteId = hoistedNoteId || appContext.tabManager.getActiveContext()?.hoistedNoteId; const noteContext = await appContext.tabManager.openEmptyTab(null, hoistedNoteId, mainNtxId); diff --git a/src/public/app/widgets/tab_row.ts b/src/public/app/widgets/tab_row.ts index f0af54493..c726cc528 100644 --- a/src/public/app/widgets/tab_row.ts +++ b/src/public/app/widgets/tab_row.ts @@ -1,10 +1,10 @@ -import Draggabilly, { type DraggabillyCallback, type MoveVector } from "draggabilly"; +import Draggabilly, { type MoveVector } from "draggabilly"; import { t } from "../services/i18n.js"; import BasicWidget from "./basic_widget.js"; import contextMenu from "../menus/context_menu.js"; import utils from "../services/utils.js"; import keyboardActionService from "../services/keyboard_actions.js"; -import appContext, { type CommandData, type CommandListenerData, type EventData } from "../components/app_context.js"; +import appContext, { type CommandListenerData, type EventData } from "../components/app_context.js"; import froca from "../services/froca.js"; import attributeService from "../services/attributes.js"; import type NoteContext from "../components/note_context.js"; @@ -419,13 +419,13 @@ export default class TabRowWidget extends BasicWidget { closeActiveTabCommand({ $el }: CommandListenerData<"closeActiveTab">) { const ntxId = $el.closest(".note-tab").attr("data-ntx-id"); - appContext.tabManager.removeNoteContext(ntxId); + appContext.tabManager.removeNoteContext(ntxId ?? null); } setTabCloseEvent($tab: JQuery) { $tab.on("mousedown", (e) => { if (e.which === 2) { - appContext.tabManager.removeNoteContext($tab.attr("data-ntx-id")); + appContext.tabManager.removeNoteContext($tab.attr("data-ntx-id") ?? null); return true; // event has been handled } @@ -494,7 +494,7 @@ export default class TabRowWidget extends BasicWidget { return $tab.attr("data-ntx-id"); } - noteContextRemovedEvent({ ntxIds }: EventData<"noteContextRemovedEvent">) { + noteContextRemovedEvent({ ntxIds }: EventData<"noteContextRemoved">) { for (const ntxId of ntxIds) { this.removeTab(ntxId); } @@ -516,7 +516,7 @@ export default class TabRowWidget extends BasicWidget { this.draggabillyDragging.element.style.transform = ""; this.draggabillyDragging.dragEnd(); this.draggabillyDragging.isDragging = false; - this.draggabillyDragging.positionDrag = () => {}; // Prevent Draggabilly from updating tabEl.style.transform in later frames + this.draggabillyDragging.positionDrag = () => { }; // Prevent Draggabilly from updating tabEl.style.transform in later frames this.draggabillyDragging.destroy(); this.draggabillyDragging = null; } @@ -650,7 +650,7 @@ export default class TabRowWidget extends BasicWidget { } contextsReopenedEvent({ mainNtxId, tabPosition }: EventData<"contextsReopenedEvent">) { - if (mainNtxId === undefined || tabPosition === undefined) { + if (!mainNtxId || !tabPosition) { // no tab reopened return; } @@ -748,7 +748,7 @@ export default class TabRowWidget extends BasicWidget { hoistedNoteChangedEvent({ ntxId }: EventData<"hoistedNoteChanged">) { const $tab = this.getTabById(ntxId); - if ($tab) { + if ($tab && ntxId) { const noteContext = appContext.tabManager.getNoteContextById(ntxId); this.updateTab($tab, noteContext); From a9d8d7d3c5f8237dbcb726af4e4d475785e2d730 Mon Sep 17 00:00:00 2001 From: Jin <22962980+JYC333@users.noreply.github.com> Date: Mon, 3 Mar 2025 22:56:24 +0100 Subject: [PATCH 2/8] =?UTF-8?q?fix:=20=F0=9F=90=9B=20fix=20wrong=20trigger?= =?UTF-8?q?Event=20usage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/public/app/components/app_context.ts | 6 +++--- src/public/app/components/tab_manager.ts | 9 ++++----- src/public/app/widgets/containers/scrolling_container.ts | 2 +- .../app/widgets/containers/split_note_container.ts | 2 +- src/public/app/widgets/note_context_aware_widget.ts | 2 +- src/public/app/widgets/tab_row.ts | 4 ++-- 6 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/public/app/components/app_context.ts b/src/public/app/components/app_context.ts index a8616b1c6..105af75f6 100644 --- a/src/public/app/components/app_context.ts +++ b/src/public/app/components/app_context.ts @@ -296,7 +296,7 @@ type EventMappings = { noteContext: NoteContext; notePath?: string | null; }; - noteSwitchedAndActivatedEvent: { + noteSwitchedAndActivated: { noteContext: NoteContext; notePath: string; }; @@ -326,7 +326,7 @@ type EventMappings = { noteId: string; ntxId: string | null; }; - contextsReopenedEvent: { + contextsReopened: { mainNtxId: string | null; tabPosition: number; }; @@ -362,7 +362,7 @@ type EventMappings = { relationMapResetPanZoom: { ntxId: string | null | undefined }; relationMapResetZoomIn: { ntxId: string | null | undefined }; relationMapResetZoomOut: { ntxId: string | null | undefined }; - activeNoteChangedEvent: {}; + activeNoteChanged: {}; showAddLinkDialog: { textTypeWidget: EditableTextTypeWidget; text: string; diff --git a/src/public/app/components/tab_manager.ts b/src/public/app/components/tab_manager.ts index b441c7819..f222a4655 100644 --- a/src/public/app/components/tab_manager.ts +++ b/src/public/app/components/tab_manager.ts @@ -163,7 +163,7 @@ export default class TabManager extends Component { const activeNoteContext = this.getActiveContext(); this.updateDocumentTitle(activeNoteContext); - this.triggerEvent("activeNoteChangedEvent", {}); // trigger this even in on popstate event + this.triggerEvent("activeNoteChanged", {}); // trigger this even in on popstate event } calculateHash(): string { @@ -338,7 +338,6 @@ export default class TabManager extends Component { const viewScope = opts.viewScope || { viewMode: "default" }; const noteContext = await this.openEmptyTab(ntxId, hoistedNoteId, mainNtxId); - if (notePath) { await noteContext.setNote(notePath, { // if activate is false, then send normal noteSwitched event @@ -350,7 +349,7 @@ export default class TabManager extends Component { if (activate && noteContext.notePath) { this.activateNoteContext(noteContext.ntxId, false); - await this.triggerEvent("noteSwitchedAndActivatedEvent", { + await this.triggerEvent("noteSwitchedAndActivated", { noteContext, notePath: noteContext.notePath // resolved note path }); @@ -647,13 +646,13 @@ export default class TabManager extends Component { let mainNtx = noteContexts.find((nc) => nc.isMainContext()); if (mainNtx) { // reopened a tab, need to reorder new tab widget in tab row - await this.triggerEvent("contextsReopenedEvent", { + await this.triggerEvent("contextsReopened", { mainNtxId: mainNtx.ntxId, tabPosition: ntxsInOrder.filter((nc) => nc.isMainContext()).findIndex((nc) => nc.ntxId === mainNtx.ntxId) }); } else { // reopened a single split, need to reorder the pane widget in split note container - await this.triggerEvent("contextsReopenedEvent", { + await this.triggerEvent("contextsReopened", { mainNtxId: ntxsInOrder[lastClosedTab.position].ntxId, // this is safe since lastClosedTab.position can never be 0 in this case tabPosition: lastClosedTab.position - 1 diff --git a/src/public/app/widgets/containers/scrolling_container.ts b/src/public/app/widgets/containers/scrolling_container.ts index 62d4ec2c4..fab51254c 100644 --- a/src/public/app/widgets/containers/scrolling_container.ts +++ b/src/public/app/widgets/containers/scrolling_container.ts @@ -24,7 +24,7 @@ export default class ScrollingContainer extends Container { this.$widget.scrollTop(0); } - async noteSwitchedAndActivatedEvent({ noteContext, notePath }: EventData<"noteSwitchedAndActivatedEvent">) { + async noteSwitchedAndActivatedEvent({ noteContext, notePath }: EventData<"noteSwitchedAndActivated">) { this.noteContext = noteContext; this.$widget.scrollTop(0); diff --git a/src/public/app/widgets/containers/split_note_container.ts b/src/public/app/widgets/containers/split_note_container.ts index 9b828120b..8e686476c 100644 --- a/src/public/app/widgets/containers/split_note_container.ts +++ b/src/public/app/widgets/containers/split_note_container.ts @@ -199,7 +199,7 @@ export default class SplitNoteContainer extends FlexContainer { return Promise.resolve(); } - if (widget.hasBeenAlreadyShown || name === "noteSwitchedAndActivatedEvent" || appContext.tabManager.getActiveMainContext() === noteContext.getMainContext()) { + if (widget.hasBeenAlreadyShown || name === "noteSwitchedAndActivated" || appContext.tabManager.getActiveMainContext() === noteContext.getMainContext()) { widget.hasBeenAlreadyShown = true; return Promise.all([ diff --git a/src/public/app/widgets/note_context_aware_widget.ts b/src/public/app/widgets/note_context_aware_widget.ts index 3c1153c2f..639061f38 100644 --- a/src/public/app/widgets/note_context_aware_widget.ts +++ b/src/public/app/widgets/note_context_aware_widget.ts @@ -105,7 +105,7 @@ class NoteContextAwareWidget extends BasicWidget { } // when note is both switched and activated, this should not produce a double refresh - async noteSwitchedAndActivatedEvent({ noteContext, notePath }: EventData<"noteSwitchedAndActivatedEvent">) { + async noteSwitchedAndActivatedEvent({ noteContext, notePath }: EventData<"noteSwitchedAndActivated">) { this.noteContext = noteContext; // if notePath does not match, then the noteContext has been switched to another note in the meantime diff --git a/src/public/app/widgets/tab_row.ts b/src/public/app/widgets/tab_row.ts index c726cc528..b2cf11fd8 100644 --- a/src/public/app/widgets/tab_row.ts +++ b/src/public/app/widgets/tab_row.ts @@ -628,7 +628,7 @@ export default class TabRowWidget extends BasicWidget { return closestIndex; } - noteSwitchedAndActivatedEvent({ noteContext }: EventData<"noteSwitchedAndActivatedEvent">) { + noteSwitchedAndActivatedEvent({ noteContext }: EventData<"noteSwitchedAndActivated">) { this.activeContextChangedEvent(); this.updateTabById(noteContext.mainNtxId || noteContext.ntxId); @@ -649,7 +649,7 @@ export default class TabRowWidget extends BasicWidget { this.updateTabById(newMainNtxId); } - contextsReopenedEvent({ mainNtxId, tabPosition }: EventData<"contextsReopenedEvent">) { + contextsReopenedEvent({ mainNtxId, tabPosition }: EventData<"contextsReopened">) { if (!mainNtxId || !tabPosition) { // no tab reopened return; From c9c18146f4e5b2885075d0c01f7bad960aba5f37 Mon Sep 17 00:00:00 2001 From: Jin <22962980+JYC333@users.noreply.github.com> Date: Mon, 3 Mar 2025 23:15:58 +0100 Subject: [PATCH 3/8] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20refactor=20serva?= =?UTF-8?q?l=20event=20names?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refactore serval event names to follow the current usage in repo --- src/public/app/components/app_context.ts | 5 +---- src/public/app/widgets/buttons/close_pane_button.ts | 2 +- src/public/app/widgets/floating_buttons/code_buttons.ts | 2 +- src/public/app/widgets/note_context_aware_widget.ts | 2 +- src/public/app/widgets/tab_row.ts | 2 +- 5 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/public/app/components/app_context.ts b/src/public/app/components/app_context.ts index 105af75f6..cde4f217a 100644 --- a/src/public/app/components/app_context.ts +++ b/src/public/app/components/app_context.ts @@ -303,9 +303,6 @@ type EventMappings = { setNoteContext: { noteContext: NoteContext; }; - noteTypeMimeChangedEvent: { - noteId: string; - }; reEvaluateHighlightsListWidgetVisibility: { noteId: string | undefined; }; @@ -333,7 +330,7 @@ type EventMappings = { noteDetailRefreshed: { ntxId?: string | null; }; - noteContextReorderEvent: { + noteContextReorder: { oldMainNtxId: string; newMainNtxId: string; ntxIdsInOrder: string[]; diff --git a/src/public/app/widgets/buttons/close_pane_button.ts b/src/public/app/widgets/buttons/close_pane_button.ts index 09e9aef11..1f34b6a35 100644 --- a/src/public/app/widgets/buttons/close_pane_button.ts +++ b/src/public/app/widgets/buttons/close_pane_button.ts @@ -12,7 +12,7 @@ export default class ClosePaneButton extends OnClickButtonWidget { ); } - async noteContextReorderEvent({ ntxIdsInOrder }: EventData<"noteContextReorderEvent">) { + async noteContextReorderEvent({ ntxIdsInOrder }: EventData<"noteContextReorder">) { this.refresh(); } diff --git a/src/public/app/widgets/floating_buttons/code_buttons.ts b/src/public/app/widgets/floating_buttons/code_buttons.ts index ca6491f76..496688f9d 100644 --- a/src/public/app/widgets/floating_buttons/code_buttons.ts +++ b/src/public/app/widgets/floating_buttons/code_buttons.ts @@ -85,7 +85,7 @@ export default class CodeButtonsWidget extends NoteContextAwareWidget { this.$openTriliumApiDocsButton.toggle(note.mime.startsWith("application/javascript;env=")); } - async noteTypeMimeChangedEvent({ noteId }: EventData<"noteTypeMimeChangedEvent">) { + async noteTypeMimeChangedEvent({ noteId }: EventData<"noteTypeMimeChanged">) { if (this.isNote(noteId)) { await this.refresh(); } diff --git a/src/public/app/widgets/note_context_aware_widget.ts b/src/public/app/widgets/note_context_aware_widget.ts index 639061f38..f43030ed8 100644 --- a/src/public/app/widgets/note_context_aware_widget.ts +++ b/src/public/app/widgets/note_context_aware_widget.ts @@ -119,7 +119,7 @@ class NoteContextAwareWidget extends BasicWidget { this.noteContext = noteContext; } - async noteTypeMimeChangedEvent({ noteId }: EventData<"noteTypeMimeChangedEvent">) { + async noteTypeMimeChangedEvent({ noteId }: EventData<"noteTypeMimeChanged">) { if (this.isNote(noteId)) { await this.refresh(); } diff --git a/src/public/app/widgets/tab_row.ts b/src/public/app/widgets/tab_row.ts index b2cf11fd8..0f60a9c2e 100644 --- a/src/public/app/widgets/tab_row.ts +++ b/src/public/app/widgets/tab_row.ts @@ -638,7 +638,7 @@ export default class TabRowWidget extends BasicWidget { this.updateTabById(noteContext.mainNtxId || noteContext.ntxId); } - noteContextReorderEvent({ oldMainNtxId, newMainNtxId }: EventData<"noteContextReorderEvent">) { + noteContextReorderEvent({ oldMainNtxId, newMainNtxId }: EventData<"noteContextReorder">) { if (!oldMainNtxId || !newMainNtxId) { // no need to update tab row return; From 0858f531e4e6bf35e4a5ac0ec83777705a855e40 Mon Sep 17 00:00:00 2001 From: Jin <22962980+JYC333@users.noreply.github.com> Date: Wed, 5 Mar 2025 13:40:58 +0100 Subject: [PATCH 4/8] =?UTF-8?q?fix:=20=F0=9F=90=9B=20can't=20move=20a=20ta?= =?UTF-8?q?b=20to=20new=20window?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/public/app/components/tab_manager.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/public/app/components/tab_manager.ts b/src/public/app/components/tab_manager.ts index f222a4655..8906d496a 100644 --- a/src/public/app/components/tab_manager.ts +++ b/src/public/app/components/tab_manager.ts @@ -393,17 +393,17 @@ export default class TabManager extends Component { this.setCurrentNavigationStateToHash(); } - async removeNoteContext(ntxId: string | null) { + async removeNoteContext(ntxId: string | null): Promise { // removing note context is an async process which can take some time, if users presses CTRL-W quickly, two // close events could interleave which would then lead to attempting to activate already removed context. - return await this.mutex.runExclusively(async () => { + return await this.mutex.runExclusively(async (): Promise => { let noteContextToRemove; try { noteContextToRemove = this.getNoteContextById(ntxId); } catch { // note context not found - return; + return false; } if (noteContextToRemove.isMainContext()) { @@ -413,7 +413,7 @@ export default class TabManager extends Component { if (noteContextToRemove.isEmpty()) { // this is already the empty note context, no point in closing it and replacing with another // empty tab - return; + return false; } await this.openEmptyTab(); @@ -451,6 +451,7 @@ export default class TabManager extends Component { } this.removeNoteContexts(noteContextsToRemove); + return true; }); } From e12be14dc9a873d77c7658828f55bc20b7da7065 Mon Sep 17 00:00:00 2001 From: Jin <22962980+JYC333@users.noreply.github.com> Date: Tue, 18 Mar 2025 17:39:59 +0100 Subject: [PATCH 5/8] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20remove=20redunda?= =?UTF-8?q?nt=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/public/app/components/tab_manager.ts | 14 ++++---------- src/public/app/widgets/tab_row.ts | 4 ++-- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/public/app/components/tab_manager.ts b/src/public/app/components/tab_manager.ts index 8906d496a..4cac7a5e3 100644 --- a/src/public/app/components/tab_manager.ts +++ b/src/public/app/components/tab_manager.ts @@ -550,9 +550,7 @@ export default class TabManager extends Component { } async closeActiveTabCommand() { - if (this.activeNtxId) { - await this.removeNoteContext(this.activeNtxId); - } + await this.removeNoteContext(this.activeNtxId); } beforeUnloadEvent(): boolean { @@ -566,15 +564,13 @@ export default class TabManager extends Component { async closeAllTabsCommand() { for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) { - if (ntxIdToRemove) { - await this.removeNoteContext(ntxIdToRemove); - } + await this.removeNoteContext(ntxIdToRemove); } } async closeOtherTabsCommand({ ntxId }: { ntxId: string }) { for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) { - if (ntxIdToRemove && ntxIdToRemove !== ntxId) { + if (ntxIdToRemove !== ntxId) { await this.removeNoteContext(ntxIdToRemove); } } @@ -587,9 +583,7 @@ export default class TabManager extends Component { if (index !== -1) { const idsToRemove = ntxIds.slice(index + 1); for (const ntxIdToRemove of idsToRemove) { - if (ntxIdToRemove) { - await this.removeNoteContext(ntxIdToRemove); - } + await this.removeNoteContext(ntxIdToRemove); } } } diff --git a/src/public/app/widgets/tab_row.ts b/src/public/app/widgets/tab_row.ts index 0f60a9c2e..68557df3a 100644 --- a/src/public/app/widgets/tab_row.ts +++ b/src/public/app/widgets/tab_row.ts @@ -419,13 +419,13 @@ export default class TabRowWidget extends BasicWidget { closeActiveTabCommand({ $el }: CommandListenerData<"closeActiveTab">) { const ntxId = $el.closest(".note-tab").attr("data-ntx-id"); - appContext.tabManager.removeNoteContext(ntxId ?? null); + appContext.tabManager.removeNoteContext(ntxId); } setTabCloseEvent($tab: JQuery) { $tab.on("mousedown", (e) => { if (e.which === 2) { - appContext.tabManager.removeNoteContext($tab.attr("data-ntx-id") ?? null); + appContext.tabManager.removeNoteContext($tab.attr("data-ntx-id")); return true; // event has been handled } From b18cfb5d20a50f260bdb32ab3d3ff5d2872f3747 Mon Sep 17 00:00:00 2001 From: Jin <22962980+JYC333@users.noreply.github.com> Date: Tue, 18 Mar 2025 18:44:48 +0100 Subject: [PATCH 6/8] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20Fix=20ts=20error?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/public/app/services/utils.ts | 6 +++++- src/public/app/widgets/dialogs/recent_changes.ts | 10 ++++++++-- src/public/app/widgets/quick_search.ts | 10 ++++++++-- src/public/app/widgets/tab_row.ts | 4 ++-- src/public/app/widgets/type_widgets/empty.ts | 5 ++++- 5 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/public/app/services/utils.ts b/src/public/app/services/utils.ts index 53fd85a7b..ee76093bb 100644 --- a/src/public/app/services/utils.ts +++ b/src/public/app/services/utils.ts @@ -411,7 +411,11 @@ async function openInAppHelp($button: JQuery) { if (inAppHelpPage) { // Dynamic import to avoid import issues in tests. const appContext = (await import("../components/app_context.js")).default; - const subContexts = appContext.tabManager.getActiveContext().getSubContexts(); + const activeContext = appContext.tabManager.getActiveContext(); + if (!activeContext) { + return; + } + const subContexts = activeContext.getSubContexts(); const targetNote = `_help_${inAppHelpPage}`; const helpSubcontext = subContexts.find((s) => s.viewScope?.viewMode === "contextual-help"); const viewScope: ViewScope = { diff --git a/src/public/app/widgets/dialogs/recent_changes.ts b/src/public/app/widgets/dialogs/recent_changes.ts index 9961817b1..dbaca5268 100644 --- a/src/public/app/widgets/dialogs/recent_changes.ts +++ b/src/public/app/widgets/dialogs/recent_changes.ts @@ -115,7 +115,10 @@ export default class RecentChangesDialog extends BasicWidget { await ws.waitForMaxKnownEntityChangeId(); - appContext.tabManager.getActiveContext().setNote(change.noteId); + const activeContext = appContext.tabManager.getActiveContext(); + if (activeContext) { + activeContext.setNote(change.noteId); + } } }); @@ -141,7 +144,10 @@ export default class RecentChangesDialog extends BasicWidget { // Skip clicks on the link or deleted notes if (e.target?.nodeName !== "A" && !change.current_isDeleted) { // Open the current note - appContext.tabManager.getActiveContext().setNote(change.noteId); + const activeContext = appContext.tabManager.getActiveContext(); + if (activeContext) { + activeContext.setNote(change.noteId); + } } }) .toggleClass("deleted-note", !!change.current_isDeleted) diff --git a/src/public/app/widgets/quick_search.ts b/src/public/app/widgets/quick_search.ts index 90ed9325e..f38d5e742 100644 --- a/src/public/app/widgets/quick_search.ts +++ b/src/public/app/widgets/quick_search.ts @@ -140,13 +140,19 @@ export default class QuickSearchWidget extends BasicWidget { if (!e.target || e.target.nodeName !== "A") { // click on the link is handled by link handling, but we want the whole item clickable - appContext.tabManager.getActiveContext().setNote(note.noteId); + const activeContext = appContext.tabManager.getActiveContext(); + if (activeContext) { + activeContext.setNote(note.noteId); + } } }); shortcutService.bindElShortcut($link, "return", () => { this.dropdown.hide(); - appContext.tabManager.getActiveContext().setNote(note.noteId); + const activeContext = appContext.tabManager.getActiveContext(); + if (activeContext) { + activeContext.setNote(note.noteId); + } }); this.$dropdownMenu.append($link); diff --git a/src/public/app/widgets/tab_row.ts b/src/public/app/widgets/tab_row.ts index 68557df3a..0f60a9c2e 100644 --- a/src/public/app/widgets/tab_row.ts +++ b/src/public/app/widgets/tab_row.ts @@ -419,13 +419,13 @@ export default class TabRowWidget extends BasicWidget { closeActiveTabCommand({ $el }: CommandListenerData<"closeActiveTab">) { const ntxId = $el.closest(".note-tab").attr("data-ntx-id"); - appContext.tabManager.removeNoteContext(ntxId); + appContext.tabManager.removeNoteContext(ntxId ?? null); } setTabCloseEvent($tab: JQuery) { $tab.on("mousedown", (e) => { if (e.which === 2) { - appContext.tabManager.removeNoteContext($tab.attr("data-ntx-id")); + appContext.tabManager.removeNoteContext($tab.attr("data-ntx-id") ?? null); return true; // event has been handled } diff --git a/src/public/app/widgets/type_widgets/empty.ts b/src/public/app/widgets/type_widgets/empty.ts index 8338f53ae..e2a79e0c4 100644 --- a/src/public/app/widgets/type_widgets/empty.ts +++ b/src/public/app/widgets/type_widgets/empty.ts @@ -87,7 +87,10 @@ export default class EmptyTypeWidget extends TypeWidget { return false; } - appContext.tabManager.getActiveContext().setNote(suggestion.notePath); + const activeContext = appContext.tabManager.getActiveContext(); + if (activeContext) { + activeContext.setNote(suggestion.notePath); + } }); this.$workspaceNotes = this.$widget.find(".workspace-notes"); From ae1a4b7a80fbb80b399fe25d071e0b9739074cd9 Mon Sep 17 00:00:00 2001 From: Jin <22962980+JYC333@users.noreply.github.com> Date: Tue, 18 Mar 2025 18:51:22 +0100 Subject: [PATCH 7/8] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Fix=20tab=20empty=20p?= =?UTF-8?q?ath=20behavior?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/public/app/components/tab_manager.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/public/app/components/tab_manager.ts b/src/public/app/components/tab_manager.ts index 4cac7a5e3..a4d00a075 100644 --- a/src/public/app/components/tab_manager.ts +++ b/src/public/app/components/tab_manager.ts @@ -98,8 +98,7 @@ export default class TabManager extends Component { ntxId: parsedFromUrl.ntxId, active: true, hoistedNoteId: parsedFromUrl.hoistedNoteId || "root", - viewScope: parsedFromUrl.viewScope || {}, - mainNtxId: null + viewScope: parsedFromUrl.viewScope || {} }); } else if (!filteredNoteContexts.find((tab: NoteContextState) => tab.active)) { filteredNoteContexts[0].active = true; @@ -279,10 +278,7 @@ export default class TabManager extends Component { } async openInNewTab(targetNoteId: string, hoistedNoteId: string | null = null) { - const noteContext = await this.openEmptyTab( - null, - hoistedNoteId || this.getActiveContext()?.hoistedNoteId - ); + const noteContext = await this.openEmptyTab(null, hoistedNoteId || this.getActiveContext()?.hoistedNoteId); await noteContext.setNote(targetNoteId); } From 49d7fa17354f895203ab57588478ccd4a0ac6331 Mon Sep 17 00:00:00 2001 From: Jin <22962980+JYC333@users.noreply.github.com> Date: Tue, 18 Mar 2025 22:01:08 +0100 Subject: [PATCH 8/8] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Fix=20playwright=20te?= =?UTF-8?q?st?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- e2e/support/app.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/e2e/support/app.ts b/e2e/support/app.ts index 64e60d74e..55f36a7ff 100644 --- a/e2e/support/app.ts +++ b/e2e/support/app.ts @@ -75,6 +75,8 @@ export default class App { */ async closeAllTabs() { await this.triggerCommand("closeAllTabs"); + // Page in Playwright is not updated somehow, need to click on the tab to make sure it's rendered + await this.getTab(0).click(); } /**