Skip to content

Commit

Permalink
refactor: use obsidian's event system
Browse files Browse the repository at this point in the history
  • Loading branch information
Vinzent03 committed Oct 9, 2024
1 parent 16716b0 commit 4ae564b
Show file tree
Hide file tree
Showing 9 changed files with 99 additions and 64 deletions.
6 changes: 3 additions & 3 deletions src/gitManager/simpleGit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ export class SimpleGit extends GitManager {
await this.formatCommitMessage(message),
(err) => this.onError(err)
);
dispatchEvent(new CustomEvent("git-head-update"));
this.app.workspace.trigger("obsidian-git:head-change");

return res.summary.changes;
}
Expand All @@ -325,7 +325,7 @@ export class SimpleGit extends GitManager {
(err) => this.onError(err)
)
).summary.changes;
dispatchEvent(new CustomEvent("git-head-update"));
this.app.workspace.trigger("obsidian-git:head-change");

this.plugin.setState(PluginState.idle);
return res;
Expand Down Expand Up @@ -466,7 +466,7 @@ export class SimpleGit extends GitManager {
);
}
}
dispatchEvent(new CustomEvent("git-head-update"));
this.app.workspace.trigger("obsidian-git:head-change");

const afterMergeCommit = await this.git.revparse(
[branchInfo.current!],
Expand Down
62 changes: 32 additions & 30 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import { IsomorphicGit } from "./gitManager/isomorphicGit";
import { SimpleGit } from "./gitManager/simpleGit";
import { LocalStorageSettings } from "./setting/localStorageSettings";
import type {
DiffViewState,
FileStatusResult,
ObsidianGitSettings,
Status,
Expand Down Expand Up @@ -64,7 +63,7 @@ export default class ObsidianGit extends Plugin {
lastPulledFiles: FileStatusResult[];
gitReady = false;
promiseQueue: PromiseQueue = new PromiseQueue();
autoCommitDebouncer: Debouncer<any, void> | undefined;
autoCommitDebouncer: Debouncer<[], void> | undefined;
offlineMode = false;
loading = false;
cachedStatus: Status | undefined;
Expand All @@ -77,7 +76,7 @@ export default class ObsidianGit extends Plugin {
renameEvent: EventRef;
lineAuthoringFeature: LineAuthoringFeature = new LineAuthoringFeature(this);

debRefresh: Debouncer<any, void>;
debRefresh: Debouncer<[], void>;

setState(state: PluginState): void {
this.state = state;
Expand Down Expand Up @@ -105,19 +104,19 @@ export default class ObsidianGit extends Plugin {
historyView.length > 0
) {
this.loading = true;
dispatchEvent(new CustomEvent("git-view-refresh"));
this.app.workspace.trigger("obsidian-git:view-refresh");

await this.updateCachedStatus();
this.loading = false;
dispatchEvent(new CustomEvent("git-view-refresh"));
this.app.workspace.trigger("obsidian-git:view-refresh");
}

// We don't put a line authoring refresh here, as it would force a re-loading
// of the line authoring feature - which would lead to a jumpy editor-view in the
// ui after every rename event.
}

async refreshUpdatedHead() {
refreshUpdatedHead() {
this.lineAuthoringFeature.refreshLineAuthorViews();
}

Expand All @@ -135,7 +134,7 @@ export default class ObsidianGit extends Plugin {

this.localStorage.migrate();
await this.loadSettings();
this.migrateSettings();
await this.migrateSettings();

this.settingsTab = new ObsidianGitSettingsTab(this.app, this);
this.addSettingTab(this.settingsTab);
Expand All @@ -145,9 +144,17 @@ export default class ObsidianGit extends Plugin {
}
}

async loadPlugin() {
addEventListener("git-refresh", this.refresh.bind(this));
addEventListener("git-head-update", this.refreshUpdatedHead.bind(this));
loadPlugin() {
this.registerEvent(
this.app.workspace.on("obsidian-git:refresh", () => {
this.refresh().catch((e) => this.displayError(e));
})
);
this.registerEvent(
this.app.workspace.on("obsidian-git:head-change", () => {
this.refreshUpdatedHead();
})
);

this.registerView(SOURCE_CONTROL_VIEW_CONFIG.type, (leaf) => {
return new GitView(leaf, this);
Expand Down Expand Up @@ -178,9 +185,9 @@ export default class ObsidianGit extends Plugin {
} else {
leaf = leafs.first()!;
}
this.app.workspace.revealLeaf(leaf);
await this.app.workspace.revealLeaf(leaf);

dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");
}
);

Expand Down Expand Up @@ -339,15 +346,10 @@ export default class ObsidianGit extends Plugin {

unloadPlugin() {
this.gitReady = false;
dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");

this.lineAuthoringFeature.deactivateFeature();
this.automaticsManager.unload();
removeEventListener("git-refresh", this.refresh.bind(this));
removeEventListener(
"git-head-update",
this.refreshUpdatedHead.bind(this)
);
this.app.workspace.offref(this.openEvent);
this.app.metadataCache.offref(this.modifyEvent);
this.app.metadataCache.offref(this.deleteEvent);
Expand All @@ -356,7 +358,7 @@ export default class ObsidianGit extends Plugin {
this.debRefresh.cancel();
}

async onunload() {
onunload() {
(this.app.workspace as any).unregisterHoverLinkSource(
SOURCE_CONTROL_VIEW_CONFIG.type
);
Expand Down Expand Up @@ -442,7 +444,7 @@ export default class ObsidianGit extends Plugin {

this.lineAuthoringFeature.conditionallyActivateBySettings();

dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");

if (this.settings.autoPullOnBoot) {
this.promiseQueue.addTask(() =>
Expand Down Expand Up @@ -600,7 +602,7 @@ export default class ObsidianGit extends Plugin {
}
}

dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");
this.setState(PluginState.idle);
}

Expand Down Expand Up @@ -789,7 +791,7 @@ export default class ObsidianGit extends Plugin {
} else {
this.displayMessage("No changes to commit");
}
dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");

this.setState(PluginState.idle);
return true;
Expand Down Expand Up @@ -839,7 +841,7 @@ export default class ObsidianGit extends Plugin {
}
this.offlineMode = false;
this.setState(PluginState.idle);
dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");

return true;
}
Expand Down Expand Up @@ -874,7 +876,7 @@ export default class ObsidianGit extends Plugin {

this.displayMessage(`Fetched from remote`);
this.offlineMode = false;
dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");
}

async mayDeleteConflictFile(): Promise<void> {
Expand All @@ -898,7 +900,7 @@ export default class ObsidianGit extends Plugin {
await this.gitManager.stage(file.path, true);
this.displayMessage(`Staged ${file.path}`);

dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");

this.setState(PluginState.idle);
return true;
Expand All @@ -910,7 +912,7 @@ export default class ObsidianGit extends Plugin {
await this.gitManager.unstage(file.path, true);
this.displayMessage(`Unstaged ${file.path}`);

dispatchEvent(new CustomEvent("git-refresh"));
this.app.workspace.trigger("obsidian-git:refresh");

this.setState(PluginState.idle);
return true;
Expand Down Expand Up @@ -1210,19 +1212,19 @@ I strongly recommend to use "Source mode" for viewing the conflicted files. For
this.log(message);
}

displayError(message: any, timeout: number = 10 * 1000): void {
if (message instanceof Errors.UserCanceledError) {
displayError(data: unknown, timeout: number = 10 * 1000): void {
if (data instanceof Errors.UserCanceledError) {
new Notice("Aborted");
return;
}
// Some errors might not be of type string
message = message.toString();
const message = String(data);
new Notice(message, timeout);
this.log(`error: ${message}`);
this.statusBar?.displayMessage(message.toLowerCase(), timeout);
}

log(...data: any[]) {
log(...data: unknown[]) {
console.log(`${this.manifest.id}:`, ...data);
}
}
22 changes: 22 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,4 +277,26 @@ declare module "obsidian" {
interface View {
titleEl: HTMLElement;
}
interface Workspace {
on(
name: "obsidian-git:refresh",
callback: () => void,
ctx?: unknown
): EventRef;
on(
name: "obsidian-git:view-refresh",
callback: () => void,
ctx?: unknown
): EventRef;
on(
name: "obsidian-git:head-change",
callback: () => void,
ctx?: unknown
): EventRef;

trigger(name: string, ...data: unknown[]): void;
trigger(name: "obsidian-git:refresh"): void;
trigger(name: "obsidian-git:view-refresh"): void;
trigger(name: "obsidian-git:head-change"): void;
}
}
28 changes: 19 additions & 9 deletions src/ui/diff/diffView.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { html } from "diff2html";
import type { ViewStateResult, WorkspaceLeaf } from "obsidian";
import type { EventRef, ViewStateResult, WorkspaceLeaf } from "obsidian";
import { ItemView, Platform } from "obsidian";
import { DIFF_VIEW_CONFIG } from "src/constants";
import { SimpleGit } from "src/gitManager/simpleGit";
Expand All @@ -10,8 +10,8 @@ export default class DiffView extends ItemView {
parser: DOMParser;
gettingDiff = false;
state: DiffViewState;
gitRefreshBind = this.refresh.bind(this);
gitViewRefreshBind = this.refresh.bind(this);
gitRefreshRef: EventRef;
gitViewRefreshRef: EventRef;

constructor(
leaf: WorkspaceLeaf,
Expand All @@ -20,8 +20,18 @@ export default class DiffView extends ItemView {
super(leaf);
this.parser = new DOMParser();
this.navigation = true;
addEventListener("git-refresh", this.gitRefreshBind);
addEventListener("git-view-refresh", this.gitViewRefreshBind);
this.gitRefreshRef = this.app.workspace.on(
"obsidian-git:refresh",
() => {
this.refresh().catch(console.error);
}
);
this.gitViewRefreshRef = this.app.workspace.on(
"obsidian-git:view-refresh",
() => {
this.refresh().catch(console.error);
}
);
}

getViewType(): string {
Expand Down Expand Up @@ -58,13 +68,13 @@ export default class DiffView extends ItemView {
}

onClose(): Promise<void> {
removeEventListener("git-refresh", this.gitRefreshBind);
removeEventListener("git-view-refresh", this.gitViewRefreshBind);
this.app.workspace.offref(this.gitRefreshRef);
this.app.workspace.offref(this.gitViewRefreshRef);
return super.onClose();
}

onOpen(): Promise<void> {
this.refresh();
async onOpen(): Promise<void> {
await this.refresh();
return super.onOpen();
}

Expand Down
9 changes: 5 additions & 4 deletions src/ui/history/historyView.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script lang="ts">
import { setIcon } from "obsidian";
import { setIcon, type EventRef } from "obsidian";
import { SimpleGit } from "src/gitManager/simpleGit";
import type ObsidianGit from "src/main";
import type { LogEntry } from "src/types";
Expand All @@ -13,6 +13,7 @@
let buttons: HTMLElement[] = [];
let logs: LogEntry[] | undefined;
let showTree: boolean = plugin.settings.treeStructure;
let refreshRef: EventRef;
let layoutBtn: HTMLElement;
$: {
Expand All @@ -21,7 +22,7 @@
setIcon(layoutBtn, showTree ? "list" : "folder");
}
}
addEventListener("git-view-refresh", refresh);
refreshRef = view.app.workspace.on("obsidian-git:view-refresh", refresh);
refresh();
//This should go in the onMount callback, for some reason it doesn't fire though
//setTimeout's callback will execute after the current event loop finishes.
Expand All @@ -32,11 +33,11 @@
}, 0);
});
onDestroy(() => {
removeEventListener("git-view-refresh", refresh);
view.app.workspace.offref(refreshRef);
});
function triggerRefresh() {
dispatchEvent(new CustomEvent("git-refresh"));
view.app.workspace.trigger("obsidian-git:refresh");
}
async function refresh() {
Expand Down
8 changes: 5 additions & 3 deletions src/ui/sourceControl/components/fileComponent.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
function stage() {
manager.stage(change.path, false).finally(() => {
dispatchEvent(new CustomEvent("git-refresh"));
view.app.workspace.trigger("obsidian-git:refresh");
});
}
Expand All @@ -61,11 +61,13 @@
view.app.vault.adapter
.remove(change.vault_path)
.finally(() => {
dispatchEvent(new CustomEvent("git-refresh"));
view.app.workspace.trigger(
"obsidian-git:refresh"
);
});
} else {
manager.discard(change.path).finally(() => {
dispatchEvent(new CustomEvent("git-refresh"));
view.app.workspace.trigger("obsidian-git:refresh");
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/ui/sourceControl/components/stagedFileComponent.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
function unstage() {
manager.unstage(change.path, false).finally(() => {
dispatchEvent(new CustomEvent("git-refresh"));
view.app.workspace.trigger("obsidian-git:refresh");
});
}
</script>
Expand Down
Loading

0 comments on commit 4ae564b

Please sign in to comment.