mirror of
https://github.com/zadam/trilium.git
synced 2025-11-13 16:55:50 +01:00
chore(monorepo): relocate client files
This commit is contained in:
593
apps/client/src/components/app_context.ts
Normal file
593
apps/client/src/components/app_context.ts
Normal file
@@ -0,0 +1,593 @@
|
||||
import froca from "../services/froca.js";
|
||||
import bundleService from "../services/bundle.js";
|
||||
import RootCommandExecutor from "./root_command_executor.js";
|
||||
import Entrypoints, { type SqlExecuteResults } from "./entrypoints.js";
|
||||
import options from "../services/options.js";
|
||||
import utils, { hasTouchBar } from "../services/utils.js";
|
||||
import zoomComponent from "./zoom.js";
|
||||
import TabManager from "./tab_manager.js";
|
||||
import Component from "./component.js";
|
||||
import keyboardActionsService from "../services/keyboard_actions.js";
|
||||
import linkService, { type ViewScope } from "../services/link.js";
|
||||
import MobileScreenSwitcherExecutor, { type Screen } from "./mobile_screen_switcher.js";
|
||||
import MainTreeExecutors from "./main_tree_executors.js";
|
||||
import toast from "../services/toast.js";
|
||||
import ShortcutComponent from "./shortcut_component.js";
|
||||
import { t, initLocale } from "../services/i18n.js";
|
||||
import type NoteDetailWidget from "../widgets/note_detail.js";
|
||||
import type { ResolveOptions } from "../widgets/dialogs/delete_notes.js";
|
||||
import type { PromptDialogOptions } from "../widgets/dialogs/prompt.js";
|
||||
import type { ConfirmWithMessageOptions, ConfirmWithTitleOptions } from "../widgets/dialogs/confirm.js";
|
||||
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 TypeWidget from "../widgets/type_widgets/type_widget.js";
|
||||
import type EditableTextTypeWidget from "../widgets/type_widgets/editable_text.js";
|
||||
import type { NativeImage, TouchBar } from "electron";
|
||||
import TouchBarComponent from "./touch_bar.js";
|
||||
|
||||
interface Layout {
|
||||
getRootWidget: (appContext: AppContext) => RootWidget;
|
||||
}
|
||||
|
||||
interface RootWidget extends Component {
|
||||
render: () => JQuery<HTMLElement>;
|
||||
}
|
||||
|
||||
interface BeforeUploadListener extends Component {
|
||||
beforeUnloadEvent(): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base interface for the data/arguments for a given command (see {@link CommandMappings}).
|
||||
*/
|
||||
export interface CommandData {
|
||||
ntxId?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a set of commands that are triggered from the context menu, providing information such as the selected note.
|
||||
*/
|
||||
export interface ContextMenuCommandData extends CommandData {
|
||||
node: Fancytree.FancytreeNode;
|
||||
notePath?: string;
|
||||
noteId?: string;
|
||||
selectedOrActiveBranchIds: string[];
|
||||
selectedOrActiveNoteIds?: string[];
|
||||
}
|
||||
|
||||
export interface NoteCommandData extends CommandData {
|
||||
notePath?: string | null;
|
||||
hoistedNoteId?: string | null;
|
||||
viewScope?: ViewScope;
|
||||
}
|
||||
|
||||
export interface ExecuteCommandData<T> extends CommandData {
|
||||
resolve: (data: T) => void;
|
||||
}
|
||||
|
||||
export interface NoteSwitchedContext {
|
||||
noteContext: NoteContext;
|
||||
notePath: string | null | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys represent the different commands that can be triggered via {@link AppContext#triggerCommand} (first argument), and the values represent the data or arguments definition of the given command. All data for commands must extend {@link CommandData}.
|
||||
*/
|
||||
export type CommandMappings = {
|
||||
"api-log-messages": CommandData;
|
||||
focusTree: CommandData;
|
||||
focusOnTitle: CommandData;
|
||||
focusOnDetail: CommandData;
|
||||
focusOnSearchDefinition: Required<CommandData>;
|
||||
searchNotes: CommandData & {
|
||||
searchString?: string;
|
||||
ancestorNoteId?: string | null;
|
||||
};
|
||||
closeTocCommand: CommandData;
|
||||
closeHlt: CommandData;
|
||||
showLaunchBarSubtree: CommandData;
|
||||
showRevisions: CommandData;
|
||||
showLlmChat: CommandData;
|
||||
createAiChat: CommandData;
|
||||
showOptions: CommandData & {
|
||||
section: string;
|
||||
};
|
||||
showExportDialog: CommandData & {
|
||||
notePath: string;
|
||||
defaultType: "single" | "subtree";
|
||||
};
|
||||
showDeleteNotesDialog: CommandData & {
|
||||
branchIdsToDelete: string[];
|
||||
callback: (value: ResolveOptions) => void;
|
||||
forceDeleteAllClones: boolean;
|
||||
};
|
||||
showConfirmDeleteNoteBoxWithNoteDialog: ConfirmWithTitleOptions;
|
||||
openedFileUpdated: CommandData & {
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
lastModifiedMs: number;
|
||||
filePath: string;
|
||||
};
|
||||
focusAndSelectTitle: CommandData & {
|
||||
isNewNote?: boolean;
|
||||
};
|
||||
showPromptDialog: PromptDialogOptions;
|
||||
showInfoDialog: ConfirmWithMessageOptions;
|
||||
showConfirmDialog: ConfirmWithMessageOptions;
|
||||
showRecentChanges: CommandData & { ancestorNoteId: string };
|
||||
showImportDialog: CommandData & { noteId: string };
|
||||
openNewNoteSplit: NoteCommandData;
|
||||
openInWindow: NoteCommandData;
|
||||
openNoteInNewTab: CommandData;
|
||||
openNoteInNewSplit: CommandData;
|
||||
openNoteInNewWindow: CommandData;
|
||||
openAboutDialog: CommandData;
|
||||
hideFloatingButtons: {};
|
||||
hideLeftPane: CommandData;
|
||||
showLeftPane: CommandData;
|
||||
hoistNote: CommandData & { noteId: string };
|
||||
leaveProtectedSession: CommandData;
|
||||
enterProtectedSession: CommandData;
|
||||
noteContextReorder: CommandData & {
|
||||
ntxIdsInOrder: string[];
|
||||
oldMainNtxId?: string | null;
|
||||
newMainNtxId?: string | null;
|
||||
};
|
||||
openInTab: ContextMenuCommandData;
|
||||
openNoteInSplit: ContextMenuCommandData;
|
||||
toggleNoteHoisting: ContextMenuCommandData;
|
||||
insertNoteAfter: ContextMenuCommandData;
|
||||
insertChildNote: ContextMenuCommandData;
|
||||
delete: ContextMenuCommandData;
|
||||
editNoteTitle: {};
|
||||
protectSubtree: ContextMenuCommandData;
|
||||
unprotectSubtree: ContextMenuCommandData;
|
||||
openBulkActionsDialog:
|
||||
| ContextMenuCommandData
|
||||
| {
|
||||
selectedOrActiveNoteIds?: string[];
|
||||
};
|
||||
editBranchPrefix: ContextMenuCommandData;
|
||||
convertNoteToAttachment: ContextMenuCommandData;
|
||||
duplicateSubtree: ContextMenuCommandData;
|
||||
expandSubtree: ContextMenuCommandData;
|
||||
collapseSubtree: ContextMenuCommandData;
|
||||
sortChildNotes: ContextMenuCommandData;
|
||||
copyNotePathToClipboard: ContextMenuCommandData;
|
||||
recentChangesInSubtree: ContextMenuCommandData;
|
||||
cutNotesToClipboard: ContextMenuCommandData;
|
||||
copyNotesToClipboard: ContextMenuCommandData;
|
||||
pasteNotesFromClipboard: ContextMenuCommandData;
|
||||
pasteNotesAfterFromClipboard: ContextMenuCommandData;
|
||||
moveNotesTo: ContextMenuCommandData;
|
||||
cloneNotesTo: ContextMenuCommandData;
|
||||
deleteNotes: ContextMenuCommandData;
|
||||
importIntoNote: ContextMenuCommandData;
|
||||
exportNote: ContextMenuCommandData;
|
||||
searchInSubtree: ContextMenuCommandData;
|
||||
moveNoteUp: ContextMenuCommandData;
|
||||
moveNoteDown: ContextMenuCommandData;
|
||||
moveNoteUpInHierarchy: ContextMenuCommandData;
|
||||
moveNoteDownInHierarchy: ContextMenuCommandData;
|
||||
selectAllNotesInParent: ContextMenuCommandData;
|
||||
|
||||
createNoteIntoInbox: CommandData;
|
||||
|
||||
addNoteLauncher: ContextMenuCommandData;
|
||||
addScriptLauncher: ContextMenuCommandData;
|
||||
addWidgetLauncher: ContextMenuCommandData;
|
||||
addSpacerLauncher: ContextMenuCommandData;
|
||||
moveLauncherToVisible: ContextMenuCommandData;
|
||||
moveLauncherToAvailable: ContextMenuCommandData;
|
||||
resetLauncher: ContextMenuCommandData;
|
||||
|
||||
executeInActiveNoteDetailWidget: CommandData & {
|
||||
callback: (value: NoteDetailWidget | PromiseLike<NoteDetailWidget>) => void;
|
||||
};
|
||||
executeWithTextEditor: CommandData &
|
||||
ExecuteCommandData<TextEditor> & {
|
||||
callback?: GetTextEditorCallback;
|
||||
};
|
||||
executeWithCodeEditor: CommandData & ExecuteCommandData<CodeMirrorInstance>;
|
||||
/**
|
||||
* Called upon when attempting to retrieve the content element of a {@link NoteContext}.
|
||||
* Generally should not be invoked manually, as it is used by {@link NoteContext.getContentElement}.
|
||||
*/
|
||||
executeWithContentElement: CommandData & ExecuteCommandData<JQuery<HTMLElement>>;
|
||||
executeWithTypeWidget: CommandData & ExecuteCommandData<TypeWidget | null>;
|
||||
addTextToActiveEditor: CommandData & {
|
||||
text: string;
|
||||
};
|
||||
/** Works only in the electron context menu. */
|
||||
replaceMisspelling: CommandData;
|
||||
|
||||
importMarkdownInline: CommandData;
|
||||
showPasswordNotSet: CommandData;
|
||||
showProtectedSessionPasswordDialog: CommandData;
|
||||
showUploadAttachmentsDialog: CommandData & { noteId: string };
|
||||
showIncludeNoteDialog: CommandData & { textTypeWidget: EditableTextTypeWidget };
|
||||
showAddLinkDialog: CommandData & { textTypeWidget: EditableTextTypeWidget, text: string };
|
||||
closeProtectedSessionPasswordDialog: CommandData;
|
||||
copyImageReferenceToClipboard: CommandData;
|
||||
copyImageToClipboard: CommandData;
|
||||
updateAttributesList: {
|
||||
attributes: Attribute[];
|
||||
};
|
||||
|
||||
addNewLabel: CommandData;
|
||||
addNewRelation: CommandData;
|
||||
addNewLabelDefinition: CommandData;
|
||||
addNewRelationDefinition: CommandData;
|
||||
|
||||
cloneNoteIdsTo: CommandData & {
|
||||
noteIds: string[];
|
||||
};
|
||||
moveBranchIdsTo: CommandData & {
|
||||
branchIds: string[];
|
||||
};
|
||||
/** Sets the active {@link Screen} (e.g. to toggle the tree sidebar). It triggers the {@link EventMappings.activeScreenChanged} event, but only if the provided <em>screen</em> is different than the current one. */
|
||||
setActiveScreen: CommandData & {
|
||||
screen: Screen;
|
||||
};
|
||||
closeTab: CommandData;
|
||||
closeToc: CommandData;
|
||||
closeOtherTabs: CommandData;
|
||||
closeRightTabs: CommandData;
|
||||
closeAllTabs: CommandData;
|
||||
reopenLastTab: CommandData;
|
||||
moveTabToNewWindow: CommandData;
|
||||
copyTabToNewWindow: CommandData;
|
||||
closeActiveTab: CommandData & {
|
||||
$el: JQuery<HTMLElement>;
|
||||
};
|
||||
setZoomFactorAndSave: {
|
||||
zoomFactor: string;
|
||||
};
|
||||
|
||||
reEvaluateRightPaneVisibility: CommandData;
|
||||
runActiveNote: CommandData;
|
||||
scrollContainerToCommand: CommandData & {
|
||||
position: number;
|
||||
};
|
||||
scrollToEnd: CommandData;
|
||||
closeThisNoteSplit: CommandData;
|
||||
moveThisNoteSplit: CommandData & { isMovingLeft: boolean };
|
||||
jumpToNote: CommandData;
|
||||
|
||||
// Geomap
|
||||
deleteFromMap: { noteId: string };
|
||||
openGeoLocation: { noteId: string; event: JQuery.MouseDownEvent };
|
||||
|
||||
toggleZenMode: CommandData;
|
||||
|
||||
updateAttributeList: CommandData & { attributes: Attribute[] };
|
||||
saveAttributes: CommandData;
|
||||
reloadAttributes: CommandData;
|
||||
refreshNoteList: CommandData & { noteId: string };
|
||||
|
||||
refreshResults: {};
|
||||
refreshSearchDefinition: {};
|
||||
|
||||
geoMapCreateChildNote: CommandData;
|
||||
|
||||
buildTouchBar: CommandData & {
|
||||
TouchBar: typeof TouchBar;
|
||||
buildIcon(name: string): NativeImage;
|
||||
};
|
||||
refreshTouchBar: CommandData;
|
||||
};
|
||||
|
||||
type EventMappings = {
|
||||
initialRenderComplete: {};
|
||||
frocaReloaded: {};
|
||||
protectedSessionStarted: {};
|
||||
notesReloaded: {
|
||||
noteIds: string[];
|
||||
};
|
||||
refreshIncludedNote: {
|
||||
noteId: string;
|
||||
};
|
||||
apiLogMessages: {
|
||||
noteId: string;
|
||||
messages: string[];
|
||||
};
|
||||
entitiesReloaded: {
|
||||
loadResults: LoadResults;
|
||||
};
|
||||
addNewLabel: CommandData;
|
||||
addNewRelation: CommandData;
|
||||
sqlQueryResults: CommandData & {
|
||||
results: SqlExecuteResults;
|
||||
};
|
||||
readOnlyTemporarilyDisabled: {
|
||||
noteContext: NoteContext;
|
||||
};
|
||||
/** Triggered when the {@link CommandMappings.setActiveScreen} command is invoked. */
|
||||
activeScreenChanged: {
|
||||
activeScreen: Screen;
|
||||
};
|
||||
activeContextChanged: {
|
||||
noteContext: NoteContext;
|
||||
};
|
||||
beforeNoteSwitch: {
|
||||
noteContext: NoteContext;
|
||||
};
|
||||
beforeNoteContextRemove: {
|
||||
ntxIds: string[];
|
||||
};
|
||||
noteSwitched: NoteSwitchedContext;
|
||||
noteSwitchedAndActivated: NoteSwitchedContext;
|
||||
setNoteContext: {
|
||||
noteContext: NoteContext;
|
||||
};
|
||||
reEvaluateHighlightsListWidgetVisibility: {
|
||||
noteId: string | undefined;
|
||||
};
|
||||
reEvaluateTocWidgetVisibility: {
|
||||
noteId: string | undefined;
|
||||
};
|
||||
showHighlightsListWidget: {
|
||||
noteId: string;
|
||||
};
|
||||
showTocWidget: {
|
||||
noteId: string;
|
||||
};
|
||||
showSearchError: {
|
||||
error: string;
|
||||
};
|
||||
searchRefreshed: { ntxId?: string | null };
|
||||
hoistedNoteChanged: {
|
||||
noteId: string;
|
||||
ntxId: string | null;
|
||||
};
|
||||
contextsReopened: {
|
||||
ntxId?: string;
|
||||
mainNtxId: string | null;
|
||||
tabPosition: number;
|
||||
afterNtxId?: string;
|
||||
};
|
||||
noteDetailRefreshed: {
|
||||
ntxId?: string | null;
|
||||
};
|
||||
noteContextReorder: {
|
||||
oldMainNtxId: string;
|
||||
newMainNtxId: string;
|
||||
ntxIdsInOrder: string[];
|
||||
};
|
||||
newNoteContextCreated: {
|
||||
noteContext: NoteContext;
|
||||
};
|
||||
noteContextRemoved: {
|
||||
ntxIds: string[];
|
||||
};
|
||||
exportSvg: { ntxId: string | null | undefined; };
|
||||
exportPng: { ntxId: string | null | undefined; };
|
||||
geoMapCreateChildNote: {
|
||||
ntxId: string | null | undefined; // TODO: deduplicate ntxId
|
||||
};
|
||||
tabReorder: {
|
||||
ntxIdsInOrder: string[];
|
||||
};
|
||||
refreshNoteList: {
|
||||
noteId: string;
|
||||
};
|
||||
noteTypeMimeChanged: { noteId: string };
|
||||
zenModeChanged: { isEnabled: boolean };
|
||||
relationMapCreateChildNote: { ntxId: string | null | undefined };
|
||||
relationMapResetPanZoom: { ntxId: string | null | undefined };
|
||||
relationMapResetZoomIn: { ntxId: string | null | undefined };
|
||||
relationMapResetZoomOut: { ntxId: string | null | undefined };
|
||||
activeNoteChanged: {};
|
||||
showAddLinkDialog: {
|
||||
textTypeWidget: EditableTextTypeWidget;
|
||||
text: string;
|
||||
};
|
||||
showIncludeDialog: {
|
||||
textTypeWidget: EditableTextTypeWidget;
|
||||
};
|
||||
openBulkActionsDialog: {
|
||||
selectedOrActiveNoteIds: string[];
|
||||
};
|
||||
cloneNoteIdsTo: {
|
||||
noteIds: string[];
|
||||
};
|
||||
refreshData: { ntxId: string | null | undefined };
|
||||
};
|
||||
|
||||
export type EventListener<T extends EventNames> = {
|
||||
[key in T as `${key}Event`]: (data: EventData<T>) => void;
|
||||
};
|
||||
|
||||
export type CommandListener<T extends CommandNames> = {
|
||||
[key in T as `${key}Command`]: (data: CommandListenerData<T>) => void;
|
||||
};
|
||||
|
||||
export type CommandListenerData<T extends CommandNames> = CommandMappings[T];
|
||||
|
||||
type CommandAndEventMappings = CommandMappings & EventMappings;
|
||||
type EventOnlyNames = keyof EventMappings;
|
||||
export type EventNames = CommandNames | EventOnlyNames;
|
||||
export type EventData<T extends EventNames> = CommandAndEventMappings[T];
|
||||
|
||||
/**
|
||||
* This type is a discriminated union which contains all the possible commands that can be triggered via {@link AppContext.triggerCommand}.
|
||||
*/
|
||||
export type CommandNames = keyof CommandMappings;
|
||||
|
||||
type FilterByValueType<T, ValueType> = { [K in keyof T]: T[K] extends ValueType ? K : never }[keyof T];
|
||||
|
||||
/**
|
||||
* Generic which filters {@link CommandNames} to provide only those commands that take in as data the desired implementation of {@link CommandData}. Mostly useful for contextual menu, to enforce consistency in the commands.
|
||||
*/
|
||||
export type FilteredCommandNames<T extends CommandData> = keyof Pick<CommandMappings, FilterByValueType<CommandMappings, T>>;
|
||||
|
||||
export class AppContext extends Component {
|
||||
isMainWindow: boolean;
|
||||
components: Component[];
|
||||
beforeUnloadListeners: WeakRef<BeforeUploadListener>[];
|
||||
tabManager!: TabManager;
|
||||
layout?: Layout;
|
||||
noteTreeWidget?: NoteTreeWidget;
|
||||
|
||||
lastSearchString?: string;
|
||||
|
||||
constructor(isMainWindow: boolean) {
|
||||
super();
|
||||
|
||||
this.isMainWindow = isMainWindow;
|
||||
// non-widget/layout components needed for the application
|
||||
this.components = [];
|
||||
this.beforeUnloadListeners = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be called as soon as possible, before the creation of any components since this method is in charge of initializing the locale. Any attempts to read translation before this method is called will result in `undefined`.
|
||||
*/
|
||||
async earlyInit() {
|
||||
await options.initializedPromise;
|
||||
await initLocale();
|
||||
}
|
||||
|
||||
setLayout(layout: Layout) {
|
||||
this.layout = layout;
|
||||
}
|
||||
|
||||
async start() {
|
||||
this.initComponents();
|
||||
this.renderWidgets();
|
||||
|
||||
await froca.initializedPromise;
|
||||
|
||||
this.tabManager.loadTabs();
|
||||
|
||||
setTimeout(() => bundleService.executeStartupBundles(), 2000);
|
||||
}
|
||||
|
||||
initComponents() {
|
||||
this.tabManager = new TabManager();
|
||||
|
||||
this.components = [this.tabManager, new RootCommandExecutor(), new Entrypoints(), new MainTreeExecutors(), new ShortcutComponent()];
|
||||
|
||||
if (utils.isMobile()) {
|
||||
this.components.push(new MobileScreenSwitcherExecutor());
|
||||
}
|
||||
|
||||
for (const component of this.components) {
|
||||
this.child(component);
|
||||
}
|
||||
|
||||
if (utils.isElectron()) {
|
||||
this.child(zoomComponent);
|
||||
}
|
||||
|
||||
if (hasTouchBar) {
|
||||
this.child(new TouchBarComponent());
|
||||
}
|
||||
}
|
||||
|
||||
renderWidgets() {
|
||||
if (!this.layout) {
|
||||
throw new Error("Missing layout.");
|
||||
}
|
||||
|
||||
const rootWidget = this.layout.getRootWidget(this);
|
||||
const $renderedWidget = rootWidget.render();
|
||||
|
||||
keyboardActionsService.updateDisplayedShortcuts($renderedWidget);
|
||||
|
||||
$("body").append($renderedWidget);
|
||||
|
||||
$renderedWidget.on("click", "[data-trigger-command]", function () {
|
||||
if ($(this).hasClass("disabled")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const commandName = $(this).attr("data-trigger-command");
|
||||
const $component = $(this).closest(".component");
|
||||
const component = $component.prop("component");
|
||||
|
||||
component.triggerCommand(commandName, { $el: $(this) });
|
||||
});
|
||||
|
||||
this.child(rootWidget);
|
||||
|
||||
this.triggerEvent("initialRenderComplete", {});
|
||||
}
|
||||
|
||||
triggerEvent<K extends EventNames>(name: K, data: EventData<K>) {
|
||||
return this.handleEvent(name, data);
|
||||
}
|
||||
|
||||
triggerCommand<K extends CommandNames>(name: K, _data?: CommandMappings[K]) {
|
||||
const data = _data || {};
|
||||
for (const executor of this.components) {
|
||||
const fun = (executor as any)[`${name}Command`];
|
||||
|
||||
if (fun) {
|
||||
return executor.callMethod(fun, data);
|
||||
}
|
||||
}
|
||||
|
||||
// this might hint at error, but sometimes this is used by components which are at different places
|
||||
// in the component tree to communicate with each other
|
||||
console.debug(`Unhandled command ${name}, converting to event.`);
|
||||
|
||||
return this.triggerEvent(name, data as CommandAndEventMappings[K]);
|
||||
}
|
||||
|
||||
getComponentByEl(el: HTMLElement) {
|
||||
return $(el).closest(".component").prop("component");
|
||||
}
|
||||
|
||||
addBeforeUnloadListener(obj: BeforeUploadListener) {
|
||||
if (typeof WeakRef !== "function") {
|
||||
// older browsers don't support WeakRef
|
||||
return;
|
||||
}
|
||||
|
||||
this.beforeUnloadListeners.push(new WeakRef<BeforeUploadListener>(obj));
|
||||
}
|
||||
}
|
||||
|
||||
const appContext = new AppContext(window.glob.isMainWindow);
|
||||
|
||||
// we should save all outstanding changes before the page/app is closed
|
||||
$(window).on("beforeunload", () => {
|
||||
let allSaved = true;
|
||||
|
||||
appContext.beforeUnloadListeners = appContext.beforeUnloadListeners.filter((wr) => !!wr.deref());
|
||||
|
||||
for (const weakRef of appContext.beforeUnloadListeners) {
|
||||
const component = weakRef.deref();
|
||||
|
||||
if (!component) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!component.beforeUnloadEvent()) {
|
||||
console.log(`Component ${component.componentId} is not finished saving its state.`);
|
||||
|
||||
toast.showMessage(t("app_context.please_wait_for_save"), 10000);
|
||||
|
||||
allSaved = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!allSaved) {
|
||||
return "some string";
|
||||
}
|
||||
});
|
||||
|
||||
$(window).on("hashchange", function () {
|
||||
const { notePath, ntxId, viewScope, searchString } = linkService.parseNavigationStateFromUrl(window.location.href);
|
||||
|
||||
if (notePath || ntxId) {
|
||||
appContext.tabManager.switchToNoteContext(ntxId, notePath, viewScope);
|
||||
} else if (searchString) {
|
||||
appContext.triggerCommand("searchNotes", { searchString });
|
||||
}
|
||||
});
|
||||
|
||||
export default appContext;
|
||||
129
apps/client/src/components/component.ts
Normal file
129
apps/client/src/components/component.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import utils from "../services/utils.js";
|
||||
import type { CommandMappings, CommandNames, EventData, EventNames } from "./app_context.js";
|
||||
|
||||
/**
|
||||
* Abstract class for all components in the Trilium's frontend.
|
||||
*
|
||||
* Contains also event implementation with following properties:
|
||||
* - event / command distribution is synchronous which among others mean that events are well-ordered - event
|
||||
* which was sent out first will also be processed first by the component
|
||||
* - execution of the event / command is asynchronous - each component executes the event on its own without regard for
|
||||
* other components.
|
||||
* - although the execution is async, we are collecting all the promises, and therefore it is possible to wait until the
|
||||
* event / command is executed in all components - by simply awaiting the `triggerEvent()`.
|
||||
*/
|
||||
export class TypedComponent<ChildT extends TypedComponent<ChildT>> {
|
||||
$widget!: JQuery<HTMLElement>;
|
||||
componentId: string;
|
||||
children: ChildT[];
|
||||
initialized: Promise<void> | null;
|
||||
parent?: TypedComponent<any>;
|
||||
_position!: number;
|
||||
|
||||
constructor() {
|
||||
this.componentId = `${this.sanitizedClassName}-${utils.randomString(8)}`;
|
||||
this.children = [];
|
||||
this.initialized = null;
|
||||
}
|
||||
|
||||
get sanitizedClassName() {
|
||||
// webpack mangles names and sometimes uses unsafe characters
|
||||
return this.constructor.name.replace(/[^A-Z0-9]/gi, "_");
|
||||
}
|
||||
|
||||
get position() {
|
||||
return this._position;
|
||||
}
|
||||
|
||||
set position(newPosition: number) {
|
||||
this._position = newPosition;
|
||||
}
|
||||
|
||||
setParent(parent: TypedComponent<any>) {
|
||||
this.parent = parent;
|
||||
return this;
|
||||
}
|
||||
|
||||
child(...components: ChildT[]) {
|
||||
for (const component of components) {
|
||||
component.setParent(this);
|
||||
|
||||
this.children.push(component);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
handleEvent<T extends EventNames>(name: T, data: EventData<T>): Promise<unknown[] | unknown> | null | undefined {
|
||||
try {
|
||||
const callMethodPromise = this.initialized ? this.initialized.then(() => this.callMethod((this as any)[`${name}Event`], data)) : this.callMethod((this as any)[`${name}Event`], data);
|
||||
|
||||
const childrenPromise = this.handleEventInChildren(name, data);
|
||||
|
||||
// don't create promises if not needed (optimization)
|
||||
return callMethodPromise && childrenPromise ? Promise.all([callMethodPromise, childrenPromise]) : callMethodPromise || childrenPromise;
|
||||
} catch (e: any) {
|
||||
console.error(`Handling of event '${name}' failed in ${this.constructor.name} with error ${e.message} ${e.stack}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
triggerEvent<T extends EventNames>(name: T, data: EventData<T>): Promise<unknown> | undefined | null {
|
||||
return this.parent?.triggerEvent(name, data);
|
||||
}
|
||||
|
||||
handleEventInChildren<T extends EventNames>(name: T, data: EventData<T>): Promise<unknown[] | unknown> | null {
|
||||
const promises: Promise<unknown>[] = [];
|
||||
|
||||
for (const child of this.children) {
|
||||
const ret = child.handleEvent(name, data) as Promise<void>;
|
||||
|
||||
if (ret) {
|
||||
promises.push(ret);
|
||||
}
|
||||
}
|
||||
|
||||
// don't create promises if not needed (optimization)
|
||||
return promises.length > 0 ? Promise.all(promises) : null;
|
||||
}
|
||||
|
||||
triggerCommand<K extends CommandNames>(name: K, data?: CommandMappings[K]): Promise<unknown> | undefined | null {
|
||||
const fun = (this as any)[`${name}Command`];
|
||||
|
||||
if (fun) {
|
||||
return this.callMethod(fun, data);
|
||||
} else {
|
||||
if (!this.parent) {
|
||||
throw new Error(`Component "${this.componentId}" does not have a parent attached to propagate a command.`);
|
||||
}
|
||||
|
||||
return this.parent.triggerCommand(name, data);
|
||||
}
|
||||
}
|
||||
|
||||
callMethod(fun: (arg: unknown) => Promise<unknown>, data: unknown) {
|
||||
if (typeof fun !== "function") {
|
||||
return;
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
const promise = fun.call(this, data);
|
||||
|
||||
const took = Date.now() - startTime;
|
||||
|
||||
if (glob.isDev && took > 20) {
|
||||
// measuring only sync handlers
|
||||
console.log(`Call to ${fun.name} in ${this.componentId} took ${took}ms`);
|
||||
}
|
||||
|
||||
if (glob.isDev && promise) {
|
||||
return utils.timeLimit(promise, 20000, `Time limit failed on ${this.constructor.name} with ${fun.name}`);
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
}
|
||||
|
||||
export default class Component extends TypedComponent<Component> {}
|
||||
233
apps/client/src/components/entrypoints.ts
Normal file
233
apps/client/src/components/entrypoints.ts
Normal file
@@ -0,0 +1,233 @@
|
||||
import utils from "../services/utils.js";
|
||||
import dateNoteService from "../services/date_notes.js";
|
||||
import protectedSessionHolder from "../services/protected_session_holder.js";
|
||||
import server from "../services/server.js";
|
||||
import appContext, { type NoteCommandData } from "./app_context.js";
|
||||
import Component from "./component.js";
|
||||
import toastService from "../services/toast.js";
|
||||
import ws from "../services/ws.js";
|
||||
import bundleService from "../services/bundle.js";
|
||||
import froca from "../services/froca.js";
|
||||
import linkService from "../services/link.js";
|
||||
import { t } from "../services/i18n.js";
|
||||
import type FNote from "../entities/fnote.js";
|
||||
|
||||
// TODO: Move somewhere else nicer.
|
||||
export type SqlExecuteResults = string[][][];
|
||||
|
||||
// TODO: Deduplicate with server.
|
||||
interface SqlExecuteResponse {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
results: SqlExecuteResults;
|
||||
}
|
||||
|
||||
// TODO: Deduplicate with server.
|
||||
interface CreateChildrenResponse {
|
||||
note: FNote;
|
||||
}
|
||||
|
||||
export default class Entrypoints extends Component {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
if (jQuery.hotkeys) {
|
||||
// hot keys are active also inside inputs and content editables
|
||||
jQuery.hotkeys.options.filterInputAcceptingElements = false;
|
||||
jQuery.hotkeys.options.filterContentEditable = false;
|
||||
jQuery.hotkeys.options.filterTextInputs = false;
|
||||
}
|
||||
}
|
||||
|
||||
openDevToolsCommand() {
|
||||
if (utils.isElectron()) {
|
||||
utils.dynamicRequire("@electron/remote").getCurrentWindow().toggleDevTools();
|
||||
}
|
||||
}
|
||||
|
||||
async createNoteIntoInboxCommand() {
|
||||
const inboxNote = await dateNoteService.getInboxNote();
|
||||
if (!inboxNote) {
|
||||
console.warn("Missing inbox note.");
|
||||
return;
|
||||
}
|
||||
|
||||
const { note } = await server.post<CreateChildrenResponse>(`notes/${inboxNote.noteId}/children?target=into`, {
|
||||
content: "",
|
||||
type: "text",
|
||||
isProtected: inboxNote.isProtected && protectedSessionHolder.isProtectedSessionAvailable()
|
||||
});
|
||||
|
||||
await ws.waitForMaxKnownEntityChangeId();
|
||||
|
||||
await appContext.tabManager.openTabWithNoteWithHoisting(note.noteId, { activate: true });
|
||||
|
||||
appContext.triggerEvent("focusAndSelectTitle", { isNewNote: true });
|
||||
}
|
||||
|
||||
async toggleNoteHoistingCommand({ noteId = appContext.tabManager.getActiveContextNoteId() }) {
|
||||
const activeNoteContext = appContext.tabManager.getActiveContext();
|
||||
|
||||
if (!activeNoteContext || !noteId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const noteToHoist = await froca.getNote(noteId);
|
||||
|
||||
if (noteToHoist?.noteId === activeNoteContext.hoistedNoteId) {
|
||||
await activeNoteContext.unhoist();
|
||||
} else if (noteToHoist?.type !== "search") {
|
||||
await activeNoteContext.setHoistedNoteId(noteId);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
async unhoistCommand() {
|
||||
const activeNoteContext = appContext.tabManager.getActiveContext();
|
||||
|
||||
if (activeNoteContext) {
|
||||
activeNoteContext.unhoist();
|
||||
}
|
||||
}
|
||||
|
||||
copyWithoutFormattingCommand() {
|
||||
utils.copySelectionToClipboard();
|
||||
}
|
||||
|
||||
toggleFullscreenCommand() {
|
||||
if (utils.isElectron()) {
|
||||
const win = utils.dynamicRequire("@electron/remote").getCurrentWindow();
|
||||
|
||||
if (win.isFullScreenable()) {
|
||||
win.setFullScreen(!win.isFullScreen());
|
||||
}
|
||||
} // outside of electron this is handled by the browser
|
||||
}
|
||||
|
||||
reloadFrontendAppCommand() {
|
||||
utils.reloadFrontendApp();
|
||||
}
|
||||
|
||||
async logoutCommand() {
|
||||
await server.post("../logout");
|
||||
window.location.replace(`/login`);
|
||||
}
|
||||
|
||||
backInNoteHistoryCommand() {
|
||||
if (utils.isElectron()) {
|
||||
// standard JS version does not work completely correctly in electron
|
||||
const webContents = utils.dynamicRequire("@electron/remote").getCurrentWebContents();
|
||||
const activeIndex = parseInt(webContents.navigationHistory.getActiveIndex());
|
||||
|
||||
webContents.goToIndex(activeIndex - 1);
|
||||
} else {
|
||||
window.history.back();
|
||||
}
|
||||
}
|
||||
|
||||
forwardInNoteHistoryCommand() {
|
||||
if (utils.isElectron()) {
|
||||
// standard JS version does not work completely correctly in electron
|
||||
const webContents = utils.dynamicRequire("@electron/remote").getCurrentWebContents();
|
||||
const activeIndex = parseInt(webContents.navigationHistory.getActiveIndex());
|
||||
|
||||
webContents.goToIndex(activeIndex + 1);
|
||||
} else {
|
||||
window.history.forward();
|
||||
}
|
||||
}
|
||||
|
||||
async switchToDesktopVersionCommand() {
|
||||
utils.setCookie("trilium-device", "desktop");
|
||||
|
||||
utils.reloadFrontendApp("Switching to desktop version");
|
||||
}
|
||||
|
||||
async switchToMobileVersionCommand() {
|
||||
utils.setCookie("trilium-device", "mobile");
|
||||
|
||||
utils.reloadFrontendApp("Switching to mobile version");
|
||||
}
|
||||
|
||||
async openInWindowCommand({ notePath, hoistedNoteId, viewScope }: NoteCommandData) {
|
||||
const extraWindowHash = linkService.calculateHash({ notePath, hoistedNoteId, viewScope });
|
||||
|
||||
if (utils.isElectron()) {
|
||||
const { ipcRenderer } = utils.dynamicRequire("electron");
|
||||
|
||||
ipcRenderer.send("create-extra-window", { extraWindowHash });
|
||||
} else {
|
||||
const url = `${window.location.protocol}//${window.location.host}${window.location.pathname}?extraWindow=1${extraWindowHash}`;
|
||||
|
||||
window.open(url, "", "width=1000,height=800");
|
||||
}
|
||||
}
|
||||
|
||||
async openNewWindowCommand() {
|
||||
this.openInWindowCommand({ notePath: "", hoistedNoteId: "root" });
|
||||
}
|
||||
|
||||
async runActiveNoteCommand() {
|
||||
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") {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: use note.executeScript()
|
||||
if (note.mime.endsWith("env=frontend")) {
|
||||
await bundleService.getAndExecuteBundle(note.noteId);
|
||||
} else if (note.mime.endsWith("env=backend")) {
|
||||
await server.post(`script/run/${note.noteId}`);
|
||||
} else if (note.mime === "text/x-sqlite;schema=trilium") {
|
||||
const resp = await server.post<SqlExecuteResponse>(`sql/execute/${note.noteId}`);
|
||||
|
||||
if (!resp.success) {
|
||||
toastService.showError(t("entrypoints.sql-error", { message: resp.error }));
|
||||
}
|
||||
|
||||
await appContext.triggerEvent("sqlQueryResults", { ntxId: ntxId, results: resp.results });
|
||||
}
|
||||
|
||||
toastService.showMessage(t("entrypoints.note-executed"));
|
||||
}
|
||||
|
||||
hideAllPopups() {
|
||||
if (utils.isDesktop()) {
|
||||
$(".aa-input").autocomplete("close");
|
||||
}
|
||||
}
|
||||
|
||||
noteSwitchedEvent() {
|
||||
this.hideAllPopups();
|
||||
}
|
||||
|
||||
activeContextChangedEvent() {
|
||||
this.hideAllPopups();
|
||||
}
|
||||
|
||||
async forceSaveRevisionCommand() {
|
||||
const noteId = appContext.tabManager.getActiveContextNoteId();
|
||||
|
||||
await server.post(`notes/${noteId}/revision`);
|
||||
|
||||
toastService.showMessage(t("entrypoints.note-revision-created"));
|
||||
}
|
||||
}
|
||||
8
apps/client/src/components/events.ts
Normal file
8
apps/client/src/components/events.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import type { MenuCommandItem } from "../menus/context_menu.js";
|
||||
import type { CommandNames } from "./app_context.js";
|
||||
|
||||
type ListenerReturnType = void | Promise<void>;
|
||||
|
||||
export interface SelectMenuItemEventListener<T extends CommandNames> {
|
||||
selectMenuItemHandler(item: MenuCommandItem<T>): ListenerReturnType;
|
||||
}
|
||||
82
apps/client/src/components/main_tree_executors.ts
Normal file
82
apps/client/src/components/main_tree_executors.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import appContext, { type EventData } from "./app_context.js";
|
||||
import noteCreateService from "../services/note_create.js";
|
||||
import treeService from "../services/tree.js";
|
||||
import hoistedNoteService from "../services/hoisted_note.js";
|
||||
import Component from "./component.js";
|
||||
|
||||
/**
|
||||
* This class contains command executors which logically belong to the NoteTree widget, but for better user experience,
|
||||
* the keyboard shortcuts must be active on the whole screen and not just on the widget itself, so the executors
|
||||
* must be at the root of the component tree.
|
||||
*/
|
||||
export default class MainTreeExecutors extends Component {
|
||||
/**
|
||||
* On mobile it will be `undefined`.
|
||||
*/
|
||||
get tree() {
|
||||
return appContext.noteTreeWidget;
|
||||
}
|
||||
|
||||
async cloneNotesToCommand({ selectedOrActiveNoteIds }: EventData<"cloneNotesTo">) {
|
||||
if (!selectedOrActiveNoteIds && this.tree) {
|
||||
selectedOrActiveNoteIds = this.tree.getSelectedOrActiveNodes().map((node) => node.data.noteId);
|
||||
}
|
||||
|
||||
if (!selectedOrActiveNoteIds) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.triggerCommand("cloneNoteIdsTo", { noteIds: selectedOrActiveNoteIds });
|
||||
}
|
||||
|
||||
async moveNotesToCommand({ selectedOrActiveBranchIds }: EventData<"moveNotesTo">) {
|
||||
if (!selectedOrActiveBranchIds && this.tree) {
|
||||
selectedOrActiveBranchIds = this.tree.getSelectedOrActiveNodes().map((node) => node.data.branchId);
|
||||
}
|
||||
|
||||
if (!selectedOrActiveBranchIds) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.triggerCommand("moveBranchIdsTo", { branchIds: selectedOrActiveBranchIds });
|
||||
}
|
||||
|
||||
async createNoteIntoCommand() {
|
||||
const activeNoteContext = appContext.tabManager.getActiveContext();
|
||||
|
||||
if (!activeNoteContext || !activeNoteContext.notePath || !activeNoteContext.note) {
|
||||
return;
|
||||
}
|
||||
|
||||
await noteCreateService.createNote(activeNoteContext.notePath, {
|
||||
isProtected: activeNoteContext.note.isProtected,
|
||||
saveSelection: false
|
||||
});
|
||||
}
|
||||
|
||||
async createNoteAfterCommand() {
|
||||
if (!this.tree) {
|
||||
return;
|
||||
}
|
||||
|
||||
const node = this.tree.getActiveNode();
|
||||
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parentNotePath = treeService.getNotePath(node.getParent());
|
||||
const isProtected = treeService.getParentProtectedStatus(node);
|
||||
|
||||
if (node.data.noteId === "root" || node.data.noteId === hoistedNoteService.getHoistedNoteId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
await noteCreateService.createNote(parentNotePath, {
|
||||
target: "after",
|
||||
targetBranchId: node.data.branchId,
|
||||
isProtected: isProtected,
|
||||
saveSelection: false
|
||||
});
|
||||
}
|
||||
}
|
||||
15
apps/client/src/components/mobile_screen_switcher.ts
Normal file
15
apps/client/src/components/mobile_screen_switcher.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import Component from "./component.js";
|
||||
import type { CommandListener, CommandListenerData } from "./app_context.js";
|
||||
|
||||
export type Screen = "detail" | "tree";
|
||||
|
||||
export default class MobileScreenSwitcherExecutor extends Component implements CommandListener<"setActiveScreen"> {
|
||||
private activeScreen?: Screen;
|
||||
|
||||
setActiveScreenCommand({ screen }: CommandListenerData<"setActiveScreen">) {
|
||||
if (screen !== this.activeScreen) {
|
||||
this.activeScreen = screen;
|
||||
this.triggerEvent("activeScreenChanged", { activeScreen: screen });
|
||||
}
|
||||
}
|
||||
}
|
||||
388
apps/client/src/components/note_context.ts
Normal file
388
apps/client/src/components/note_context.ts
Normal file
@@ -0,0 +1,388 @@
|
||||
import protectedSessionHolder from "../services/protected_session_holder.js";
|
||||
import server from "../services/server.js";
|
||||
import utils from "../services/utils.js";
|
||||
import appContext, { type EventData, type EventListener } from "./app_context.js";
|
||||
import treeService from "../services/tree.js";
|
||||
import Component from "./component.js";
|
||||
import froca from "../services/froca.js";
|
||||
import hoistedNoteService from "../services/hoisted_note.js";
|
||||
import options from "../services/options.js";
|
||||
import type { ViewScope } from "../services/link.js";
|
||||
import type FNote from "../entities/fnote.js";
|
||||
import type TypeWidget from "../widgets/type_widgets/type_widget.js";
|
||||
|
||||
export interface SetNoteOpts {
|
||||
triggerSwitchEvent?: unknown;
|
||||
viewScope?: ViewScope;
|
||||
}
|
||||
|
||||
export type GetTextEditorCallback = (editor: TextEditor) => void;
|
||||
|
||||
class NoteContext extends Component implements EventListener<"entitiesReloaded"> {
|
||||
ntxId: string | null;
|
||||
hoistedNoteId: string;
|
||||
mainNtxId: string | null;
|
||||
|
||||
notePath?: string | null;
|
||||
noteId?: string | null;
|
||||
parentNoteId?: string | null;
|
||||
viewScope?: ViewScope;
|
||||
|
||||
constructor(ntxId: string | null = null, hoistedNoteId: string = "root", mainNtxId: string | null = null) {
|
||||
super();
|
||||
|
||||
this.ntxId = ntxId || NoteContext.generateNtxId();
|
||||
this.hoistedNoteId = hoistedNoteId;
|
||||
this.mainNtxId = mainNtxId;
|
||||
|
||||
this.resetViewScope();
|
||||
}
|
||||
|
||||
static generateNtxId() {
|
||||
return utils.randomString(6);
|
||||
}
|
||||
|
||||
setEmpty() {
|
||||
this.notePath = null;
|
||||
this.noteId = null;
|
||||
this.parentNoteId = null;
|
||||
// hoisted note is kept intentionally
|
||||
|
||||
this.triggerEvent("noteSwitched", {
|
||||
noteContext: this,
|
||||
notePath: this.notePath
|
||||
});
|
||||
|
||||
this.resetViewScope();
|
||||
}
|
||||
|
||||
isEmpty() {
|
||||
return !this.noteId;
|
||||
}
|
||||
|
||||
async setNote(inputNotePath: string | undefined, opts: SetNoteOpts = {}) {
|
||||
opts.triggerSwitchEvent = opts.triggerSwitchEvent !== undefined ? opts.triggerSwitchEvent : true;
|
||||
opts.viewScope = opts.viewScope || {};
|
||||
opts.viewScope.viewMode = opts.viewScope.viewMode || "default";
|
||||
|
||||
if (!inputNotePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resolvedNotePath = await this.getResolvedNotePath(inputNotePath);
|
||||
|
||||
if (!resolvedNotePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.notePath === resolvedNotePath && utils.areObjectsEqual(this.viewScope, opts.viewScope)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.triggerEvent("beforeNoteSwitch", { noteContext: this });
|
||||
|
||||
utils.closeActiveDialog();
|
||||
|
||||
this.notePath = resolvedNotePath;
|
||||
this.viewScope = opts.viewScope;
|
||||
({ noteId: this.noteId, parentNoteId: this.parentNoteId } = treeService.getNoteIdAndParentIdFromUrl(resolvedNotePath));
|
||||
|
||||
this.saveToRecentNotes(resolvedNotePath);
|
||||
|
||||
protectedSessionHolder.touchProtectedSessionIfNecessary(this.note);
|
||||
|
||||
if (opts.triggerSwitchEvent) {
|
||||
await this.triggerEvent("noteSwitched", {
|
||||
noteContext: this,
|
||||
notePath: this.notePath
|
||||
});
|
||||
}
|
||||
|
||||
await this.setHoistedNoteIfNeeded();
|
||||
|
||||
if (utils.isMobile()) {
|
||||
this.triggerCommand("setActiveScreen", { screen: "detail" });
|
||||
}
|
||||
}
|
||||
|
||||
async setHoistedNoteIfNeeded() {
|
||||
if (this.hoistedNoteId === "root" && this.notePath?.startsWith("root/_hidden") && !this.note?.isLabelTruthy("keepCurrentHoisting")) {
|
||||
// hidden subtree displays only when hoisted, so it doesn't make sense to keep root as hoisted note
|
||||
|
||||
let hoistedNoteId = "_hidden";
|
||||
|
||||
if (this.note?.isLaunchBarConfig()) {
|
||||
hoistedNoteId = "_lbRoot";
|
||||
} else if (this.note?.isOptions()) {
|
||||
hoistedNoteId = "_options";
|
||||
}
|
||||
|
||||
await this.setHoistedNoteId(hoistedNoteId);
|
||||
}
|
||||
}
|
||||
|
||||
getSubContexts() {
|
||||
return appContext.tabManager.noteContexts.filter((nc) => nc.ntxId === this.ntxId || nc.mainNtxId === this.ntxId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A main context represents a tab and also the first split. Further splits are the children contexts of the main context.
|
||||
* Imagine you have a tab with 3 splits, each showing notes A, B, C (in this order).
|
||||
* In such a scenario, A context is the main context (also representing the tab as a whole), and B, C are the children
|
||||
* of context A.
|
||||
*
|
||||
* @returns {boolean} true if the context is main (= tab)
|
||||
*/
|
||||
isMainContext() {
|
||||
// if null, then this is a main context
|
||||
return !this.mainNtxId;
|
||||
}
|
||||
|
||||
/**
|
||||
* See docs for isMainContext() for better explanation.
|
||||
*
|
||||
* @returns {NoteContext}
|
||||
*/
|
||||
getMainContext() {
|
||||
if (this.mainNtxId) {
|
||||
try {
|
||||
return appContext.tabManager.getNoteContextById(this.mainNtxId);
|
||||
} catch (e) {
|
||||
this.mainNtxId = null;
|
||||
return this;
|
||||
}
|
||||
} else {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
saveToRecentNotes(resolvedNotePath: string) {
|
||||
setTimeout(async () => {
|
||||
// we include the note in the recent list only if the user stayed on the note at least 5 seconds
|
||||
if (resolvedNotePath && resolvedNotePath === this.notePath) {
|
||||
await server.post("recent-notes", {
|
||||
noteId: this.note?.noteId,
|
||||
notePath: this.notePath
|
||||
});
|
||||
utils.reloadTray();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
async getResolvedNotePath(inputNotePath: string) {
|
||||
const resolvedNotePath = await treeService.resolveNotePath(inputNotePath, this.hoistedNoteId);
|
||||
|
||||
if (!resolvedNotePath) {
|
||||
logError(`Cannot resolve note path ${inputNotePath}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if ((await hoistedNoteService.checkNoteAccess(resolvedNotePath, this)) === false) {
|
||||
return; // note is outside of hoisted subtree and user chose not to unhoist
|
||||
}
|
||||
|
||||
return resolvedNotePath;
|
||||
}
|
||||
|
||||
get note(): FNote | null {
|
||||
if (!this.noteId || !(this.noteId in froca.notes)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return froca.notes[this.noteId];
|
||||
}
|
||||
|
||||
/** @returns {string[]} */
|
||||
get notePathArray() {
|
||||
return this.notePath ? this.notePath.split("/") : [];
|
||||
}
|
||||
|
||||
isActive() {
|
||||
return appContext.tabManager.activeNtxId === this.ntxId;
|
||||
}
|
||||
|
||||
getPojoState() {
|
||||
if (this.hoistedNoteId !== "root") {
|
||||
// keeping empty hoisted tab is esp. important for mobile (e.g. opened launcher config)
|
||||
|
||||
if (!this.notePath && this.getSubContexts().length === 0) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ntxId: this.ntxId,
|
||||
mainNtxId: this.mainNtxId,
|
||||
notePath: this.notePath,
|
||||
hoistedNoteId: this.hoistedNoteId,
|
||||
active: this.isActive(),
|
||||
viewScope: this.viewScope
|
||||
};
|
||||
}
|
||||
|
||||
async unhoist() {
|
||||
await this.setHoistedNoteId("root");
|
||||
}
|
||||
|
||||
async setHoistedNoteId(noteIdToHoist: string) {
|
||||
if (this.hoistedNoteId === noteIdToHoist) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.hoistedNoteId = noteIdToHoist;
|
||||
|
||||
if (!this.notePathArray?.includes(noteIdToHoist)) {
|
||||
await this.setNote(noteIdToHoist);
|
||||
}
|
||||
|
||||
await this.triggerEvent("hoistedNoteChanged", {
|
||||
noteId: noteIdToHoist,
|
||||
ntxId: this.ntxId
|
||||
});
|
||||
}
|
||||
|
||||
/** @returns {Promise<boolean>} */
|
||||
async isReadOnly() {
|
||||
if (this?.viewScope?.readOnlyTemporarilyDisabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// "readOnly" is a state valid only for text/code notes
|
||||
if (!this.note || (this.note.type !== "text" && this.note.type !== "code")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.note.isLabelTruthy("readOnly")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.viewScope?.viewMode === "source") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const blob = await this.note.getBlob();
|
||||
if (!blob) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const sizeLimit = this.note.type === "text" ? options.getInt("autoReadonlySizeText") : options.getInt("autoReadonlySizeCode");
|
||||
|
||||
return sizeLimit && blob.contentLength > sizeLimit && !this.note.isLabelTruthy("autoReadOnlyDisabled");
|
||||
}
|
||||
|
||||
async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
|
||||
if (this.noteId && loadResults.isNoteReloaded(this.noteId)) {
|
||||
const noteRow = loadResults.getEntityRow("notes", this.noteId);
|
||||
|
||||
if (noteRow.isDeleted) {
|
||||
this.noteId = null;
|
||||
this.notePath = null;
|
||||
|
||||
this.triggerEvent("noteSwitched", {
|
||||
noteContext: this,
|
||||
notePath: this.notePath
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasNoteList() {
|
||||
return (
|
||||
this.note &&
|
||||
["default", "contextual-help"].includes(this.viewScope?.viewMode ?? "") &&
|
||||
(this.note.hasChildren() || this.note.getLabelValue("viewType") === "calendar") &&
|
||||
["book", "text", "code"].includes(this.note.type) &&
|
||||
this.note.mime !== "text/x-sqlite;schema=trilium" &&
|
||||
!this.note.isLabelTruthy("hideChildrenOverview")
|
||||
);
|
||||
}
|
||||
|
||||
async getTextEditor(callback?: GetTextEditorCallback) {
|
||||
return this.timeout<TextEditor>(
|
||||
new Promise((resolve) =>
|
||||
appContext.triggerCommand("executeWithTextEditor", {
|
||||
callback,
|
||||
resolve,
|
||||
ntxId: this.ntxId
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
async getCodeEditor() {
|
||||
return this.timeout(
|
||||
new Promise<CodeMirrorInstance>((resolve) =>
|
||||
appContext.triggerCommand("executeWithCodeEditor", {
|
||||
resolve,
|
||||
ntxId: this.ntxId
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a promise which will retrieve the JQuery element of the content of this note context.
|
||||
*
|
||||
* Do note that retrieving the content element needs to be handled by the type widget, which is the one which
|
||||
* provides the content element by listening to the `executeWithContentElement` event. Not all note types support
|
||||
* this.
|
||||
*
|
||||
* If no content could be determined `null` is returned instead.
|
||||
*/
|
||||
async getContentElement() {
|
||||
return this.timeout<JQuery<HTMLElement>>(
|
||||
new Promise((resolve) =>
|
||||
appContext.triggerCommand("executeWithContentElement", {
|
||||
resolve,
|
||||
ntxId: this.ntxId
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
async getTypeWidget() {
|
||||
return this.timeout(
|
||||
new Promise<TypeWidget | null>((resolve) =>
|
||||
appContext.triggerCommand("executeWithTypeWidget", {
|
||||
resolve,
|
||||
ntxId: this.ntxId
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
timeout<T>(promise: Promise<T | null>) {
|
||||
return Promise.race([promise, new Promise((res) => setTimeout(() => res(null), 200))]) as Promise<T>;
|
||||
}
|
||||
|
||||
resetViewScope() {
|
||||
// view scope contains data specific to one note context and one "view".
|
||||
// it is used to e.g., make read-only note temporarily editable or to hide TOC
|
||||
// this is reset after navigating to a different note
|
||||
this.viewScope = {};
|
||||
}
|
||||
|
||||
async getNavigationTitle() {
|
||||
if (!this.note) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { note, viewScope } = this;
|
||||
|
||||
const isNormalView = (viewScope?.viewMode === "default" || viewScope?.viewMode === "contextual-help");
|
||||
let title = (isNormalView ? note.title : `${note.title}: ${viewScope?.viewMode}`);
|
||||
|
||||
if (viewScope?.attachmentId) {
|
||||
// assuming the attachment has been already loaded
|
||||
const attachment = await note.getAttachmentById(viewScope.attachmentId);
|
||||
|
||||
if (attachment) {
|
||||
title += `: ${attachment.title}`;
|
||||
}
|
||||
}
|
||||
|
||||
return title;
|
||||
}
|
||||
}
|
||||
|
||||
export default NoteContext;
|
||||
263
apps/client/src/components/root_command_executor.ts
Normal file
263
apps/client/src/components/root_command_executor.ts
Normal file
@@ -0,0 +1,263 @@
|
||||
import Component from "./component.js";
|
||||
import appContext, { type CommandData, type CommandListenerData } from "./app_context.js";
|
||||
import dateNoteService from "../services/date_notes.js";
|
||||
import treeService from "../services/tree.js";
|
||||
import openService from "../services/open.js";
|
||||
import protectedSessionService from "../services/protected_session.js";
|
||||
import options from "../services/options.js";
|
||||
import froca from "../services/froca.js";
|
||||
import utils from "../services/utils.js";
|
||||
import LlmChatPanel from "../widgets/llm_chat_panel.js";
|
||||
import toastService from "../services/toast.js";
|
||||
import noteCreateService from "../services/note_create.js";
|
||||
|
||||
export default class RootCommandExecutor extends Component {
|
||||
editReadOnlyNoteCommand() {
|
||||
const noteContext = appContext.tabManager.getActiveContext();
|
||||
if (noteContext?.viewScope) {
|
||||
noteContext.viewScope.readOnlyTemporarilyDisabled = true;
|
||||
appContext.triggerEvent("readOnlyTemporarilyDisabled", { noteContext });
|
||||
}
|
||||
}
|
||||
|
||||
async showSQLConsoleCommand() {
|
||||
const sqlConsoleNote = await dateNoteService.createSqlConsole();
|
||||
if (!sqlConsoleNote) {
|
||||
return;
|
||||
}
|
||||
|
||||
const noteContext = await appContext.tabManager.openTabWithNoteWithHoisting(sqlConsoleNote.noteId, { activate: true });
|
||||
|
||||
appContext.triggerEvent("focusOnDetail", { ntxId: noteContext.ntxId });
|
||||
}
|
||||
|
||||
async searchNotesCommand({ searchString, ancestorNoteId }: CommandListenerData<"searchNotes">) {
|
||||
const searchNote = await dateNoteService.createSearchNote({ searchString, ancestorNoteId });
|
||||
if (!searchNote) {
|
||||
return;
|
||||
}
|
||||
|
||||
// force immediate search
|
||||
await froca.loadSearchNote(searchNote.noteId);
|
||||
|
||||
const noteContext = await appContext.tabManager.openTabWithNoteWithHoisting(searchNote.noteId, {
|
||||
activate: true
|
||||
});
|
||||
|
||||
appContext.triggerCommand("focusOnSearchDefinition", { ntxId: noteContext.ntxId });
|
||||
}
|
||||
|
||||
async searchInSubtreeCommand({ notePath }: CommandListenerData<"searchInSubtree">) {
|
||||
const noteId = treeService.getNoteIdFromUrl(notePath);
|
||||
|
||||
this.searchNotesCommand({ ancestorNoteId: noteId });
|
||||
}
|
||||
|
||||
openNoteExternallyCommand() {
|
||||
const noteId = appContext.tabManager.getActiveContextNoteId();
|
||||
const mime = appContext.tabManager.getActiveContextNoteMime();
|
||||
if (noteId) {
|
||||
openService.openNoteExternally(noteId, mime || "");
|
||||
}
|
||||
}
|
||||
|
||||
openNoteCustomCommand() {
|
||||
const noteId = appContext.tabManager.getActiveContextNoteId();
|
||||
const mime = appContext.tabManager.getActiveContextNoteMime();
|
||||
if (noteId) {
|
||||
openService.openNoteCustom(noteId, mime || "");
|
||||
}
|
||||
}
|
||||
|
||||
enterProtectedSessionCommand() {
|
||||
protectedSessionService.enterProtectedSession();
|
||||
}
|
||||
|
||||
leaveProtectedSessionCommand() {
|
||||
protectedSessionService.leaveProtectedSession();
|
||||
}
|
||||
|
||||
hideLeftPaneCommand() {
|
||||
options.save(`leftPaneVisible`, "false");
|
||||
}
|
||||
|
||||
showLeftPaneCommand() {
|
||||
options.save(`leftPaneVisible`, "true");
|
||||
}
|
||||
|
||||
toggleLeftPaneCommand() {
|
||||
options.toggle("leftPaneVisible");
|
||||
}
|
||||
|
||||
async showBackendLogCommand() {
|
||||
await appContext.tabManager.openTabWithNoteWithHoisting("_backendLog", { activate: true });
|
||||
}
|
||||
|
||||
async showHelpCommand() {
|
||||
await this.showAndHoistSubtree("_help");
|
||||
}
|
||||
|
||||
async showLaunchBarSubtreeCommand() {
|
||||
const rootNote = utils.isMobile() ? "_lbMobileRoot" : "_lbRoot";
|
||||
await this.showAndHoistSubtree(rootNote);
|
||||
this.showLeftPaneCommand();
|
||||
}
|
||||
|
||||
async showShareSubtreeCommand() {
|
||||
await this.showAndHoistSubtree("_share");
|
||||
}
|
||||
|
||||
async showHiddenSubtreeCommand() {
|
||||
await this.showAndHoistSubtree("_hidden");
|
||||
}
|
||||
|
||||
async showOptionsCommand({ section }: CommandListenerData<"showOptions">) {
|
||||
await appContext.tabManager.openContextWithNote(section || "_options", {
|
||||
activate: true,
|
||||
hoistedNoteId: "_options"
|
||||
});
|
||||
}
|
||||
|
||||
async showSQLConsoleHistoryCommand() {
|
||||
await this.showAndHoistSubtree("_sqlConsole");
|
||||
}
|
||||
|
||||
async showSearchHistoryCommand() {
|
||||
await this.showAndHoistSubtree("_search");
|
||||
}
|
||||
|
||||
async showAndHoistSubtree(subtreeNoteId: string) {
|
||||
await appContext.tabManager.openContextWithNote(subtreeNoteId, {
|
||||
activate: true,
|
||||
hoistedNoteId: subtreeNoteId
|
||||
});
|
||||
}
|
||||
|
||||
async showNoteSourceCommand() {
|
||||
const notePath = appContext.tabManager.getActiveContextNotePath();
|
||||
|
||||
if (notePath) {
|
||||
await appContext.tabManager.openTabWithNoteWithHoisting(notePath, {
|
||||
activate: true,
|
||||
viewScope: {
|
||||
viewMode: "source"
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async showAttachmentsCommand() {
|
||||
const notePath = appContext.tabManager.getActiveContextNotePath();
|
||||
|
||||
if (notePath) {
|
||||
await appContext.tabManager.openTabWithNoteWithHoisting(notePath, {
|
||||
activate: true,
|
||||
viewScope: {
|
||||
viewMode: "attachments"
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async showAttachmentDetailCommand() {
|
||||
const notePath = appContext.tabManager.getActiveContextNotePath();
|
||||
|
||||
if (notePath) {
|
||||
await appContext.tabManager.openTabWithNoteWithHoisting(notePath, {
|
||||
activate: true,
|
||||
viewScope: {
|
||||
viewMode: "attachments"
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
toggleTrayCommand() {
|
||||
if (!utils.isElectron()) return;
|
||||
const { BrowserWindow } = utils.dynamicRequire("@electron/remote");
|
||||
const windows = BrowserWindow.getAllWindows() as Electron.BaseWindow[];
|
||||
const isVisible = windows.every((w) => w.isVisible());
|
||||
const action = isVisible ? "hide" : "show";
|
||||
for (const window of windows) window[action]();
|
||||
}
|
||||
|
||||
toggleZenModeCommand() {
|
||||
const $body = $("body");
|
||||
$body.toggleClass("zen");
|
||||
const isEnabled = $body.hasClass("zen");
|
||||
appContext.triggerEvent("zenModeChanged", { isEnabled });
|
||||
}
|
||||
|
||||
firstTabCommand() {
|
||||
this.#goToTab(1);
|
||||
}
|
||||
secondTabCommand() {
|
||||
this.#goToTab(2);
|
||||
}
|
||||
thirdTabCommand() {
|
||||
this.#goToTab(3);
|
||||
}
|
||||
fourthTabCommand() {
|
||||
this.#goToTab(4);
|
||||
}
|
||||
fifthTabCommand() {
|
||||
this.#goToTab(5);
|
||||
}
|
||||
sixthTabCommand() {
|
||||
this.#goToTab(6);
|
||||
}
|
||||
seventhTabCommand() {
|
||||
this.#goToTab(7);
|
||||
}
|
||||
eigthTabCommand() {
|
||||
this.#goToTab(8);
|
||||
}
|
||||
ninthTabCommand() {
|
||||
this.#goToTab(9);
|
||||
}
|
||||
lastTabCommand() {
|
||||
this.#goToTab(Number.POSITIVE_INFINITY);
|
||||
}
|
||||
|
||||
#goToTab(tabNumber: number) {
|
||||
const mainNoteContexts = appContext.tabManager.getMainNoteContexts();
|
||||
|
||||
const index = tabNumber === Number.POSITIVE_INFINITY ? mainNoteContexts.length - 1 : tabNumber - 1;
|
||||
const tab = mainNoteContexts[index];
|
||||
|
||||
if (tab) {
|
||||
appContext.tabManager.activateNoteContext(tab.ntxId);
|
||||
}
|
||||
}
|
||||
|
||||
async createAiChatCommand() {
|
||||
try {
|
||||
// Create a new AI Chat note at the root level
|
||||
const rootNoteId = "root";
|
||||
|
||||
const result = await noteCreateService.createNote(rootNoteId, {
|
||||
title: "New AI Chat",
|
||||
type: "aiChat",
|
||||
content: JSON.stringify({
|
||||
messages: [],
|
||||
title: "New AI Chat"
|
||||
})
|
||||
});
|
||||
|
||||
if (!result.note) {
|
||||
toastService.showError("Failed to create AI Chat note");
|
||||
return;
|
||||
}
|
||||
|
||||
await appContext.tabManager.openTabWithNoteWithHoisting(result.note.noteId, {
|
||||
activate: true
|
||||
});
|
||||
|
||||
toastService.showMessage("Created new AI Chat note");
|
||||
}
|
||||
catch (e) {
|
||||
console.error("Error creating AI Chat note:", e);
|
||||
toastService.showError("Failed to create AI Chat note: " + (e as Error).message);
|
||||
}
|
||||
}
|
||||
}
|
||||
44
apps/client/src/components/shortcut_component.ts
Normal file
44
apps/client/src/components/shortcut_component.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import appContext, { type EventData, type EventListener } from "./app_context.js";
|
||||
import shortcutService from "../services/shortcuts.js";
|
||||
import server from "../services/server.js";
|
||||
import Component from "./component.js";
|
||||
import froca from "../services/froca.js";
|
||||
import type { AttributeRow } from "../services/load_results.js";
|
||||
|
||||
export default class ShortcutComponent extends Component implements EventListener<"entitiesReloaded"> {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
server.get<AttributeRow[]>("keyboard-shortcuts-for-notes").then((shortcutAttributes) => {
|
||||
for (const attr of shortcutAttributes) {
|
||||
this.bindNoteShortcutHandler(attr);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bindNoteShortcutHandler(labelOrRow: AttributeRow) {
|
||||
const handler = () => appContext.tabManager.getActiveContext()?.setNote(labelOrRow.noteId);
|
||||
const namespace = labelOrRow.attributeId;
|
||||
|
||||
if (labelOrRow.isDeleted) {
|
||||
// only applicable if row
|
||||
if (namespace) {
|
||||
shortcutService.removeGlobalShortcut(namespace);
|
||||
}
|
||||
} else if (labelOrRow.value) {
|
||||
shortcutService.bindGlobalShortcut(labelOrRow.value, handler, namespace);
|
||||
}
|
||||
}
|
||||
|
||||
async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
|
||||
for (const attr of loadResults.getAttributeRows()) {
|
||||
if (attr.type === "label" && attr.name === "keyboardShortcut" && attr.noteId) {
|
||||
const note = await froca.getNote(attr.noteId);
|
||||
// launcher shortcuts are handled specifically
|
||||
if (note && attr && note.type !== "launcher") {
|
||||
this.bindNoteShortcutHandler(attr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
700
apps/client/src/components/tab_manager.ts
Normal file
700
apps/client/src/components/tab_manager.ts
Normal file
@@ -0,0 +1,700 @@
|
||||
import Component from "./component.js";
|
||||
import SpacedUpdate from "../services/spaced_update.js";
|
||||
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 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<string, any>;
|
||||
}
|
||||
|
||||
export default class TabManager extends Component {
|
||||
public children: NoteContext[];
|
||||
public mutex: Mutex;
|
||||
public activeNtxId: string | null;
|
||||
public recentlyClosedTabs: TabState[];
|
||||
public tabsUpdate: SpacedUpdate;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.children = [];
|
||||
this.mutex = new Mutex();
|
||||
this.activeNtxId = null;
|
||||
this.recentlyClosedTabs = [];
|
||||
|
||||
this.tabsUpdate = new SpacedUpdate(async () => {
|
||||
if (!appContext.isMainWindow) {
|
||||
return;
|
||||
}
|
||||
|
||||
const openNoteContexts = this.noteContexts
|
||||
.map((nc) => nc.getPojoState())
|
||||
.filter((t) => !!t);
|
||||
|
||||
await server.put("options", {
|
||||
openNoteContexts: JSON.stringify(openNoteContexts)
|
||||
});
|
||||
});
|
||||
|
||||
appContext.addBeforeUnloadListener(this);
|
||||
}
|
||||
|
||||
get noteContexts(): NoteContext[] {
|
||||
return this.children;
|
||||
}
|
||||
|
||||
get mainNoteContexts(): NoteContext[] {
|
||||
return this.noteContexts.filter((nc) => !nc.mainNtxId);
|
||||
}
|
||||
|
||||
async loadTabs() {
|
||||
try {
|
||||
const noteContextsToOpen = (appContext.isMainWindow && options.getJson("openNoteContexts")) || [];
|
||||
|
||||
// preload all notes at once
|
||||
await froca.getNotes([...noteContextsToOpen.flatMap((tab: NoteContextState) =>
|
||||
[treeService.getNoteIdFromUrl(tab.notePath), tab.hoistedNoteId])], true);
|
||||
|
||||
const filteredNoteContexts = noteContextsToOpen.filter((openTab: NoteContextState) => {
|
||||
const noteId = treeService.getNoteIdFromUrl(openTab.notePath);
|
||||
if (!noteId || !(noteId in froca.notes)) {
|
||||
// note doesn't exist so don't try to open tab for it
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(openTab.hoistedNoteId in froca.notes)) {
|
||||
openTab.hoistedNoteId = "root";
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// resolve before opened tabs can change this
|
||||
const parsedFromUrl = linkService.parseNavigationStateFromUrl(window.location.href);
|
||||
|
||||
if (filteredNoteContexts.length === 0) {
|
||||
parsedFromUrl.ntxId = parsedFromUrl.ntxId || NoteContext.generateNtxId(); // generate already here, so that we later know which one to activate
|
||||
|
||||
filteredNoteContexts.push({
|
||||
notePath: parsedFromUrl.notePath || "root",
|
||||
ntxId: parsedFromUrl.ntxId,
|
||||
active: true,
|
||||
hoistedNoteId: parsedFromUrl.hoistedNoteId || "root",
|
||||
viewScope: parsedFromUrl.viewScope || {}
|
||||
});
|
||||
} else if (!filteredNoteContexts.find((tab: NoteContextState) => tab.active)) {
|
||||
filteredNoteContexts[0].active = true;
|
||||
}
|
||||
|
||||
await this.tabsUpdate.allowUpdateWithoutChange(async () => {
|
||||
for (const tab of filteredNoteContexts) {
|
||||
await this.openContextWithNote(tab.notePath, {
|
||||
activate: tab.active,
|
||||
ntxId: tab.ntxId,
|
||||
mainNtxId: tab.mainNtxId,
|
||||
hoistedNoteId: tab.hoistedNoteId,
|
||||
viewScope: tab.viewScope
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 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
|
||||
);
|
||||
} else if (parsedFromUrl.searchString) {
|
||||
await appContext.triggerCommand("searchNotes", {
|
||||
searchString: parsedFromUrl.searchString
|
||||
});
|
||||
}
|
||||
} 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 }: EventData<"noteSwitched">) {
|
||||
if (noteContext.isActive()) {
|
||||
this.setCurrentNavigationStateToHash();
|
||||
}
|
||||
|
||||
this.tabsUpdate.scheduleUpdate();
|
||||
}
|
||||
|
||||
setCurrentNavigationStateToHash() {
|
||||
const calculatedHash = this.calculateHash();
|
||||
|
||||
// update if it's the first history entry or there has been a change
|
||||
if (window.history.length === 0 || calculatedHash !== window.location?.hash) {
|
||||
// using pushState instead of directly modifying document.location because it does not trigger hashchange
|
||||
window.history.pushState(null, "", calculatedHash);
|
||||
}
|
||||
|
||||
const activeNoteContext = this.getActiveContext();
|
||||
this.updateDocumentTitle(activeNoteContext);
|
||||
|
||||
this.triggerEvent("activeNoteChanged", {}); // trigger this even in on popstate event
|
||||
}
|
||||
|
||||
calculateHash(): string {
|
||||
const activeNoteContext = this.getActiveContext();
|
||||
if (!activeNoteContext) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return linkService.calculateHash({
|
||||
notePath: activeNoteContext.notePath,
|
||||
ntxId: activeNoteContext.ntxId,
|
||||
hoistedNoteId: activeNoteContext.hoistedNoteId,
|
||||
viewScope: activeNoteContext.viewScope
|
||||
});
|
||||
}
|
||||
|
||||
getNoteContexts(): NoteContext[] {
|
||||
return this.noteContexts;
|
||||
}
|
||||
|
||||
getMainNoteContexts(): NoteContext[] {
|
||||
return this.noteContexts.filter((nc) => nc.isMainContext());
|
||||
}
|
||||
|
||||
getNoteContextById(ntxId: string | null): NoteContext {
|
||||
const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId);
|
||||
|
||||
if (!noteContext) {
|
||||
throw new Error(`Cannot find noteContext id='${ntxId}'`);
|
||||
}
|
||||
|
||||
return noteContext;
|
||||
}
|
||||
|
||||
getActiveContext(): NoteContext | null {
|
||||
return this.activeNtxId ? this.getNoteContextById(this.activeNtxId) : null;
|
||||
}
|
||||
|
||||
getActiveMainContext(): NoteContext | null {
|
||||
return this.activeNtxId ? this.getNoteContextById(this.activeNtxId).getMainContext() : null;
|
||||
}
|
||||
|
||||
getActiveContextNotePath(): string | null {
|
||||
const activeContext = this.getActiveContext();
|
||||
return activeContext?.notePath ?? null;
|
||||
}
|
||||
|
||||
getActiveContextNote(): FNote | null {
|
||||
const activeContext = this.getActiveContext();
|
||||
return activeContext ? activeContext.note : null;
|
||||
}
|
||||
|
||||
getActiveContextNoteId(): string | null {
|
||||
const activeNote = this.getActiveContextNote();
|
||||
return activeNote ? activeNote.noteId : null;
|
||||
}
|
||||
|
||||
getActiveContextNoteType(): string | null {
|
||||
const activeNote = this.getActiveContextNote();
|
||||
return activeNote ? activeNote.type : null;
|
||||
}
|
||||
|
||||
getActiveContextNoteMime(): string | null {
|
||||
const activeNote = this.getActiveContextNote();
|
||||
return activeNote ? activeNote.mime : null;
|
||||
}
|
||||
|
||||
async switchToNoteContext(
|
||||
ntxId: string | null,
|
||||
notePath: string,
|
||||
viewScope: Record<string, any> = {},
|
||||
hoistedNoteId: string | null = null
|
||||
) {
|
||||
const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId) ||
|
||||
await this.openEmptyTab();
|
||||
|
||||
await this.activateNoteContext(noteContext.ntxId);
|
||||
|
||||
if (hoistedNoteId) {
|
||||
await noteContext.setHoistedNoteId(hoistedNoteId);
|
||||
}
|
||||
|
||||
if (notePath) {
|
||||
await noteContext.setNote(notePath, { viewScope });
|
||||
}
|
||||
}
|
||||
|
||||
async openAndActivateEmptyTab() {
|
||||
const noteContext = await this.openEmptyTab();
|
||||
await this.activateNoteContext(noteContext.ntxId);
|
||||
noteContext.setEmpty();
|
||||
}
|
||||
|
||||
async openEmptyTab(
|
||||
ntxId: string | null = null,
|
||||
hoistedNoteId: string = "root",
|
||||
mainNtxId: string | null = null
|
||||
): Promise<NoteContext> {
|
||||
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;
|
||||
}
|
||||
|
||||
this.child(noteContext);
|
||||
|
||||
await this.triggerEvent("newNoteContextCreated", { noteContext });
|
||||
|
||||
return noteContext;
|
||||
}
|
||||
|
||||
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: string, hoistedNoteId: string | null = null) {
|
||||
const activeContext = this.getActiveContext();
|
||||
if (!activeContext) return;
|
||||
|
||||
await activeContext.setHoistedNoteId(hoistedNoteId || activeContext.hoistedNoteId);
|
||||
await activeContext.setNote(targetNoteId);
|
||||
}
|
||||
|
||||
async openTabWithNoteWithHoisting(
|
||||
notePath: string,
|
||||
opts: {
|
||||
activate?: boolean | null;
|
||||
ntxId?: string | null;
|
||||
mainNtxId?: string | null;
|
||||
hoistedNoteId?: string | null;
|
||||
viewScope?: Record<string, any> | null;
|
||||
} = {}
|
||||
): Promise<NoteContext> {
|
||||
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")) {
|
||||
hoistedNoteId = noteContext.hoistedNoteId;
|
||||
}
|
||||
}
|
||||
|
||||
opts.hoistedNoteId = hoistedNoteId;
|
||||
|
||||
return this.openContextWithNote(notePath, opts);
|
||||
}
|
||||
|
||||
async openContextWithNote(
|
||||
notePath: string | null,
|
||||
opts: {
|
||||
activate?: boolean | null;
|
||||
ntxId?: string | null;
|
||||
mainNtxId?: string | null;
|
||||
hoistedNoteId?: string | null;
|
||||
viewScope?: Record<string, any> | null;
|
||||
} = {}
|
||||
): Promise<NoteContext> {
|
||||
const activate = !!opts.activate;
|
||||
const ntxId = opts.ntxId || null;
|
||||
const mainNtxId = opts.mainNtxId || null;
|
||||
const hoistedNoteId = opts.hoistedNoteId || "root";
|
||||
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
|
||||
triggerSwitchEvent: !activate,
|
||||
viewScope: viewScope
|
||||
});
|
||||
}
|
||||
|
||||
if (activate && noteContext.notePath) {
|
||||
this.activateNoteContext(noteContext.ntxId, false);
|
||||
|
||||
await this.triggerEvent("noteSwitchedAndActivated", {
|
||||
noteContext,
|
||||
notePath: noteContext.notePath // resolved note path
|
||||
});
|
||||
}
|
||||
|
||||
return noteContext;
|
||||
}
|
||||
|
||||
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: string | null, triggerEvent: boolean = true) {
|
||||
if (!ntxId) {
|
||||
logError("activateNoteContext: ntxId is null");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ntxId === this.activeNtxId) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.activeNtxId = ntxId;
|
||||
|
||||
if (triggerEvent) {
|
||||
await this.triggerEvent("activeContextChanged", {
|
||||
noteContext: this.getNoteContextById(ntxId)
|
||||
});
|
||||
}
|
||||
|
||||
this.tabsUpdate.scheduleUpdate();
|
||||
|
||||
this.setCurrentNavigationStateToHash();
|
||||
}
|
||||
|
||||
async removeNoteContext(ntxId: string | null): Promise<boolean> {
|
||||
// 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 (): Promise<boolean> => {
|
||||
let noteContextToRemove;
|
||||
|
||||
try {
|
||||
noteContextToRemove = this.getNoteContextById(ntxId);
|
||||
} catch {
|
||||
// note context not found
|
||||
return false;
|
||||
}
|
||||
|
||||
if (noteContextToRemove.isMainContext()) {
|
||||
const mainNoteContexts = this.getNoteContexts().filter((nc) => nc.isMainContext());
|
||||
|
||||
if (mainNoteContexts.length === 1) {
|
||||
if (noteContextToRemove.isEmpty()) {
|
||||
// this is already the empty note context, no point in closing it and replacing with another
|
||||
// empty tab
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.openEmptyTab();
|
||||
}
|
||||
}
|
||||
|
||||
// close dangling autocompletes after closing the tab
|
||||
const $autocompleteEl = $(".aa-input");
|
||||
if ("autocomplete" in $autocompleteEl) {
|
||||
$autocompleteEl.autocomplete("close");
|
||||
}
|
||||
|
||||
const noteContextsToRemove = noteContextToRemove.getSubContexts();
|
||||
const ntxIdsToRemove = noteContextsToRemove.map((nc) => nc.ntxId);
|
||||
|
||||
await this.triggerEvent("beforeNoteContextRemove", { ntxIds: ntxIdsToRemove.filter((id) => id !== null) });
|
||||
|
||||
if (!noteContextToRemove.isMainContext()) {
|
||||
const siblings = noteContextToRemove.getMainContext().getSubContexts();
|
||||
const idx = siblings.findIndex((nc) => nc.ntxId === noteContextToRemove.ntxId);
|
||||
const contextToActivateIdx = idx === siblings.length - 1 ? idx - 1 : idx + 1;
|
||||
const contextToActivate = siblings[contextToActivateIdx];
|
||||
|
||||
await this.activateNoteContext(contextToActivate.ntxId);
|
||||
} else if (this.mainNoteContexts.length <= 1) {
|
||||
await this.openAndActivateEmptyTab();
|
||||
} else if (ntxIdsToRemove.includes(this.activeNtxId)) {
|
||||
const idx = this.mainNoteContexts.findIndex((nc) => nc.ntxId === noteContextToRemove.ntxId);
|
||||
|
||||
if (idx === this.mainNoteContexts.length - 1) {
|
||||
await this.activatePreviousTabCommand();
|
||||
} else {
|
||||
await this.activateNextTabCommand();
|
||||
}
|
||||
}
|
||||
|
||||
this.removeNoteContexts(noteContextsToRemove);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
removeNoteContexts(noteContextsToRemove: NoteContext[]) {
|
||||
const ntxIdsToRemove = noteContextsToRemove.map((nc) => nc.ntxId);
|
||||
|
||||
const position = this.noteContexts.findIndex((nc) => ntxIdsToRemove.includes(nc.ntxId));
|
||||
|
||||
this.children = this.children.filter((nc) => !ntxIdsToRemove.includes(nc.ntxId));
|
||||
|
||||
this.addToRecentlyClosedTabs(noteContextsToRemove, position);
|
||||
|
||||
this.triggerEvent("noteContextRemoved", { ntxIds: ntxIdsToRemove.filter((id) => id !== null) });
|
||||
|
||||
this.tabsUpdate.scheduleUpdate();
|
||||
}
|
||||
|
||||
addToRecentlyClosedTabs(noteContexts: NoteContext[], position: number) {
|
||||
if (noteContexts.length === 1 && noteContexts[0].isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.recentlyClosedTabs.push({ contexts: noteContexts, position: position });
|
||||
}
|
||||
|
||||
tabReorderEvent({ ntxIdsInOrder }: { ntxIdsInOrder: string[] }) {
|
||||
const order: Record<string, number> = {};
|
||||
|
||||
let i = 0;
|
||||
|
||||
for (const ntxId of ntxIdsInOrder) {
|
||||
for (const noteContext of this.getNoteContextById(ntxId).getSubContexts()) {
|
||||
if (noteContext.ntxId) {
|
||||
order[noteContext.ntxId] = i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}: {
|
||||
ntxIdsInOrder: string[];
|
||||
oldMainNtxId?: string;
|
||||
newMainNtxId?: string;
|
||||
}) {
|
||||
const order = Object.fromEntries(ntxIdsInOrder.map((v, i) => [v, i]));
|
||||
|
||||
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) => {
|
||||
if (c.ntxId === newMainNtxId) {
|
||||
// new main context has null mainNtxId
|
||||
c.mainNtxId = null;
|
||||
} else if (c.ntxId === oldMainNtxId || c.mainNtxId === oldMainNtxId) {
|
||||
// old main context or subcontexts all have the new mainNtxId
|
||||
c.mainNtxId = newMainNtxId;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
this.tabsUpdate.scheduleUpdate();
|
||||
}
|
||||
|
||||
async activateNextTabCommand() {
|
||||
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;
|
||||
|
||||
await this.activateNoteContext(newActiveNtxId);
|
||||
}
|
||||
|
||||
async activatePreviousTabCommand() {
|
||||
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;
|
||||
|
||||
await this.activateNoteContext(newActiveNtxId);
|
||||
}
|
||||
|
||||
async closeActiveTabCommand() {
|
||||
await this.removeNoteContext(this.activeNtxId);
|
||||
}
|
||||
|
||||
beforeUnloadEvent(): boolean {
|
||||
this.tabsUpdate.updateNowIfNecessary();
|
||||
return true; // don't block closing the tab, this metadata is not that important
|
||||
}
|
||||
|
||||
openNewTabCommand() {
|
||||
this.openAndActivateEmptyTab();
|
||||
}
|
||||
|
||||
async closeAllTabsCommand() {
|
||||
for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) {
|
||||
await this.removeNoteContext(ntxIdToRemove);
|
||||
}
|
||||
}
|
||||
|
||||
async closeOtherTabsCommand({ ntxId }: { ntxId: string }) {
|
||||
for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) {
|
||||
if (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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async closeTabCommand({ ntxId }: { ntxId: string }) {
|
||||
await this.removeNoteContext(ntxId);
|
||||
}
|
||||
|
||||
async moveTabToNewWindowCommand({ ntxId }: { ntxId: string }) {
|
||||
const { notePath, hoistedNoteId } = this.getNoteContextById(ntxId);
|
||||
|
||||
const removed = await this.removeNoteContext(ntxId);
|
||||
|
||||
if (removed) {
|
||||
this.triggerCommand("openInWindow", { notePath, hoistedNoteId });
|
||||
}
|
||||
}
|
||||
|
||||
async copyTabToNewWindowCommand({ ntxId }: { ntxId: string }) {
|
||||
const { notePath, hoistedNoteId } = this.getNoteContextById(ntxId);
|
||||
this.triggerCommand("openInWindow", { notePath, hoistedNoteId });
|
||||
}
|
||||
|
||||
async reopenLastTabCommand() {
|
||||
const closeLastEmptyTab: NoteContext | undefined = await this.mutex.runExclusively(async () => {
|
||||
let closeLastEmptyTab
|
||||
if (this.recentlyClosedTabs.length === 0) {
|
||||
return closeLastEmptyTab;
|
||||
}
|
||||
|
||||
if (this.noteContexts.length === 1 && this.noteContexts[0].isEmpty()) {
|
||||
// new empty tab is created after closing the last tab, this reverses the empty tab creation
|
||||
closeLastEmptyTab = this.noteContexts[0];
|
||||
}
|
||||
|
||||
const lastClosedTab = this.recentlyClosedTabs.pop();
|
||||
if (!lastClosedTab) return closeLastEmptyTab;
|
||||
|
||||
const noteContexts = lastClosedTab.contexts;
|
||||
|
||||
for (const noteContext of noteContexts) {
|
||||
this.child(noteContext);
|
||||
|
||||
await this.triggerEvent("newNoteContextCreated", { noteContext });
|
||||
}
|
||||
|
||||
// restore last position of contexts stored in tab manager
|
||||
const ntxsInOrder = [
|
||||
...this.noteContexts.slice(0, lastClosedTab.position),
|
||||
...this.noteContexts.slice(-noteContexts.length),
|
||||
...this.noteContexts.slice(lastClosedTab.position, -noteContexts.length)
|
||||
];
|
||||
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", {
|
||||
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", {
|
||||
mainNtxId: ntxsInOrder[lastClosedTab.position].ntxId,
|
||||
// this is safe since lastClosedTab.position can never be 0 in this case
|
||||
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);
|
||||
|
||||
await this.triggerEvent("noteSwitched", {
|
||||
noteContext: noteContextToActivate,
|
||||
notePath: noteContextToActivate.notePath
|
||||
});
|
||||
return closeLastEmptyTab;
|
||||
});
|
||||
|
||||
if (closeLastEmptyTab) {
|
||||
await this.removeNoteContext(closeLastEmptyTab.ntxId);
|
||||
}
|
||||
}
|
||||
|
||||
hoistedNoteChangedEvent() {
|
||||
this.tabsUpdate.scheduleUpdate();
|
||||
}
|
||||
|
||||
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(),
|
||||
"TriliumNext Notes"
|
||||
].filter(Boolean);
|
||||
|
||||
document.title = titleFragments.join(" - ");
|
||||
}
|
||||
|
||||
async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
|
||||
const activeContext = this.getActiveContext();
|
||||
|
||||
if (activeContext && loadResults.isNoteReloaded(activeContext.noteId)) {
|
||||
await this.updateDocumentTitle(activeContext);
|
||||
}
|
||||
}
|
||||
|
||||
async frocaReloadedEvent() {
|
||||
const activeContext = this.getActiveContext();
|
||||
if (activeContext) {
|
||||
await this.updateDocumentTitle(activeContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
135
apps/client/src/components/touch_bar.ts
Normal file
135
apps/client/src/components/touch_bar.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import utils from "../services/utils.js";
|
||||
import Component from "./component.js";
|
||||
import appContext from "./app_context.js";
|
||||
import type { TouchBarButton, TouchBarGroup, TouchBarSegmentedControl, TouchBarSpacer } from "@electron/remote";
|
||||
|
||||
export type TouchBarItem = (TouchBarButton | TouchBarSpacer | TouchBarGroup | TouchBarSegmentedControl);
|
||||
|
||||
export function buildSelectedBackgroundColor(isSelected: boolean) {
|
||||
return isSelected ? "#757575" : undefined;
|
||||
}
|
||||
|
||||
export default class TouchBarComponent extends Component {
|
||||
|
||||
nativeImage: typeof import("electron").nativeImage;
|
||||
remote: typeof import("@electron/remote");
|
||||
lastFocusedComponent?: Component;
|
||||
private $activeModal?: JQuery<HTMLElement>;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.nativeImage = utils.dynamicRequire("electron").nativeImage;
|
||||
this.remote = utils.dynamicRequire("@electron/remote") as typeof import("@electron/remote");
|
||||
this.$widget = $("<div>");
|
||||
|
||||
$(window).on("focusin", async (e) => {
|
||||
const $target = $(e.target);
|
||||
|
||||
this.$activeModal = $target.closest(".modal-dialog");
|
||||
const parentComponentEl = $target.closest(".component");
|
||||
this.lastFocusedComponent = appContext.getComponentByEl(parentComponentEl[0]);
|
||||
this.#refreshTouchBar();
|
||||
});
|
||||
}
|
||||
|
||||
buildIcon(name: string) {
|
||||
const sourceImage = this.nativeImage.createFromNamedImage(name, [-1, 0, 1]);
|
||||
const { width, height } = sourceImage.getSize();
|
||||
const newImage = this.nativeImage.createEmpty();
|
||||
newImage.addRepresentation({
|
||||
scaleFactor: 1,
|
||||
width: width / 2,
|
||||
height: height / 2,
|
||||
buffer: sourceImage.resize({ height: height / 2 }).toBitmap()
|
||||
});
|
||||
newImage.addRepresentation({
|
||||
scaleFactor: 2,
|
||||
width: width,
|
||||
height: height,
|
||||
buffer: sourceImage.toBitmap()
|
||||
});
|
||||
return newImage;
|
||||
}
|
||||
|
||||
#refreshTouchBar() {
|
||||
const { TouchBar } = this.remote;
|
||||
const parentComponent = this.lastFocusedComponent;
|
||||
let touchBar = null;
|
||||
|
||||
if (this.$activeModal?.length) {
|
||||
touchBar = this.#buildModalTouchBar();
|
||||
} else if (parentComponent) {
|
||||
const items = parentComponent.triggerCommand("buildTouchBar", {
|
||||
TouchBar,
|
||||
buildIcon: this.buildIcon.bind(this)
|
||||
}) as unknown as TouchBarItem[];
|
||||
touchBar = this.#buildTouchBar(items);
|
||||
}
|
||||
|
||||
if (touchBar) {
|
||||
this.remote.getCurrentWindow().setTouchBar(touchBar);
|
||||
}
|
||||
}
|
||||
|
||||
#buildModalTouchBar() {
|
||||
const { TouchBar } = this.remote;
|
||||
const { TouchBarButton, TouchBarLabel, TouchBarSpacer } = this.remote.TouchBar;
|
||||
const items: TouchBarItem[] = [];
|
||||
|
||||
// Look for the modal title.
|
||||
const $title = this.$activeModal?.find(".modal-title");
|
||||
if ($title?.length) {
|
||||
items.push(new TouchBarLabel({ label: $title.text() }))
|
||||
}
|
||||
|
||||
items.push(new TouchBarSpacer({ size: "flexible" }));
|
||||
|
||||
// Look for buttons in the modal.
|
||||
const $buttons = this.$activeModal?.find(".modal-footer button");
|
||||
for (const button of $buttons ?? []) {
|
||||
items.push(new TouchBarButton({
|
||||
label: button.innerText,
|
||||
click: () => button.click(),
|
||||
enabled: !button.hasAttribute("disabled")
|
||||
}));
|
||||
}
|
||||
|
||||
items.push(new TouchBarSpacer({ size: "flexible" }));
|
||||
return new TouchBar({ items });
|
||||
}
|
||||
|
||||
#buildTouchBar(componentSpecificItems?: TouchBarItem[]) {
|
||||
const { TouchBar } = this.remote;
|
||||
const { TouchBarButton, TouchBarSpacer, TouchBarGroup, TouchBarSegmentedControl, TouchBarOtherItemsProxy } = this.remote.TouchBar;
|
||||
|
||||
// Disregard recursive calls or empty results.
|
||||
if (!componentSpecificItems || "then" in componentSpecificItems) {
|
||||
componentSpecificItems = [];
|
||||
}
|
||||
|
||||
const items = [
|
||||
new TouchBarButton({
|
||||
icon: this.buildIcon("NSTouchBarComposeTemplate"),
|
||||
click: () => this.triggerCommand("createNoteIntoInbox")
|
||||
}),
|
||||
new TouchBarSpacer({ size: "small" }),
|
||||
...componentSpecificItems,
|
||||
new TouchBarSpacer({ size: "flexible" }),
|
||||
new TouchBarOtherItemsProxy(),
|
||||
new TouchBarButton({
|
||||
icon: this.buildIcon("NSTouchBarAddDetailTemplate"),
|
||||
click: () => this.triggerCommand("jumpToNote")
|
||||
})
|
||||
].flat();
|
||||
|
||||
console.log("Update ", items);
|
||||
return new TouchBar({
|
||||
items
|
||||
});
|
||||
}
|
||||
|
||||
refreshTouchBarEvent() {
|
||||
this.#refreshTouchBar();
|
||||
}
|
||||
|
||||
}
|
||||
68
apps/client/src/components/zoom.ts
Normal file
68
apps/client/src/components/zoom.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import options from "../services/options.js";
|
||||
import Component from "./component.js";
|
||||
import utils from "../services/utils.js";
|
||||
|
||||
const MIN_ZOOM = 0.5;
|
||||
const MAX_ZOOM = 2.0;
|
||||
|
||||
class ZoomComponent extends Component {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
if (utils.isElectron()) {
|
||||
options.initializedPromise.then(() => {
|
||||
const zoomFactor = options.getFloat("zoomFactor");
|
||||
if (zoomFactor) {
|
||||
this.setZoomFactor(zoomFactor);
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener("wheel", (event) => {
|
||||
if (event.ctrlKey) {
|
||||
this.setZoomFactorAndSave(this.getCurrentZoom() - event.deltaY * 0.001);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setZoomFactor(zoomFactor: string | number) {
|
||||
const parsedZoomFactor = typeof zoomFactor !== "number" ? parseFloat(zoomFactor) : zoomFactor;
|
||||
const webFrame = utils.dynamicRequire("electron").webFrame;
|
||||
webFrame.setZoomFactor(parsedZoomFactor);
|
||||
}
|
||||
|
||||
async setZoomFactorAndSave(zoomFactor: number) {
|
||||
if (zoomFactor >= MIN_ZOOM && zoomFactor <= MAX_ZOOM) {
|
||||
zoomFactor = Math.round(zoomFactor * 10) / 10;
|
||||
|
||||
this.setZoomFactor(zoomFactor);
|
||||
|
||||
await options.save("zoomFactor", zoomFactor);
|
||||
} else {
|
||||
console.log(`Zoom factor ${zoomFactor} outside of the range, ignored.`);
|
||||
}
|
||||
}
|
||||
|
||||
getCurrentZoom() {
|
||||
return utils.dynamicRequire("electron").webFrame.getZoomFactor();
|
||||
}
|
||||
|
||||
zoomOutEvent() {
|
||||
this.setZoomFactorAndSave(this.getCurrentZoom() - 0.1);
|
||||
}
|
||||
|
||||
zoomInEvent() {
|
||||
this.setZoomFactorAndSave(this.getCurrentZoom() + 0.1);
|
||||
}
|
||||
zoomResetEvent() {
|
||||
this.setZoomFactorAndSave(1);
|
||||
}
|
||||
|
||||
setZoomFactorAndSaveEvent({ zoomFactor }: { zoomFactor: number }) {
|
||||
this.setZoomFactorAndSave(zoomFactor);
|
||||
}
|
||||
}
|
||||
|
||||
const zoomService = new ZoomComponent();
|
||||
|
||||
export default zoomService;
|
||||
Reference in New Issue
Block a user