obsidian#TFolder TypeScript Examples

The following examples show how to use obsidian#TFolder. 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: vault-handler.ts    From folder-note-core with MIT License 6 votes vote down vote up
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 #2
Source File: folder-focus.ts    From alx-folder-note with MIT License 6 votes vote down vote up
constructor(plugin: ALxFolderNote, fileExplorer: FileExplorerView) {
    super(plugin, fileExplorer);
    const { workspace } = plugin.app;
    this.plugin.register(
      () => this.focusedFolder && this.toggleFocusFolder(null),
    );

    [
      workspace.on("file-menu", (menu, af) => {
        if (!(af instanceof TFolder) || af.isRoot()) return;
        menu.addItem((item) =>
          item
            .setTitle("Toggle Focus")
            .setIcon("crossed-star")
            .onClick(() => this.toggleFocusFolder(af)),
        );
      }),
    ].forEach(this.plugin.registerEvent.bind(this.plugin));
  }
Example #3
Source File: watcher.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
start(calendar?: Calendar) {
        const calendars = calendar ? [calendar] : this.calendars;
        if (!calendars.length) return;
        let folders: Set<string> = new Set();

        for (const calendar of calendars) {
            if (!calendar) continue;
            if (!calendar.autoParse) continue;
            const folder = this.vault.getAbstractFileByPath(calendar.path);
            if (!folder || !(folder instanceof TFolder)) continue;
            for (const child of folder.children) {
                folders.add(child.path);
            }
        }

        if (!folders.size) return;
        if (this.plugin.data.debug) {
            if (calendar) {
                console.info(
                    `Starting rescan for ${calendar.name} (${folders.size})`
                );
            } else {
                console.info(
                    `Starting rescan for ${calendars.length} calendars (${folders.size})`
                );
            }
        }
        this.startParsing([...folders]);
    }
Example #4
Source File: misc.ts    From folder-note-core with MIT License 6 votes vote down vote up
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 #5
Source File: folder.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
renderSuggestion(result: FuzzyMatch<TFolder>, el: HTMLElement) {
        let { item, match: matches } = result || {};
        let content = el.createDiv({
            cls: "suggestion-content"
        });
        if (!item) {
            content.setText(this.emptyStateText);
            content.parentElement.addClass("is-selected");
            return;
        }

        let pathLength = item.path.length - item.name.length;
        const matchElements = matches.matches.map((m) => {
            return createSpan("suggestion-highlight");
        });
        for (let i = pathLength; i < item.path.length; i++) {
            let match = matches.matches.find((m) => m[0] === i);
            if (match) {
                let element = matchElements[matches.matches.indexOf(match)];
                content.appendChild(element);
                element.appendText(item.path.substring(match[0], match[1]));

                i += match[1] - match[0] - 1;
                continue;
            }

            content.appendText(item.path[i]);
        }
        el.createDiv({
            cls: "suggestion-note",
            text: item.path
        });
    }
Example #6
Source File: checkAndCreateFolder.ts    From obsidian-ReadItLater with MIT License 6 votes vote down vote up
/**
 * Open or create a folderpath if it does not exist
 * @param vault
 * @param folderpath
 */
export async function checkAndCreateFolder(vault: Vault, folderpath: string) {
    folderpath = normalizePath(folderpath);
    const folder = vault.getAbstractFileByPath(folderpath);
    if (folder && folder instanceof TFolder) {
        return;
    }
    await vault.createFolder(folderpath);
}
Example #7
Source File: LocalImageModal.ts    From obsidian-banners with MIT License 6 votes vote down vote up
getItems(): TFile[] {
    const path = this.plugin.getSettingValue('bannersFolder');

    // Search all files if using the default setting
    if (path === DEFAULT_VALUES.bannersFolder) {
      return this.vault.getFiles().filter(f => IMAGE_FORMATS.includes(f.extension));
    }

    // Only search the designated folder when specified
    const folder = this.vault.getAbstractFileByPath(path);
    if (!folder || !(folder instanceof TFolder)) {
      new Notice(createFragment(frag => {
        frag.appendText('ERROR! Make sure that you set the ');
        frag.createEl('b', { text: 'Banners folder' });
        frag.appendText(' to a valid folder in the settings.');
      }), 7000);
      this.close();
      return [];
    }
    return this.getImagesInFolder(folder);
  }
Example #8
Source File: vault-handler.ts    From folder-note-core with MIT License 6 votes vote down vote up
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 #9
Source File: index.ts    From obsidian-dataview with MIT License 6 votes vote down vote up
private *walk(folder: TFolder, filter?: (path: string) => boolean): Generator<string> {
        for (const file of folder.children) {
            if (file instanceof TFolder) {
                yield* this.walk(file, filter);
            } else if (filter ? filter(file.path) : true) {
                yield file.path;
            }
        }
    }
