obsidian#TAbstractFile TypeScript Examples
The following examples show how to use
obsidian#TAbstractFile.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utility.ts From quickadd with MIT License | 7 votes |
// Slightly modified version of Templater's user script import implementation
// Source: https://github.com/SilentVoid13/Templater
export async function getUserScript(command: IUserScript, app: App) {
// @ts-ignore
const file: TAbstractFile = app.vault.getAbstractFileByPath(command.path);
if (!file) {
log.logError(`failed to load file ${command.path}.`);
return;
}
if (file instanceof TFile) {
let req = (s: string) => window.require && window.require(s);
let exp: Record<string, unknown> = {};
let mod = { exports: exp };
const fileContent = await app.vault.read(file);
const fn = window.eval(`(function(require, module, exports) { ${fileContent} \n})`);
fn(req, mod, exp);
// @ts-ignore
const userScript = exp['default'] || mod.exports;
if (!userScript) return;
let script = userScript;
const {memberAccess} = getUserScriptMemberAccess(command.name);
if (memberAccess && memberAccess.length > 0) {
let member: string;
while(member = memberAccess.shift()) {
script = script[member];
}
}
return script;
}
}
Example #2
Source File: main.ts From obsidian-consistent-attachments-and-links with MIT License | 6 votes |
async handleDeletedFile(file: TAbstractFile) {
if (this.isPathIgnored(file.path))
return;
let fileExt = file.path.substring(file.path.lastIndexOf("."));
if (fileExt == ".md") {
if (this.settings.deleteAttachmentsWithNote) {
await this.fh.deleteUnusedAttachmentsForCachedNote(file.path);
}
//delete child folders (do not delete parent)
if (this.settings.deleteEmptyFolders) {
if (await this.app.vault.adapter.exists(path.dirname(file.path))) {
let list = await this.app.vault.adapter.list(path.dirname(file.path));
for (let folder of list.folders) {
await this.fh.deleteEmptyFolders(folder);
}
}
}
}
}
Example #3
Source File: headingsHandler.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
private shouldIncludeFile(file: TAbstractFile): boolean {
let retVal = false;
const {
settings: {
builtInSystemOptions: { showAttachments, showAllFileTypes },
},
app: { viewRegistry },
} = this;
if (isTFile(file)) {
const { extension } = file;
retVal = viewRegistry.isExtensionRegistered(extension)
? showAttachments || extension === 'md'
: showAllFileTypes;
}
return retVal;
}
Example #4
Source File: headingsHandler.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
getAllFilesSuggestions(prepQuery: PreparedQuery): SupportedSuggestionTypes[] {
const suggestions: SupportedSuggestionTypes[] = [];
const {
app: { vault },
settings: { strictHeadingsOnly, showExistingOnly, excludeFolders },
} = this;
const isExcludedFolder = matcherFnForRegExList(excludeFolders);
let nodes: TAbstractFile[] = [vault.getRoot()];
while (nodes.length > 0) {
const node = nodes.pop();
if (isTFile(node)) {
this.addSuggestionsFromFile(suggestions, node, prepQuery);
} else if (!isExcludedFolder(node.path)) {
nodes = nodes.concat((node as TFolder).children);
}
}
if (!strictHeadingsOnly && !showExistingOnly) {
this.addUnresolvedSuggestions(suggestions as UnresolvedSuggestion[], prepQuery);
}
return suggestions;
}
Example #5
Source File: relatedItemsHandler.test.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
function makeFileTree(sourceFile: TFile): TFolder {
const mockFolder = jest.fn<
TFolder,
[name: string, path: string, children: Array<TAbstractFile>]
>((name, path, children = []) => {
return {
vault: null,
parent: null,
isRoot: undefined,
name,
path,
children,
};
});
const root = new mockFolder('', '/', [
file1,
sourceFile,
file2,
new mockFolder('l1Folder1', 'l1Folder1', [
file3,
new mockFolder('l2Folder1', 'l1Folder1/l2Folder1', [file4]),
]),
]);
return root;
}
Example #6
Source File: headingshandler.test.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
function makeFileTree(expectedFile: TFile, parentFolderName = 'l2Folder2'): TFolder {
const mockFolder = jest.fn<
TFolder,
[name: string, path: string, children: Array<TAbstractFile>]
>((name, path, children = []) => {
return {
vault: null,
parent: null,
isRoot: undefined,
name,
path,
children,
};
});
const root = new mockFolder('', '/', [
new TFile(),
new mockFolder('l1Folder1', 'l1Folder1', [
new TFile(),
new mockFolder('l2Folder1', 'l1Folder1/l2Folder1', [new TFile()]),
new mockFolder(parentFolderName, `l1Folder1/${parentFolderName}`, [expectedFile]),
]),
]);
return root;
}
Example #7
Source File: TemplateEngine.ts From quickadd with MIT License | 6 votes |
protected async getTemplateContent(templatePath: string): Promise<string> {
let correctTemplatePath: string = templatePath;
if (!MARKDOWN_FILE_EXTENSION_REGEX.test(templatePath))
correctTemplatePath += ".md";
const templateFile: TAbstractFile = this.app.vault.getAbstractFileByPath(correctTemplatePath);
if (!(templateFile instanceof TFile)) return;
return await this.app.vault.cachedRead(templateFile);
}
Example #8
Source File: QuickAddEngine.ts From quickadd with MIT License | 6 votes |
protected async getFileByPath(filePath: string): Promise<TFile> {
const file: TAbstractFile = await this.app.vault.getAbstractFileByPath(filePath);
if (!file) {
log.logError(`${filePath} not found`);
return null;
}
if (file instanceof TFolder) {
log.logError(`${filePath} found but it's a folder`);
return null;
}
if (file instanceof TFile)
return file;
}
Example #9
Source File: index.ts From obsidian-dataview with MIT License | 6 votes |
public rename(file: TAbstractFile, oldPath: string) {
if (!(file instanceof TFile) || !PathFilters.markdown(file.path)) return;
if (this.pages.has(oldPath)) {
const oldMeta = this.pages.get(oldPath);
this.pages.delete(oldPath);
if (oldMeta) {
oldMeta.path = file.path;
this.pages.set(file.path, oldMeta);
}
}
this.tags.rename(oldPath, file.path);
this.links.rename(oldPath, file.path);
this.etags.rename(oldPath, file.path);
this.touch();
this.trigger("rename", file, oldPath);
}
Example #10
Source File: vault-handler.ts From folder-note-core with MIT License | 6 votes |
onDelete = (af: TAbstractFile) => {
const { getFolderNote, getFolderFromNote } = this.finder;
if (af instanceof TFolder) {
const oldNote = getFolderNote(af);
if (!(this.settings.folderNotePref === NoteLoc.Outside && oldNote))
return;
if (this.settings.deleteOutsideNoteWithFolder) {
this.delete(oldNote);
} else this.plugin.trigger("folder-note:delete", oldNote, af);
} else if (af instanceof TFile && isMd(af)) {
const oldFolder = getFolderFromNote(af);
if (oldFolder) this.plugin.trigger("folder-note:delete", af, oldFolder);
}
};
Example #11
Source File: relatedItemsHandler.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
getRelatedFiles(sourceFile: TFile): TFile[] {
const relatedFiles: TFile[] = [];
const { excludeRelatedFolders, excludeOpenRelatedFiles } = this.settings;
const isExcludedFolder = matcherFnForRegExList(excludeRelatedFolders);
let nodes: TAbstractFile[] = [...sourceFile.parent.children];
while (nodes.length > 0) {
const node = nodes.pop();
if (isTFile(node)) {
const isSourceFile = node === sourceFile;
const isExcluded =
isSourceFile || (excludeOpenRelatedFiles && !!this.findOpenEditor(node).leaf);
if (!isExcluded) {
relatedFiles.push(node);
}
} else if (!isExcludedFolder(node.path)) {
nodes = nodes.concat((node as TFolder).children);
}
}
return relatedFiles;
}
Example #12
Source File: vault-handler.ts From folder-note-core with MIT License | 6 votes |
private shouldRename(af: TAbstractFile, oldPath?: string): oldPath is string {
if (!this.settings.autoRename || !oldPath) return false;
const renameOnly =
this.settings.folderNotePref !== NoteLoc.Index &&
dirname(af.path) === dirname(oldPath) // rename only, same loc
? true
: false;
// sync loc is enabled in folder renames only
const syncLoc =
af instanceof TFolder &&
this.settings.folderNotePref === NoteLoc.Outside &&
dirname(af.path) !== dirname(oldPath)
? true
: false;
return renameOnly || syncLoc;
}
Example #13
Source File: misc.ts From folder-note-core with MIT License | 6 votes |
afOp = (
target: TAbstractFile,
fileOp: (file: TFile) => void,
folderOp: (folder: TFolder) => void,
) => {
if (target instanceof TFile) {
fileOp(target);
} else if (target instanceof TFolder) {
folderOp(target);
} else {
log.error("unexpected TAbstractFile type", target);
throw new Error("unexpected TAbstractFile type");
}
}
Example #14
Source File: mapView.ts From obsidian-map-view with GNU General Public License v3.0 | 6 votes |
/**
* Update the map markers with a list of markers not from the removed file plus the markers from the new file.
* Run when a file is deleted, renamed or changed.
* @param fileRemoved The old file path
* @param fileAddedOrChanged The new file data
*/
private async updateMarkersWithRelationToFile(
fileRemoved: string,
fileAddedOrChanged: TAbstractFile,
skipMetadata: boolean
) {
if (!this.display.map || !this.isOpen)
// If the map has not been set up yet then do nothing
return;
let newMarkers: FileMarker[] = [];
// Create an array of all file markers not in the removed file
for (let [markerId, fileMarker] of this.display.markers) {
if (fileMarker.file.path !== fileRemoved)
newMarkers.push(fileMarker);
}
if (fileAddedOrChanged && fileAddedOrChanged instanceof TFile)
// Add file markers from the added file
await buildAndAppendFileMarkers(
newMarkers,
fileAddedOrChanged,
this.settings,
this.app
);
finalizeMarkers(newMarkers, this.settings);
this.updateMapMarkers(newMarkers);
}
Example #15
Source File: folder-mark.ts From alx-folder-note with MIT License | 6 votes |
markFolderNote = (af: TAbstractFile): boolean => {
if (af instanceof TFolder && af.isRoot()) return false;
const { getFolderNote, getFolderFromNote } = this.fncApi;
let found: TAbstractFile | null = null;
if (af instanceof TFile) found = getFolderFromNote(af);
else if (af instanceof TFolder) found = getFolderNote(af);
if (found) {
this.setMark(found);
this.setMark(af);
} else {
this.setMark(af, true);
}
return !!found;
};
Example #16
Source File: folder-mark.ts From alx-folder-note with MIT License | 6 votes |
//#region set class mark for folder notes and folders
public setMark = (
target: AFItem | TAbstractFile | string,
revert = false,
) => {
if (!target) return;
const { queue } = this.queues.mark;
let path: string;
if (target instanceof TAbstractFile) {
path = target.path;
} else if (typeof target === "string") {
path = target;
} else {
path = target.file.path;
}
queue.set(path, [revert]);
this.execQueue("mark");
};
Example #17
Source File: main.ts From obsidian-linter with MIT License | 6 votes |
onMenuOpenCallback(menu: Menu, file: TAbstractFile, source: string) {
if (file instanceof TFile && file.extension === 'md') {
menu.addItem((item) => {
item.setIcon('wrench-screwdriver-glyph');
item.setTitle('Lint file');
item.onClick(async (evt) => {
this.runLinterFile(file);
});
});
}
}
Example #18
Source File: Utils.ts From Templater with GNU Affero General Public License v3.0 | 6 votes |
export function get_tfiles_from_folder(
app: App,
folder_str: string
): Array<TFile> {
const folder = resolve_tfolder(app, folder_str);
const files: Array<TFile> = [];
Vault.recurseChildren(folder, (file: TAbstractFile) => {
if (file instanceof TFile) {
files.push(file);
}
});
files.sort((a, b) => {
return a.basename.localeCompare(b.basename);
});
return files;
}
Example #19
Source File: FolderSuggester.ts From Templater with GNU Affero General Public License v3.0 | 6 votes |
getSuggestions(inputStr: string): TFolder[] {
const abstractFiles = this.app.vault.getAllLoadedFiles();
const folders: TFolder[] = [];
const lowerCaseInputStr = inputStr.toLowerCase();
abstractFiles.forEach((folder: TAbstractFile) => {
if (
folder instanceof TFolder &&
folder.path.toLowerCase().contains(lowerCaseInputStr)
) {
folders.push(folder);
}
});
return folders;
}
Example #20
Source File: FileSuggester.ts From Templater with GNU Affero General Public License v3.0 | 6 votes |
getSuggestions(input_str: string): TFile[] {
const all_files = errorWrapperSync(
() => get_tfiles_from_folder(this.app, this.get_folder(this.mode)),
this.get_error_msg(this.mode)
);
if (!all_files) {
return [];
}
const files: TFile[] = [];
const lower_input_str = input_str.toLowerCase();
all_files.forEach((file: TAbstractFile) => {
if (
file instanceof TFile &&
file.extension === "md" &&
file.path.toLowerCase().contains(lower_input_str)
) {
files.push(file);
}
});
return files;
}
Example #21
Source File: EventHandler.ts From Templater with GNU Affero General Public License v3.0 | 6 votes |
update_trigger_file_on_creation(): void {
if (this.settings.trigger_on_file_creation) {
this.trigger_on_file_creation_event = this.app.vault.on(
"create",
(file: TAbstractFile) =>
Templater.on_file_creation(this.templater, file)
);
this.plugin.registerEvent(this.trigger_on_file_creation_event);
} else {
if (this.trigger_on_file_creation_event) {
this.app.vault.offref(this.trigger_on_file_creation_event);
this.trigger_on_file_creation_event = undefined;
}
}
}
Example #22
Source File: files-manager.ts From Obsidian_to_Anki with GNU General Public License v3.0 | 6 votes |
getFolderPathList(file: TFile): TFolder[] {
let result: TFolder[] = []
let abstractFile: TAbstractFile = file
while (abstractFile.hasOwnProperty('parent')) {
result.push(abstractFile.parent)
abstractFile = abstractFile.parent
}
result.pop() // Removes top-level vault
return result
}
Example #23
Source File: main.ts From obsidian-custom-attachment-location with GNU General Public License v3.0 | 5 votes |
async handleRename(newFile: TFile, oldFilePath: string){
console.log('Handle Rename');
//if autoRename is off or not a markdown file
if(!this.settings.autoRenameFolder || newFile.extension !== 'md')
return;
let newName = newFile.basename;
let oldName = Path.basename(oldFilePath, '.md');
let mdFolderPath: string = Path.dirname(newFile.path);
let oldMdFolderPath: string = Path.dirname(oldFilePath);
let oldAttachmentFolderPath: string = this.getAttachmentFolderFullPath(oldMdFolderPath, oldName);
let newAttachmentFolderPath: string = this.getAttachmentFolderFullPath(mdFolderPath, newName);
//check if old attachment folder exists and is necessary to rename Folder
if(await this.adapter.exists(oldAttachmentFolderPath) && (oldAttachmentFolderPath !== newAttachmentFolderPath))
{
let tfolder: TAbstractFile = this.app.vault.getAbstractFileByPath(oldAttachmentFolderPath);
if(tfolder == null)
return;
let newAttachmentParentFolderPath: string = Path.dirname(newAttachmentFolderPath)
if (!(await this.adapter.exists(newAttachmentParentFolderPath))) {
await this.app.vault.createFolder(newAttachmentParentFolderPath);
}
await this.app.fileManager.renameFile(tfolder, newAttachmentFolderPath);
let oldAttachmentParentFolderPath: string = Path.dirname(oldAttachmentFolderPath)
let oldAttachmentParentFolderList: ListedFiles = await this.adapter.list(oldAttachmentParentFolderPath);
if (oldAttachmentParentFolderList.folders.length === 0 && oldAttachmentParentFolderList.files.length === 0) {
await this.adapter.rmdir(oldAttachmentParentFolderPath, true);
}
this.updateAttachmentFolderConfig(this.getAttachmentFolderPath(newName));
}
//if autoRenameFiles is off
if(!this.settings.autoRenameFiles)
return;
let embeds = this.app.metadataCache.getCache(newFile.path)?.embeds;
if(!embeds)
return;
let files: string[] = [];
for(let embed of embeds)
{
let link = embed.link;
if(link.endsWith('.png') || link.endsWith('jpeg'))
files.push(Path.basename(link));
else
continue;
}
let attachmentFiles: ListedFiles= await this.adapter.list(newAttachmentFolderPath);
for(let file of attachmentFiles.files)
{
console.log(file);
let filePath = file;
let fileName = Path.basename(filePath);
if((files.indexOf(fileName) > -1) && fileName.contains(oldName))
{
fileName = fileName.replace(oldName, newName);
let newFilePath = normalizePath(Path.join(newAttachmentFolderPath, fileName));
let tfile = this.app.vault.getAbstractFileByPath(filePath);
await this.app.fileManager.renameFile(tfile, newFilePath);
}
else
continue;
}
}
Example #24
Source File: main.ts From obsidian-consistent-attachments-and-links with MIT License | 5 votes |
async handleRenamedFile(file: TAbstractFile, oldPath: string) {
this.recentlyRenamedFiles.push({ oldPath: oldPath, newPath: file.path });
clearTimeout(this.timerId);
this.timerId = setTimeout(() => { this.HandleRecentlyRenamedFiles() }, 3000);
}
Example #25
Source File: localdb.ts From remotely-save with Apache License 2.0 | 5 votes |
insertDeleteRecordByVault = async (
db: InternalDBs,
fileOrFolder: TAbstractFile,
vaultRandomID: string
) => {
// log.info(fileOrFolder);
let k: FileFolderHistoryRecord;
if (fileOrFolder instanceof TFile) {
k = {
key: fileOrFolder.path,
ctime: fileOrFolder.stat.ctime,
mtime: fileOrFolder.stat.mtime,
size: fileOrFolder.stat.size,
actionWhen: Date.now(),
actionType: "delete",
keyType: "file",
renameTo: "",
vaultRandomID: vaultRandomID,
};
} else if (fileOrFolder instanceof TFolder) {
// key should endswith "/"
const key = fileOrFolder.path.endsWith("/")
? fileOrFolder.path
: `${fileOrFolder.path}/`;
const ctime = 0; // they are deleted, so no way to get ctime, mtime
const mtime = 0; // they are deleted, so no way to get ctime, mtime
k = {
key: key,
ctime: ctime,
mtime: mtime,
size: 0,
actionWhen: Date.now(),
actionType: "delete",
keyType: "folder",
renameTo: "",
vaultRandomID: vaultRandomID,
};
}
await db.fileHistoryTbl.setItem(`${vaultRandomID}\t${k.key}`, k);
}
Example #26
Source File: localdb.ts From remotely-save with Apache License 2.0 | 5 votes |
insertRenameRecordByVault = async (
db: InternalDBs,
fileOrFolder: TAbstractFile,
oldPath: string,
vaultRandomID: string
) => {
// log.info(fileOrFolder);
let k1: FileFolderHistoryRecord;
let k2: FileFolderHistoryRecord;
const actionWhen = Date.now();
if (fileOrFolder instanceof TFile) {
k1 = {
key: oldPath,
ctime: fileOrFolder.stat.ctime,
mtime: fileOrFolder.stat.mtime,
size: fileOrFolder.stat.size,
actionWhen: actionWhen,
actionType: "rename",
keyType: "file",
renameTo: fileOrFolder.path,
vaultRandomID: vaultRandomID,
};
k2 = {
key: fileOrFolder.path,
ctime: fileOrFolder.stat.ctime,
mtime: fileOrFolder.stat.mtime,
size: fileOrFolder.stat.size,
actionWhen: actionWhen,
actionType: "renameDestination",
keyType: "file",
renameTo: "", // itself is the destination, so no need to set this field
vaultRandomID: vaultRandomID,
};
} else if (fileOrFolder instanceof TFolder) {
const key = oldPath.endsWith("/") ? oldPath : `${oldPath}/`;
const renameTo = fileOrFolder.path.endsWith("/")
? fileOrFolder.path
: `${fileOrFolder.path}/`;
let ctime = 0;
let mtime = 0;
if (requireApiVersion(API_VER_STAT_FOLDER)) {
// TAbstractFile does not contain these info
// but from API_VER_STAT_FOLDER we can manually stat them by path.
const s = await statFix(fileOrFolder.vault, fileOrFolder.path);
ctime = s.ctime;
mtime = s.mtime;
}
k1 = {
key: key,
ctime: ctime,
mtime: mtime,
size: 0,
actionWhen: actionWhen,
actionType: "rename",
keyType: "folder",
renameTo: renameTo,
vaultRandomID: vaultRandomID,
};
k2 = {
key: renameTo,
ctime: ctime,
mtime: mtime,
size: 0,
actionWhen: actionWhen,
actionType: "renameDestination",
keyType: "folder",
renameTo: "", // itself is the destination, so no need to set this field
vaultRandomID: vaultRandomID,
};
}
await Promise.all([
db.fileHistoryTbl.setItem(`${vaultRandomID}\t${k1.key}`, k1),
db.fileHistoryTbl.setItem(`${vaultRandomID}\t${k2.key}`, k2),
]);
}
Example #27
Source File: misc.ts From folder-note-core with MIT License | 5 votes |
getRenamedPath = (af: TAbstractFile, newName: string) => {
const dir = getParentPath(af.path);
return dir ? join(dir, newName) : dir;
}
Example #28
Source File: misc.ts From alx-folder-note with MIT License | 5 votes |
getRenamedPath = (af: TAbstractFile, newName: string) =>
join(getParentPath(af.path), newName)
Example #29
Source File: main.test.ts From Templater with GNU Affero General Public License v3.0 | 5 votes |
active_files: Array<TAbstractFile> = new Array();