Skip to content

Commit

Permalink
fix: Remove all references to global app instance
Browse files Browse the repository at this point in the history
  • Loading branch information
Zachatoo committed Oct 18, 2024
1 parent 5ec4310 commit 5580544
Show file tree
Hide file tree
Showing 22 changed files with 206 additions and 133 deletions.
75 changes: 42 additions & 33 deletions src/core/Templater.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
App,
MarkdownPostProcessorContext,
MarkdownView,
normalizePath,
Expand Down Expand Up @@ -63,7 +64,7 @@ export class Templater {
target_file: TFile,
run_mode: RunMode
): RunningConfig {
const active_file = get_active_file(app);
const active_file = get_active_file(this.plugin.app);

return {
template_file: template_file,
Expand All @@ -74,7 +75,7 @@ export class Templater {
}

async read_and_parse_template(config: RunningConfig): Promise<string> {
const template_content = await app.vault.read(
const template_content = await this.plugin.app.vault.read(
config.template_file as TFile
);
return this.parse_template(config, template_content);
Expand Down Expand Up @@ -103,7 +104,9 @@ export class Templater {
private async end_templater_task(path: string) {
this.files_with_pending_templates.delete(path);
if (this.files_with_pending_templates.size === 0) {
app.workspace.trigger("templater:all-templates-executed");
this.plugin.app.workspace.trigger(
"templater:all-templates-executed"
);
await this.functions_generator.teardown();
}
}
Expand All @@ -116,20 +119,21 @@ export class Templater {
): Promise<TFile | undefined> {
// TODO: Maybe there is an obsidian API function for that
if (!folder) {
const new_file_location = app.vault.getConfig("newFileLocation");
const new_file_location =
this.plugin.app.vault.getConfig("newFileLocation");
switch (new_file_location) {
case "current": {
const active_file = get_active_file(app);
const active_file = get_active_file(this.plugin.app);
if (active_file) {
folder = active_file.parent;
}
break;
}
case "folder":
folder = app.fileManager.getNewFileParent("");
folder = this.plugin.app.fileManager.getNewFileParent("");
break;
case "root":
folder = app.vault.getRoot();
folder = this.plugin.app.vault.getRoot();
break;
default:
break;
Expand All @@ -140,18 +144,20 @@ export class Templater {
template instanceof TFile ? template.extension || "md" : "md";
const created_note = await errorWrapper(async () => {
const folderPath = folder instanceof TFolder ? folder.path : folder;
const path = app.vault.getAvailablePath(
const path = this.plugin.app.vault.getAvailablePath(
normalizePath(`${folderPath ?? ""}/${filename || "Untitled"}`),
extension
);
const folder_path = get_folder_path_from_file_path(path);
if (
folder_path &&
!app.vault.getAbstractFileByPathInsensitive(folder_path)
!this.plugin.app.vault.getAbstractFileByPathInsensitive(
folder_path
)
) {
await app.vault.createFolder(folder_path);
await this.plugin.app.vault.createFolder(folder_path);
}
return app.vault.create(path, "");
return this.plugin.app.vault.create(path, "");
}, `Couldn't create ${extension} file.`);

if (created_note == null) {
Expand Down Expand Up @@ -185,20 +191,20 @@ export class Templater {
}

if (output_content == null) {
await app.vault.delete(created_note);
await this.plugin.app.vault.delete(created_note);
await this.end_templater_task(path);
return;
}

await app.vault.modify(created_note, output_content);
await this.plugin.app.vault.modify(created_note, output_content);

app.workspace.trigger("templater:new-note-from-template", {
this.plugin.app.workspace.trigger("templater:new-note-from-template", {
file: created_note,
content: output_content,
});

if (open_new_note) {
const active_leaf = app.workspace.getLeaf(false);
const active_leaf = this.plugin.app.workspace.getLeaf(false);
if (!active_leaf) {
log_error(new TemplaterError("No active leaf"));
return;
Expand All @@ -222,8 +228,9 @@ export class Templater {
}

async append_template_to_active_file(template_file: TFile): Promise<void> {
const active_view = app.workspace.getActiveViewOfType(MarkdownView);
const active_editor = app.workspace.activeEditor;
const active_view =
this.plugin.app.workspace.getActiveViewOfType(MarkdownView);
const active_editor = this.plugin.app.workspace.activeEditor;
if (!active_editor || !active_editor.file || !active_editor.editor) {
log_error(
new TemplaterError("No active editor, can't append templates.")
Expand Down Expand Up @@ -253,9 +260,9 @@ export class Templater {
doc.replaceSelection(output_content);
// Refresh editor to ensure properties widget shows after inserting template in blank file
if (active_editor.file) {
await app.vault.append(active_editor.file, "");
await this.plugin.app.vault.append(active_editor.file, "");
}
app.workspace.trigger("templater:template-appended", {
this.plugin.app.workspace.trigger("templater:template-appended", {
view: active_view,
editor: active_editor,
content: output_content,
Expand All @@ -276,8 +283,8 @@ export class Templater {
): Promise<void> {
const { path } = file;
this.start_templater_task(path);
const active_editor = app.workspace.activeEditor;
const active_file = get_active_file(app);
const active_editor = this.plugin.app.workspace.activeEditor;
const active_file = get_active_file(this.plugin.app);
const running_config = this.create_running_config(
template_file,
file,
Expand All @@ -292,7 +299,7 @@ export class Templater {
await this.end_templater_task(path);
return;
}
await app.vault.modify(file, output_content);
await this.plugin.app.vault.modify(file, output_content);
// Set cursor to first line of editor (below properties)
// https://github.com/SilentVoid13/Templater/issues/1231
if (
Expand All @@ -303,7 +310,7 @@ export class Templater {
const editor = active_editor.editor;
editor.setSelection({ line: 0, ch: 0 }, { line: 0, ch: 0 });
}
app.workspace.trigger("templater:new-note-from-template", {
this.plugin.app.workspace.trigger("templater:new-note-from-template", {
file,
content: output_content,
});
Expand All @@ -315,7 +322,7 @@ export class Templater {
}

overwrite_active_file_commands(): void {
const active_editor = app.workspace.activeEditor;
const active_editor = this.plugin.app.workspace.activeEditor;
if (!active_editor || !active_editor.file) {
log_error(
new TemplaterError(
Expand Down Expand Up @@ -347,8 +354,8 @@ export class Templater {
await this.end_templater_task(path);
return;
}
await app.vault.modify(file, output_content);
app.workspace.trigger("templater:overwrite-file", {
await this.plugin.app.vault.modify(file, output_content);
this.plugin.app.workspace.trigger("templater:overwrite-file", {
file,
content: output_content,
});
Expand All @@ -374,10 +381,11 @@ export class Templater {
if (content !== null) {
let match = dynamic_command_regex.exec(content);
if (match !== null) {
const file = app.metadataCache.getFirstLinkpathDest(
"",
ctx.sourcePath
);
const file =
this.plugin.app.metadataCache.getFirstLinkpathDest(
"",
ctx.sourcePath
);
if (!file || !(file instanceof TFile)) {
return;
}
Expand Down Expand Up @@ -456,6 +464,7 @@ export class Templater {

static async on_file_creation(
templater: Templater,
app: App,
file: TAbstractFile
): Promise<void> {
if (!(file instanceof TFile) || file.extension !== "md") {
Expand Down Expand Up @@ -490,7 +499,7 @@ export class Templater {
}
const template_file: TFile = await errorWrapper(
async (): Promise<TFile> => {
return resolve_tfile(folder_template_match);
return resolve_tfile(app, folder_template_match);
},
`Couldn't find template ${folder_template_match}`
);
Expand All @@ -510,7 +519,7 @@ export class Templater {
}
const template_file: TFile = await errorWrapper(
async (): Promise<TFile> => {
return resolve_tfile(file_template_match);
return resolve_tfile(app, file_template_match);
},
`Couldn't find template ${file_template_match}`
);
Expand All @@ -537,7 +546,7 @@ export class Templater {
continue;
}
const file = errorWrapperSync(
() => resolve_tfile(template),
() => resolve_tfile(this.plugin.app, template),
`Couldn't find startup template "${template}"`
);
if (!file) {
Expand Down
53 changes: 32 additions & 21 deletions src/core/functions/internal_functions/file/InternalModuleFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export class InternalModuleFile extends InternalModule {
async teardown(): Promise<void> {}

async generate_content(): Promise<string> {
return await app.vault.read(this.config.target_file);
return await this.plugin.app.vault.read(this.config.target_file);
}

generate_create_new(): (
Expand Down Expand Up @@ -108,7 +108,7 @@ export class InternalModuleFile extends InternalModule {

generate_cursor_append(): (content: string) => void {
return (content: string): string | undefined => {
const active_editor = app.workspace.activeEditor;
const active_editor = this.plugin.app.workspace.activeEditor;
if (!active_editor || !active_editor.editor) {
log_error(
new TemplaterError(
Expand All @@ -128,14 +128,14 @@ export class InternalModuleFile extends InternalModule {
generate_exists(): (filepath: string) => Promise<boolean> {
return async (filepath: string) => {
const path = normalizePath(filepath);
return await app.vault.exists(path);
return await this.plugin.app.vault.exists(path);
};
}

generate_find_tfile(): (filename: string) => TFile | null {
return (filename: string) => {
const path = normalizePath(filename);
return app.metadataCache.getFirstLinkpathDest(path, "");
return this.plugin.app.metadataCache.getFirstLinkpathDest(path, "");
};
}

Expand Down Expand Up @@ -169,7 +169,9 @@ export class InternalModuleFile extends InternalModule {
let inc_file_content: string;

if (include_link instanceof TFile) {
inc_file_content = await app.vault.read(include_link);
inc_file_content = await this.plugin.app.vault.read(
include_link
);
} else {
let match;
if ((match = this.linkpath_regex.exec(include_link)) === null) {
Expand All @@ -180,20 +182,22 @@ export class InternalModuleFile extends InternalModule {
}
const { path, subpath } = parseLinktext(match[1]);

const inc_file = app.metadataCache.getFirstLinkpathDest(
path,
""
);
const inc_file =
this.plugin.app.metadataCache.getFirstLinkpathDest(
path,
""
);
if (!inc_file) {
this.include_depth -= 1;
throw new TemplaterError(
`File ${include_link} doesn't exist`
);
}
inc_file_content = await app.vault.read(inc_file);
inc_file_content = await this.plugin.app.vault.read(inc_file);

if (subpath) {
const cache = app.metadataCache.getFileCache(inc_file);
const cache =
this.plugin.app.metadataCache.getFileCache(inc_file);
if (cache) {
const result = resolveSubpath(cache, subpath);
if (result) {
Expand Down Expand Up @@ -235,11 +239,11 @@ export class InternalModuleFile extends InternalModule {
dirs.pop(); // remove basename
if (dirs.length) {
const dir = dirs.join("/");
if (!window.app.vault.getAbstractFileByPath(dir)) {
await window.app.vault.createFolder(dir);
if (!this.plugin.app.vault.getAbstractFileByPath(dir)) {
await this.plugin.app.vault.createFolder(dir);
}
}
await app.fileManager.renameFile(file, new_path);
await this.plugin.app.fileManager.renameFile(file, new_path);
return "";
};
}
Expand All @@ -248,12 +252,14 @@ export class InternalModuleFile extends InternalModule {
return (relative = false) => {
let vault_path = "";
if (Platform.isMobileApp) {
const vault_adapter = app.vault.adapter.fs.uri;
const vault_base = app.vault.adapter.basePath;
const vault_adapter = this.plugin.app.vault.adapter.fs.uri;
const vault_base = this.plugin.app.vault.adapter.basePath;
vault_path = `${vault_adapter}/${vault_base}`;
} else {
if (app.vault.adapter instanceof FileSystemAdapter) {
vault_path = app.vault.adapter.getBasePath();
if (
this.plugin.app.vault.adapter instanceof FileSystemAdapter
) {
vault_path = this.plugin.app.vault.adapter.getBasePath();
} else {
throw new TemplaterError(
"app.vault is not a FileSystemAdapter instance"
Expand All @@ -279,14 +285,17 @@ export class InternalModuleFile extends InternalModule {
const new_path = normalizePath(
`${this.config.target_file.parent.path}/${new_title}.${this.config.target_file.extension}`
);
await app.fileManager.renameFile(this.config.target_file, new_path);
await this.plugin.app.fileManager.renameFile(
this.config.target_file,
new_path
);
return "";
};
}

generate_selection(): () => string {
return () => {
const active_editor = app.workspace.activeEditor;
const active_editor = this.plugin.app.workspace.activeEditor;
if (!active_editor || !active_editor.editor) {
throw new TemplaterError(
"Active editor is null, can't read selection."
Expand All @@ -300,7 +309,9 @@ export class InternalModuleFile extends InternalModule {

// TODO: Turn this into a function
generate_tags(): string[] | null {
const cache = app.metadataCache.getFileCache(this.config.target_file);
const cache = this.plugin.app.metadataCache.getFileCache(
this.config.target_file
);

if (cache) {
return getAllTags(cache);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ export class InternalModuleFrontmatter extends InternalModule {
async create_static_templates(): Promise<void> {}

async create_dynamic_templates(): Promise<void> {
const cache = app.metadataCache.getFileCache(this.config.target_file);
const cache = this.plugin.app.metadataCache.getFileCache(
this.config.target_file
);
this.dynamic_functions = new Map(
Object.entries(cache?.frontmatter || {})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class InternalModuleHooks extends InternalModule {
callback_function: () => unknown
) => void {
return (callback_function) => {
const event_ref = app.workspace.on(
const event_ref = this.plugin.app.workspace.on(
"templater:all-templates-executed",
async () => {
await delay(1);
Expand Down
Loading

0 comments on commit 5580544

Please sign in to comment.