Example #10
Source File: folder.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
getFolder() {
        const v = this.inputEl.value,
            folder = this.app.vault.getAbstractFileByPath(v);
        if (folder == this.folder) return;
        if (!(folder instanceof TFolder)) return;
        this.folder = folder;

        this.onInputChanged();
    }
Example #11
Source File: relatedItemsHandler.ts    From obsidian-switcher-plus with GNU General Public License v3.0 6 votes vote down vote up
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: tools.ts    From obsidian-chartsview-plugin with MIT License 6 votes vote down vote up
export function getFolderOptions(app: App) {
    const options: Record<string, string> = {};

    Vault.recurseChildren(app.vault.getRoot(), (f) => {
        if (f instanceof TFolder) {
            options[f.path] = f.path;
        }
    });

    return options;
}
Example #13
Source File: QuickAddEngine.ts    From quickadd with MIT License 6 votes vote down vote up
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 #14
Source File: headingshandler.test.ts    From obsidian-switcher-plus with GNU General Public License v3.0 6 votes vote down vote up
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 #15
Source File: LocalImageModal.ts    From obsidian-banners with MIT License 6 votes vote down vote up
private getImagesInFolder(folder: TFolder): TFile[] {
    const files: TFile[] = [];
    folder.children.forEach((abFile) => {
      if (abFile instanceof TFolder) {
        files.push(...this.getImagesInFolder(folder));
      }
      const file = abFile as TFile;
      if (IMAGE_FORMATS.includes(file.extension)) {
        files.push(file);
      }
    });
    return files;
  }
Example #16
Source File: files-manager.ts    From Obsidian_to_Anki with GNU General Public License v3.0 6 votes vote down vote up
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 #17
Source File: Templater.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
get_new_file_template_for_folder(folder: TFolder): string {
        do {
            const match = this.plugin.settings.folder_templates.find(
                (e) => e.folder == folder.path
            );

            if (match && match.template) {
                return match.template;
            }

            folder = folder.parent;
        } while (folder);
    }
Example #18
Source File: main.ts    From obsidian-tracker with MIT License 6 votes vote down vote up
getFilesInFolder(
        folder: TFolder,
        includeSubFolders: boolean = true
    ): TFile[] {
        let files: TFile[] = [];

        for (let item of folder.children) {
            if (item instanceof TFile) {
                if (item.extension === "md") {
                    files.push(item);
                }
            } else {
                if (item instanceof TFolder && includeSubFolders) {
                    files = files.concat(this.getFilesInFolder(item));
                }
            }
        }

        return files;
    }
Example #19
Source File: FolderSuggester.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
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: main.ts    From obsidian-linter with MIT License 6 votes vote down vote up
async runLinterAllFilesInFolder(folder: TFolder) {
      console.log('Linting folder ' + folder.name);

      let lintedFiles = 0;
      await Promise.all(this.app.vault.getMarkdownFiles().map(async (file) => {
        if (this.convertPathToNormalizedString(file.path).startsWith(this.convertPathToNormalizedString(folder.path) + '|') && !this.shouldIgnoreFile(file)) {
          await this.runLinterFile(file);
          lintedFiles++;
        }
      }));
      new Notice('Linted all ' + lintedFiles + ' files in ' + folder.name);
    }
Example #21
Source File: folder-focus.ts    From alx-folder-note with MIT License 6 votes vote down vote up
toggleFocusFolder(folder: TFolder | null) {
    const folderItem = folder
      ? (this.getAfItem(folder.path) as FolderItem | null)
      : null;
    if (this.focusedFolder) {
      this._focusFolder(this.focusedFolder, true);
    }
    // if given same folder as current cached, toggle it off
    if (folderItem && folderItem.file.path === this.focusedFolder?.file.path) {
      this.focusedFolder = null;
    } else {
      folderItem && this._focusFolder(folderItem, false);
      this.focusedFolder = folderItem;
    }
  }
Example #22
Source File: main.test.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
async createFolder(folder_name: string): Promise<TFolder> {
        let folder = this.retrieveActiveFile(folder_name);
        if (folder && folder instanceof TFolder) {
            return folder;
        }
        await this.app.vault.createFolder(folder_name);
        folder = this.app.vault.getAbstractFileByPath(folder_name);
        if (!(folder instanceof TFolder)) {
            return null;
        }
        this.active_files.push(folder);
        return folder;
    }
Example #23
Source File: folder.ts    From obsidian-fantasy-calendar with MIT License 5 votes vote down vote up
selectSuggestion({ item }: FuzzyMatch<TFolder>) {
        let link = item.path;

        this.text.setValue(link);
        this.onClose();

        this.close();
    }
Example #24
Source File: localdb.ts    From remotely-save with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: folder.ts    From obsidian-fantasy-calendar with MIT License 5 votes vote down vote up
folder: TFolder;
Example #26
Source File: localdb.ts    From remotely-save with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: resolver.ts    From folder-note-core with MIT License 5 votes vote down vote up
targetFolder: TFolder;
Example #28
Source File: main.ts    From obsidian-linter with MIT License 5 votes vote down vote up
async onload() {
      console.log('Loading Linter plugin');
      await this.loadSettings();

      this.addCommand({
        id: 'lint-file',
        name: 'Lint the current file',
        editorCallback: (editor) => this.runLinterEditor(editor),
        hotkeys: [
          {
            modifiers: ['Mod', 'Alt'],
            key: 'l',
          },
        ],
      });

      this.addCommand({
        id: 'lint-all-files',
        name: 'Lint all files in the vault',
        callback: () => {
          const startMessage = 'This will edit all of your files and may introduce errors.';
          const submitBtnText = 'Lint All';
          const submitBtnNoticeText = 'Linting all files...';
          new LintConfirmationModal(this.app, startMessage, submitBtnText, submitBtnNoticeText, () =>{
            return this.runLinterAllFiles(this.app);
          }).open();
        },
      });

      this.addCommand({
        id: 'lint-all-files-in-folder',
        name: 'Lint all files in the current folder',
        editorCallback: (_) => {
          this.createFolderLintModal(this.app.workspace.getActiveFile().parent);
        },
      });

      // https://github.com/mgmeyers/obsidian-kanban/blob/main/src/main.ts#L239-L251
      this.registerEvent(
          this.app.workspace.on('file-menu', (menu, file: TFile) => {
            // Add a menu item to the folder context menu to create a board
            if (file instanceof TFolder) {
              menu.addItem((item) => {
                item
                    .setTitle('Lint folder')
                    .setIcon('wrench-screwdriver-glyph')
                    .onClick(() => this.createFolderLintModal(file));
              });
            }
          }),
      );

      this.eventRef = this.app.workspace.on('file-menu',
          (menu, file, source) => this.onMenuOpenCallback(menu, file, source));
      this.registerEvent(this.eventRef);

      // Source for save setting
      // https://github.com/hipstersmoothie/obsidian-plugin-prettier/blob/main/src/main.ts
      const saveCommandDefinition = (this.app as any).commands?.commands?.[
        'editor:save-file'
      ];
      const save = saveCommandDefinition?.callback;

      if (typeof save === 'function') {
        saveCommandDefinition.callback = () => {
          if (this.settings.lintOnSave) {
            const editor = this.app.workspace.getActiveViewOfType(MarkdownView).editor;
            const file = this.app.workspace.getActiveFile();

            if (!this.shouldIgnoreFile(file)) {
              this.runLinterEditor(editor);
            }
          }
        };
      }

      this.addSettingTab(new SettingTab(this.app, this));
    }
Example #29
Source File: set-folder-icon.ts    From alx-folder-note with MIT License 5 votes vote down vote up
registerSetFolderIconCmd = (plugin: ALxFolderNote) => {
  const { workspace, vault } = plugin.app;
  const setIconField = async (icon: IconInfo | null, file: TFile) =>
    icon &&
    vault.modify(
      file,
      (matter(await vault.read(file)).stringify as any)(
        { icon: icon.id },
        { flowLevel: 3, indent: 4 },
      ),
    );
  plugin.addCommand({
    id: "set-folder-icon",
    name: "Set Folder Icon",
    checkCallback: (checking) => {
      const iscAPI = plugin.IconSCAPI;
      if (!iscAPI) return false;
      const mdView = workspace.getActiveViewOfType(MarkdownView);
      if (!mdView) return false;
      const folder = plugin.CoreApi.getFolderFromNote(mdView.file);
      if (!folder) return false;
      if (checking) return true;
      iscAPI.getIconFromUser().then((icon) => setIconField(icon, mdView.file));
    },
  });
  plugin.registerEvent(
    workspace.on("file-menu", (menu, af, src) => {
      const iscAPI = plugin.IconSCAPI;
      if (!iscAPI) return;
      let note;
      if (
        (af instanceof TFolder && (note = plugin.CoreApi.getFolderNote(af))) ||
        (af instanceof TFile &&
          ((note = af), plugin.CoreApi.getFolderFromNote(af)))
      ) {
        const folderNote = note;
        menu.addItem((item) =>
          item
            .setIcon("image-glyph")
            .setTitle("Set Folder Icon")
            .onClick(async () =>
              setIconField(await iscAPI.getIconFromUser(), folderNote),
            ),
        );
      }
    }),
  );
}