New eslint rules

This commit is contained in:
Lost Paul 2023-03-19 23:11:00 +01:00
parent 0003bd2220
commit 876e4f40e7
12 changed files with 1097 additions and 981 deletions

159
.eslintrc
View file

@ -1,23 +1,140 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"env": { "node": true },
"plugins": [
"@typescript-eslint"
"root": true,
"parser": "@typescript-eslint/parser",
"env": {
"node": true
},
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
"args": "none"
}
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["error", { "args": "none" }],
"@typescript-eslint/ban-ts-comment": "off",
"no-prototype-builtins": "off",
"@typescript-eslint/no-empty-function": "off"
}
}
"@typescript-eslint/ban-ts-comment": "off",
"no-prototype-builtins": "off",
"@typescript-eslint/no-empty-function": "off",
"brace-style": [
"error",
"1tbs",
{
"allowSingleLine": true
}
],
"consistent-return": "off",
"quotes": [
"error",
"single",
{
"avoidEscape": true
}
],
"no-mixed-spaces-and-tabs": "error",
"indent": [
"error",
"tab",
{
"SwitchCase": 1
}
],
"arrow-parens": [
"error",
"always"
],
"eol-last": [
"error",
"always"
],
"func-call-spacing": [
"error",
"never"
],
"comma-dangle": [
"error",
"always-multiline"
],
"no-multi-spaces": "error",
"no-trailing-spaces": "error",
"no-whitespace-before-property": "off",
"semi": [
"error",
"always"
],
"semi-style": [
"error",
"last"
],
"space-in-parens": [
"error",
"never"
],
"block-spacing": [
"error",
"always"
],
"object-curly-spacing": [
"error",
"always"
],
"eqeqeq": [
"error",
"always",
{
"null": "ignore"
}
],
"spaced-comment": [
"error",
"always",
{
"markers": [
"!"
]
}
],
"yoda": "error",
"prefer-destructuring": [
"error",
{
"object": false,
"array": false
}
],
"operator-assignment": [
"error",
"always"
],
"no-useless-computed-key": "error",
"no-unneeded-ternary": [
"error",
{
"defaultAssignment": false
}
],
"no-invalid-regexp": "error",
"no-constant-condition": [
"error",
{
"checkLoops": false
}
],
"no-duplicate-imports": "error",
"no-extra-semi": "error",
"dot-notation": "error",
"no-useless-escape": [
"error"
]
}
}

View file

@ -2,37 +2,37 @@ import { App, TFolder, Menu, TAbstractFile, Notice } from 'obsidian';
import FolderNotesPlugin from './main';
import { ExcludedFolder } from './settings';
export class Commands {
plugin: FolderNotesPlugin;
app: App;
constructor(app: App, plugin: FolderNotesPlugin) {
this.plugin = plugin;
this.app = app;
}
registerCommands() {
this.plugin.registerEvent(this.app.workspace.on('file-menu', (menu: Menu, file: TAbstractFile) => {
if (!(file instanceof TFolder)) return;
if (this.plugin.settings.excludeFolders.find((folder) => folder.path === file.path)) {
menu.addItem((item) => {
item.setTitle('Remove folder from excluded folders')
.setIcon('x')
.onClick(() => {
this.plugin.settings.excludeFolders = this.plugin.settings.excludeFolders.filter((folder) => folder.path !== file.path);
this.plugin.saveSettings();
new Notice('Successfully removed folder from excluded folders');
});
});
return;
}
menu.addItem((item) => {
item.setTitle('Exclude folder from folder notes')
.setIcon('x')
.onClick(() => {
const excludedFolder = new ExcludedFolder(file.path, this.plugin.settings.excludeFolders.length);
this.plugin.settings.excludeFolders.push(excludedFolder);
this.plugin.saveSettings();
new Notice('Successfully excluded folder from folder notes');
});
});
}));
}
}
plugin: FolderNotesPlugin;
app: App;
constructor(app: App, plugin: FolderNotesPlugin) {
this.plugin = plugin;
this.app = app;
}
registerCommands() {
this.plugin.registerEvent(this.app.workspace.on('file-menu', (menu: Menu, file: TAbstractFile) => {
if (!(file instanceof TFolder)) return;
if (this.plugin.settings.excludeFolders.find((folder) => folder.path === file.path)) {
menu.addItem((item) => {
item.setTitle('Remove folder from excluded folders')
.setIcon('x')
.onClick(() => {
this.plugin.settings.excludeFolders = this.plugin.settings.excludeFolders.filter((folder) => folder.path !== file.path);
this.plugin.saveSettings();
new Notice('Successfully removed folder from excluded folders');
});
});
return;
}
menu.addItem((item) => {
item.setTitle('Exclude folder from folder notes')
.setIcon('x')
.onClick(() => {
const excludedFolder = new ExcludedFolder(file.path, this.plugin.settings.excludeFolders.length);
this.plugin.settings.excludeFolders.push(excludedFolder);
this.plugin.saveSettings();
new Notice('Successfully excluded folder from folder notes');
});
});
}));
}
}

View file

@ -1,222 +1,222 @@
import { Plugin, TFile, TFolder, TAbstractFile, Notice } from 'obsidian'
import { DEFAULT_SETTINGS, FolderNotesSettings, SettingsTab } from './settings'
import { Plugin, TFile, TFolder, TAbstractFile, Notice } from 'obsidian';
import { DEFAULT_SETTINGS, FolderNotesSettings, SettingsTab } from './settings';
import FolderNameModal from './modals/folderName';
import { applyTemplate } from './template';
import { Commands } from './commands';
export default class FolderNotesPlugin extends Plugin {
observer: MutationObserver
folders: TFolder[] = []
settings: FolderNotesSettings
settingsTab: SettingsTab;
async onload() {
console.log('loading folder notes plugin');
await this.loadSettings();
this.settingsTab = new SettingsTab(this.app, this);
this.addSettingTab(this.settingsTab);
document.body.classList.add('folder-notes-plugin')
if (this.settings.hideFolderNote) {
document.body.classList.add('hide-folder-note');
} else {
document.body.classList.remove('hide-folder-note');
}
new Commands(this.app, this).registerCommands();
this.registerEvent(this.app.vault.on('create', (folder: TAbstractFile) => {
if (!this.app.workspace.layoutReady) return;
if (!this.settings.autoCreate) return;
if (!(folder instanceof TFolder)) return;
observer: MutationObserver;
folders: TFolder[] = [];
settings: FolderNotesSettings;
settingsTab: SettingsTab;
async onload() {
console.log('loading folder notes plugin');
await this.loadSettings();
this.settingsTab = new SettingsTab(this.app, this);
this.addSettingTab(this.settingsTab);
document.body.classList.add('folder-notes-plugin');
if (this.settings.hideFolderNote) {
document.body.classList.add('hide-folder-note');
} else {
document.body.classList.remove('hide-folder-note');
}
new Commands(this.app, this).registerCommands();
this.registerEvent(this.app.vault.on('create', (folder: TAbstractFile) => {
if (!this.app.workspace.layoutReady) return;
if (!this.settings.autoCreate) return;
if (!(folder instanceof TFolder)) return;
const excludedFolder = this.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder.path) ||
(excludedFolder.path === folder.path?.slice(0, folder?.path.lastIndexOf("/") >= 0 ? folder.path?.lastIndexOf("/") : folder.path.length)
const excludedFolder = this.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder.path) ||
(excludedFolder.path === folder.path?.slice(0, folder?.path.lastIndexOf('/') >= 0 ? folder.path?.lastIndexOf('/') : folder.path.length)
&& excludedFolder.subFolders));
if (excludedFolder?.disableAutoCreate) return;
if (excludedFolder?.disableAutoCreate) return;
const path = folder.path + '/' + folder.name + '.md';
if (!path) return;
const file = this.app.vault.getAbstractFileByPath(path);
if (file) return;
this.createFolderNote(path, true, true);
const path = folder.path + '/' + folder.name + '.md';
if (!path) return;
const file = this.app.vault.getAbstractFileByPath(path);
if (file) return;
this.createFolderNote(path, true, true);
}));
}));
this.registerEvent(this.app.vault.on('rename', (file: TAbstractFile, oldPath: string) => {
if (!this.settings.syncFolderName) return;
if (file instanceof TFolder) {
const folder = this.app.vault.getAbstractFileByPath(file?.path);
if (!folder) return;
const excludedFolder = this.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder.path) ||
(excludedFolder.path === folder.path?.slice(0, folder?.path.lastIndexOf("/") >= 0 ? folder.path?.lastIndexOf("/") : folder.path.length)
this.registerEvent(this.app.vault.on('rename', (file: TAbstractFile, oldPath: string) => {
if (!this.settings.syncFolderName) return;
if (file instanceof TFolder) {
const folder = this.app.vault.getAbstractFileByPath(file?.path);
if (!folder) return;
const excludedFolder = this.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder.path) ||
(excludedFolder.path === folder.path?.slice(0, folder?.path.lastIndexOf('/') >= 0 ? folder.path?.lastIndexOf('/') : folder.path.length)
&& excludedFolder.subFolders));
if (excludedFolder?.disableSync) return;
const excludedFolders = this.settings.excludeFolders.filter(
(excludedFolder) => excludedFolder.path.includes(oldPath)
);
if (excludedFolder?.disableSync) return;
const excludedFolders = this.settings.excludeFolders.filter(
(excludedFolder) => excludedFolder.path.includes(oldPath)
);
excludedFolders.forEach((excludedFolder) => {
const folders = excludedFolder.path.split('/');
if (folders.length < 1) {
folders.push(excludedFolder.path);
}
excludedFolders.forEach((excludedFolder) => {
const folders = excludedFolder.path.split('/');
if (folders.length < 1) {
folders.push(excludedFolder.path);
}
const oldName = oldPath.substring(oldPath.lastIndexOf('/' || '\\'));
folders[folders.indexOf(oldName.replace('/', ''))] = folder.name;
excludedFolder.path = folders.join('/');
});
this.saveSettings();
const oldName = oldPath.substring(oldPath.lastIndexOf('/' || '\\'));
folders[folders.indexOf(oldName.replace('/', ''))] = folder.name;
excludedFolder.path = folders.join('/');
});
this.saveSettings();
const oldName = oldPath.substring(oldPath.lastIndexOf('/' || '\\'));
const newPath = folder?.path + '/' + folder?.name + '.md';
if (folder instanceof TFolder) {
const note = this.app.vault.getAbstractFileByPath(oldPath + '/' + oldName + '.md');
if (!note) return;
(note as any).path = folder.path + '/' + oldName + '.md';
if (note instanceof TFile) {
this.app.vault.rename(note, newPath);
}
}
} else if (file instanceof TFile) {
const folder = this.app.vault.getAbstractFileByPath(oldPath.substring(0, oldPath.lastIndexOf('/' || '\\')));
if (folder?.name + '.md' == file.name) return;
const oldFileName = oldPath.substring(oldPath.lastIndexOf('/' || '\\') + 1);
if (!folder) return;
const excludedFolder = this.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder.path) ||
(excludedFolder.path === folder.path?.slice(0, folder?.path.lastIndexOf("/") >= 0 ? folder.path?.lastIndexOf("/") : folder.path.length)
const oldName = oldPath.substring(oldPath.lastIndexOf('/' || '\\'));
const newPath = folder?.path + '/' + folder?.name + '.md';
if (folder instanceof TFolder) {
const note = this.app.vault.getAbstractFileByPath(oldPath + '/' + oldName + '.md');
if (!note) return;
(note as any).path = folder.path + '/' + oldName + '.md';
if (note instanceof TFile) {
this.app.vault.rename(note, newPath);
}
}
} else if (file instanceof TFile) {
const folder = this.app.vault.getAbstractFileByPath(oldPath.substring(0, oldPath.lastIndexOf('/' || '\\')));
if (folder?.name + '.md' === file.name) return;
const oldFileName = oldPath.substring(oldPath.lastIndexOf('/' || '\\') + 1);
if (!folder) return;
const excludedFolder = this.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder.path) ||
(excludedFolder.path === folder.path?.slice(0, folder?.path.lastIndexOf('/') >= 0 ? folder.path?.lastIndexOf('/') : folder.path.length)
&& excludedFolder.subFolders));
if (excludedFolder?.disableSync) return;
if (oldFileName !== folder?.name + '.md') return;
let newFolderPath = file.path.slice(0, file.path.lastIndexOf('/'))
if (newFolderPath.lastIndexOf('/') > 0) {
newFolderPath = newFolderPath.slice(0, newFolderPath.lastIndexOf('/')) + '/'
} else {
newFolderPath = ''
}
newFolderPath = newFolderPath + file.name.replace('.md', '');
if (this.app.vault.getAbstractFileByPath(newFolderPath)) {
this.app.vault.rename(file, oldPath);
return new Notice('A folder with the same name already exists');
}
if (folder instanceof TFolder) {
this.app.vault.rename(folder, folder.path.substring(0, folder.path.lastIndexOf('/' || '\\')) + '/' + file.name.substring(0, file.name.lastIndexOf('.')));
}
}
}));
if (excludedFolder?.disableSync) return;
if (oldFileName !== folder?.name + '.md') return;
let newFolderPath = file.path.slice(0, file.path.lastIndexOf('/'));
if (newFolderPath.lastIndexOf('/') > 0) {
newFolderPath = newFolderPath.slice(0, newFolderPath.lastIndexOf('/')) + '/';
} else {
newFolderPath = '';
}
newFolderPath += file.name.replace('.md', '');
if (this.app.vault.getAbstractFileByPath(newFolderPath)) {
this.app.vault.rename(file, oldPath);
return new Notice('A folder with the same name already exists');
}
if (folder instanceof TFolder) {
this.app.vault.rename(folder, folder.path.substring(0, folder.path.lastIndexOf('/' || '\\')) + '/' + file.name.substring(0, file.name.lastIndexOf('.')));
}
}
}));
this.observer = new MutationObserver((mutations: MutationRecord[]) => {
mutations.forEach((rec) => {
if (rec.type === 'childList') {
(<Element>rec.target).querySelectorAll('div.nav-folder-title-content')
.forEach((element: HTMLElement) => {
if (element.onclick) return;
element.onclick = (event: MouseEvent) => this.handleFolderClick(event);
});
}
})
});
this.observer.observe(document.body, {
childList: true,
subtree: true,
});
}
this.observer = new MutationObserver((mutations: MutationRecord[]) => {
mutations.forEach((rec) => {
if (rec.type === 'childList') {
(<Element>rec.target).querySelectorAll('div.nav-folder-title-content')
.forEach((element: HTMLElement) => {
if (element.onclick) return;
element.onclick = (event: MouseEvent) => this.handleFolderClick(event);
});
}
});
});
this.observer.observe(document.body, {
childList: true,
subtree: true,
});
}
async handleFolderClick(event: MouseEvent) {
if (!(event.target instanceof HTMLElement)) return;
event.stopImmediatePropagation();
if (!document.body.classList.contains('folder-notes-plugin')) {
event.target.onclick = null;
event.target.click();
return;
}
async handleFolderClick(event: MouseEvent) {
if (!(event.target instanceof HTMLElement)) return;
event.stopImmediatePropagation();
if (!document.body.classList.contains('folder-notes-plugin')) {
event.target.onclick = null;
event.target.click();
return;
}
const folder = event.target.parentElement?.getAttribute('data-path');
const excludedFolder = this.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder) ||
(excludedFolder.path === folder?.slice(0, folder?.lastIndexOf("/") >= 0 ? folder?.lastIndexOf("/") : folder.length)
const folder = event.target.parentElement?.getAttribute('data-path');
const excludedFolder = this.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder) ||
(excludedFolder.path === folder?.slice(0, folder?.lastIndexOf('/') >= 0 ? folder?.lastIndexOf('/') : folder.length)
&& excludedFolder.subFolders));
if (excludedFolder?.disableFolderNote) {
event.target.onclick = null;
event.target.click();
event.target.parentElement?.parentElement?.getElementsByClassName('nav-folder-children').item(0)?.querySelectorAll('div.nav-file')
.forEach((element: HTMLElement) => {
if (element.innerText === (event.target as HTMLElement)?.innerText && element.classList.contains('is-folder-note')) {
element.removeClass('is-folder-note');
}
});
return;
} else if (excludedFolder?.enableCollapsing || this.settings.enableCollapsing) {
event.target.onclick = null;
event.target.click();
}
const path = folder + '/' + event.target.innerText + '.md';
if (excludedFolder?.disableFolderNote) {
event.target.onclick = null;
event.target.click();
event.target.parentElement?.parentElement?.getElementsByClassName('nav-folder-children').item(0)?.querySelectorAll('div.nav-file')
.forEach((element: HTMLElement) => {
if (element.innerText === (event.target as HTMLElement)?.innerText && element.classList.contains('is-folder-note')) {
element.removeClass('is-folder-note');
}
});
return;
} else if (excludedFolder?.enableCollapsing || this.settings.enableCollapsing) {
event.target.onclick = null;
event.target.click();
}
const path = folder + '/' + event.target.innerText + '.md';
if (this.app.vault.getAbstractFileByPath(path)) {
this.openFolderNote(path);
if (!this.settings.hideFolderNote) return;
event.target.parentElement?.parentElement?.getElementsByClassName('nav-folder-children').item(0)?.querySelectorAll('div.nav-file')
.forEach((element: HTMLElement) => {
if (element.innerText === (event.target as HTMLElement)?.innerText && !element.classList.contains('is-folder-note')) {
if (this.app.vault.getAbstractFileByPath(path)) {
this.openFolderNote(path);
if (!this.settings.hideFolderNote) return;
event.target.parentElement?.parentElement?.getElementsByClassName('nav-folder-children').item(0)?.querySelectorAll('div.nav-file')
.forEach((element: HTMLElement) => {
if (element.innerText === (event.target as HTMLElement)?.innerText && !element.classList.contains('is-folder-note')) {
element.addClass('is-folder-note');
}
});
element.addClass('is-folder-note');
}
});
} else if (event.altKey || event.ctrlKey) {
if ((this.settings.altKey && event.altKey) || (this.settings.ctrlKey && event.ctrlKey)) {
this.createFolderNote(path, true, true);
if (!this.settings.hideFolderNote) return;
event.target.parentElement?.parentElement?.getElementsByClassName('nav-folder-children').item(0)?.querySelectorAll('div.nav-file')
.forEach((element: HTMLElement) => {
if (element.innerText === (event.target as HTMLElement)?.innerText && !element.classList.contains('is-folder-note')) {
element.addClass('is-folder-note');
}
});
} else {
event.target.onclick = null;
event.target.click();
}
} else {
event.target.onclick = null;
event.target.click();
}
}
} else if (event.altKey || event.ctrlKey) {
if ((this.settings.altKey && event.altKey) || (this.settings.ctrlKey && event.ctrlKey)) {
this.createFolderNote(path, true, true);
if (!this.settings.hideFolderNote) return;
event.target.parentElement?.parentElement?.getElementsByClassName('nav-folder-children').item(0)?.querySelectorAll('div.nav-file')
.forEach((element: HTMLElement) => {
if (element.innerText === (event.target as HTMLElement)?.innerText && !element.classList.contains('is-folder-note')) {
element.addClass('is-folder-note');
}
});
} else {
event.target.onclick = null;
event.target.click();
}
} else {
event.target.onclick = null;
event.target.click();
}
}
async createFolderNote(path: string, openFile: boolean, useModal?: boolean) {
const leaf = this.app.workspace.getLeaf(false);
const file = await this.app.vault.create(path, '');
if (openFile) {
await leaf.openFile(file);
}
if (file) {
applyTemplate(this, file, this.settings.templatePath);
}
if (!this.settings.autoCreate) return;
if (!useModal) return;
const folder = this.app.vault.getAbstractFileByPath(path.substring(0, path.lastIndexOf('/' || '\\')));
if (!(folder instanceof TFolder)) return;
const modal = new FolderNameModal(this.app, this, folder);
modal.open();
}
async createFolderNote(path: string, openFile: boolean, useModal?: boolean) {
const leaf = this.app.workspace.getLeaf(false);
const file = await this.app.vault.create(path, '');
if (openFile) {
await leaf.openFile(file);
}
if (file) {
applyTemplate(this, file, this.settings.templatePath);
}
if (!this.settings.autoCreate) return;
if (!useModal) return;
const folder = this.app.vault.getAbstractFileByPath(path.substring(0, path.lastIndexOf('/' || '\\')));
if (!(folder instanceof TFolder)) return;
const modal = new FolderNameModal(this.app, this, folder);
modal.open();
}
async openFolderNote(path: string) {
const leaf = this.app.workspace.getLeaf(false);
const file = this.app.vault.getAbstractFileByPath(path);
if (file instanceof TFile) {
await leaf.openFile(file);
}
}
async openFolderNote(path: string) {
const leaf = this.app.workspace.getLeaf(false);
const file = this.app.vault.getAbstractFileByPath(path);
if (file instanceof TFile) {
await leaf.openFile(file);
}
}
onunload() {
console.log('unloading folder notes plugin');
this.observer.disconnect();
document.body.classList.remove('folder-notes-plugin');
}
onunload() {
console.log('unloading folder notes plugin');
this.observer.disconnect();
document.body.classList.remove('folder-notes-plugin');
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
async saveSettings() {
await this.saveData(this.settings);
}
}

View file

@ -1,47 +1,47 @@
import { App, Modal, Setting, TFolder } from 'obsidian';
import FolderNotesPlugin from '../main';
export default class ConfirmationModal extends Modal {
plugin: FolderNotesPlugin;
app: App;
folder: TFolder;
constructor(app: App, plugin: FolderNotesPlugin) {
super(app);
this.plugin = plugin;
this.app = app;
}
onOpen() {
const { contentEl } = this;
contentEl.createEl('h2', { text: 'Create folder note for every folder' });
const setting = new Setting(contentEl)
setting.infoEl.createEl('p', { text: 'Make sure to backup your vault before using this feature.' }).style.color = '#fb464c';
setting.infoEl.createEl('p', { text: 'This feature will create a folder note for every folder in your vault.' });
setting.infoEl.createEl('p', { text: 'Every folder that already has a folder note will be ignored.' });
setting.infoEl.createEl('p', { text: 'Every excluded folder will be ignored.' });
setting.infoEl.parentElement?.classList.add('fn-confirmation-modal')
const button = setting.infoEl.createEl('button', { text: 'Create' });
button.classList.add('mod-warning', 'fn-confirmation-modal-button');
button.addEventListener('click', async () => {
this.close();
this.app.vault.getAllLoadedFiles().forEach(async (folder) => {
if (folder instanceof TFolder) {
const excludedFolder = this.plugin.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder.path) ||
(excludedFolder.path === folder.path?.slice(0, folder?.path.lastIndexOf("/") >= 0 ? folder.path?.lastIndexOf("/") : folder.path.length)
plugin: FolderNotesPlugin;
app: App;
folder: TFolder;
constructor(app: App, plugin: FolderNotesPlugin) {
super(app);
this.plugin = plugin;
this.app = app;
}
onOpen() {
const { contentEl } = this;
contentEl.createEl('h2', { text: 'Create folder note for every folder' });
const setting = new Setting(contentEl);
setting.infoEl.createEl('p', { text: 'Make sure to backup your vault before using this feature.' }).style.color = '#fb464c';
setting.infoEl.createEl('p', { text: 'This feature will create a folder note for every folder in your vault.' });
setting.infoEl.createEl('p', { text: 'Every folder that already has a folder note will be ignored.' });
setting.infoEl.createEl('p', { text: 'Every excluded folder will be ignored.' });
setting.infoEl.parentElement?.classList.add('fn-confirmation-modal');
const button = setting.infoEl.createEl('button', { text: 'Create' });
button.classList.add('mod-warning', 'fn-confirmation-modal-button');
button.addEventListener('click', async () => {
this.close();
this.app.vault.getAllLoadedFiles().forEach(async (folder) => {
if (folder instanceof TFolder) {
const excludedFolder = this.plugin.settings.excludeFolders.find(
(excludedFolder) => (excludedFolder.path === folder.path) ||
(excludedFolder.path === folder.path?.slice(0, folder?.path.lastIndexOf('/') >= 0 ? folder.path?.lastIndexOf('/') : folder.path.length)
&& excludedFolder.subFolders));
if (excludedFolder) return;
if (this.app.vault.getAbstractFileByPath(folder.path + '/' + folder.name + '.md')) return;
await this.plugin.createFolderNote(folder.path + '/' + folder.name + '.md', true);
}
})
});
button.focus();
const cancelButton = setting.infoEl.createEl('button', { text: 'Cancel' });
cancelButton.addEventListener('click', async () => {
this.close();
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
if (excludedFolder) return;
if (this.app.vault.getAbstractFileByPath(folder.path + '/' + folder.name + '.md')) return;
await this.plugin.createFolderNote(folder.path + '/' + folder.name + '.md', true);
}
});
});
button.focus();
const cancelButton = setting.infoEl.createEl('button', { text: 'Cancel' });
cancelButton.addEventListener('click', async () => {
this.close();
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}

View file

@ -2,89 +2,89 @@ import { App, Modal, Setting } from 'obsidian';
import FolderNotesPlugin from '../main';
import { ExcludedFolder } from '../settings';
export default class ExcludedFolderSettings extends Modal {
plugin: FolderNotesPlugin;
app: App;
excludedFolder: ExcludedFolder;
constructor(app: App, plugin: FolderNotesPlugin, excludedFolder: ExcludedFolder) {
super(app);
this.plugin = plugin;
this.app = app;
this.excludedFolder = excludedFolder;
}
onOpen() {
this.display();
}
display() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl('h2', { text: 'Exluded folder settings' });
new Setting(contentEl)
.setName('Include subfolders')
.setDesc('Choose if the subfolders of the folder should also be excluded')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.subFolders)
.onChange(async (value) => {
this.excludedFolder.subFolders = value;
await this.plugin.saveSettings();
})
);
plugin: FolderNotesPlugin;
app: App;
excludedFolder: ExcludedFolder;
constructor(app: App, plugin: FolderNotesPlugin, excludedFolder: ExcludedFolder) {
super(app);
this.plugin = plugin;
this.app = app;
this.excludedFolder = excludedFolder;
}
onOpen() {
this.display();
}
display() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl('h2', { text: 'Exluded folder settings' });
new Setting(contentEl)
.setName('Include subfolders')
.setDesc('Choose if the subfolders of the folder should also be excluded')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.subFolders)
.onChange(async (value) => {
this.excludedFolder.subFolders = value;
await this.plugin.saveSettings();
})
);
new Setting(contentEl)
.setName('Disable folder name sync')
.setDesc('Choose if the folder note should be renamed when the folder name is changed')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.disableSync)
.onChange(async (value) => {
this.excludedFolder.disableSync = value;
await this.plugin.saveSettings();
})
);
new Setting(contentEl)
.setName('Disable folder name sync')
.setDesc('Choose if the folder note should be renamed when the folder name is changed')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.disableSync)
.onChange(async (value) => {
this.excludedFolder.disableSync = value;
await this.plugin.saveSettings();
})
);
new Setting(contentEl)
.setName('Disable auto creation of folder notes in this folder')
.setDesc('Choose if a folder note should be created when a new folder is created')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.disableAutoCreate)
.onChange(async (value) => {
this.excludedFolder.disableAutoCreate = value;
await this.plugin.saveSettings();
})
);
new Setting(contentEl)
.setName('Disable auto creation of folder notes in this folder')
.setDesc('Choose if a folder note should be created when a new folder is created')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.disableAutoCreate)
.onChange(async (value) => {
this.excludedFolder.disableAutoCreate = value;
await this.plugin.saveSettings();
})
);
new Setting(contentEl)
.setName('Disable open folder note')
.setDesc('Choose if the folder note should be opened when the folder is opened')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.disableFolderNote)
.onChange(async (value) => {
this.excludedFolder.disableFolderNote = value;
await this.plugin.saveSettings();
this.display();
})
);
new Setting(contentEl)
.setName('Disable open folder note')
.setDesc('Choose if the folder note should be opened when the folder is opened')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.disableFolderNote)
.onChange(async (value) => {
this.excludedFolder.disableFolderNote = value;
await this.plugin.saveSettings();
this.display();
})
);
if (!this.excludedFolder.disableFolderNote) {
new Setting(contentEl)
.setName('Collapse folder when opening folder note')
.setDesc('Choose if the folder should be collapsed when the folder note is opened')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.enableCollapsing)
.onChange(async (value) => {
this.excludedFolder.enableCollapsing = value;
await this.plugin.saveSettings();
})
);
}
if (!this.excludedFolder.disableFolderNote) {
new Setting(contentEl)
.setName('Collapse folder when opening folder note')
.setDesc('Choose if the folder should be collapsed when the folder note is opened')
.addToggle((toggle) =>
toggle
.setValue(this.excludedFolder.enableCollapsing)
.onChange(async (value) => {
this.excludedFolder.enableCollapsing = value;
await this.plugin.saveSettings();
})
);
}
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}

View file

@ -1,41 +1,40 @@
import { App, Modal, Setting, TFolder } from 'obsidian';
import FolderNotesPlugin from '../main';
export default class FolderNameModal extends Modal {
plugin: FolderNotesPlugin;
app: App;
folder: TFolder;
constructor(app: App, plugin: FolderNotesPlugin, folder: TFolder) {
super(app);
this.plugin = plugin;
this.app = app;
this.folder = folder;
}
onOpen() {
const { contentEl } = this;
// close when user presses enter
contentEl.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
this.close();
}
});
contentEl.createEl('h2', { text: 'Folder name' });
new Setting(contentEl)
.setName('Enter the name of the folder')
.addText((text) =>
text
.setValue(this.folder.name.replace('.md', ''))
.onChange(async (value) => {
if (value.trim() !== "") {
if (!this.app.vault.getAbstractFileByPath(this.folder.path.slice(0, this.folder.path.lastIndexOf('/') + 1) + value.trim()))
{
this.app.vault.rename(this.folder, this.folder.path.slice(0, this.folder.path.lastIndexOf('/') + 1) + value.trim());
}
}
})
);
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
plugin: FolderNotesPlugin;
app: App;
folder: TFolder;
constructor(app: App, plugin: FolderNotesPlugin, folder: TFolder) {
super(app);
this.plugin = plugin;
this.app = app;
this.folder = folder;
}
onOpen() {
const { contentEl } = this;
// close when user presses enter
contentEl.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
this.close();
}
});
contentEl.createEl('h2', { text: 'Folder name' });
new Setting(contentEl)
.setName('Enter the name of the folder')
.addText((text) =>
text
.setValue(this.folder.name.replace('.md', ''))
.onChange(async (value) => {
if (value.trim() !== '') {
if (!this.app.vault.getAbstractFileByPath(this.folder.path.slice(0, this.folder.path.lastIndexOf('/') + 1) + value.trim())) {
this.app.vault.rename(this.folder, this.folder.path.slice(0, this.folder.path.lastIndexOf('/') + 1) + value.trim());
}
}
})
);
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}

View file

@ -1,9 +1,9 @@
import { App, PluginSettingTab, Setting } from "obsidian";
import FolderNotesPlugin from "./main";
import { FolderSuggest } from "./suggesters/folderSuggester";
import ExcludedFolderSettings from "./modals/exludeFolderSettings";
import { TemplateSuggest } from "./suggesters/templateSuggester";
//import ConfirmationModal from "./modals/confirmCreation";
import { App, PluginSettingTab, Setting } from 'obsidian';
import FolderNotesPlugin from './main';
import { FolderSuggest } from './suggesters/folderSuggester';
import ExcludedFolderSettings from './modals/exludeFolderSettings';
import { TemplateSuggest } from './suggesters/templateSuggester';
// import ConfirmationModal from "./modals/confirmCreation";
export interface FolderNotesSettings {
syncFolderName: boolean;
ctrlKey: boolean;
@ -16,119 +16,119 @@ export interface FolderNotesSettings {
}
export const DEFAULT_SETTINGS: FolderNotesSettings = {
syncFolderName: true,
ctrlKey: true,
altKey: false,
hideFolderNote: false,
templatePath: '',
autoCreate: false,
enableCollapsing: false,
excludeFolders: [],
syncFolderName: true,
ctrlKey: true,
altKey: false,
hideFolderNote: false,
templatePath: '',
autoCreate: false,
enableCollapsing: false,
excludeFolders: [],
};
export class SettingsTab extends PluginSettingTab {
plugin: FolderNotesPlugin;
app: App;
excludeFolders: ExcludedFolder[];
constructor(app: App, plugin: FolderNotesPlugin) {
super(app, plugin);
}
display(): void {
const { containerEl } = this;
plugin: FolderNotesPlugin;
app: App;
excludeFolders: ExcludedFolder[];
constructor(app: App, plugin: FolderNotesPlugin) {
super(app, plugin);
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.empty();
containerEl.createEl('h2', { text: 'Folder notes settings' });
containerEl.createEl('h2', { text: 'Folder notes settings' });
new Setting(containerEl)
.setName('Disable folder collapsing')
.setDesc('Disable the ability to collapse folders by clicking on the folder name')
.addToggle((toggle) =>
toggle
.setValue(!this.plugin.settings.enableCollapsing)
.onChange(async (value) => {
this.plugin.settings.enableCollapsing = !value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Disable folder collapsing')
.setDesc('Disable the ability to collapse folders by clicking on the folder name')
.addToggle((toggle) =>
toggle
.setValue(!this.plugin.settings.enableCollapsing)
.onChange(async (value) => {
this.plugin.settings.enableCollapsing = !value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Hide folder note')
.setDesc('Hide the folder note in the file explorer')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.hideFolderNote)
.onChange(async (value) => {
this.plugin.settings.hideFolderNote = value;
await this.plugin.saveSettings();
if (value) {
document.body.classList.add('hide-folder-note');
} else {
document.body.classList.remove('hide-folder-note');
}
this.display();
})
);
new Setting(containerEl)
.setName('Sync folder name')
.setDesc('Automatically rename the folder note when the folder name is changed')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.syncFolderName)
.onChange(async (value) => {
this.plugin.settings.syncFolderName = value;
await this.plugin.saveSettings();
this.display();
})
);
new Setting(containerEl)
.setName('Auto create folder note')
.setDesc('Automatically create a folder note when a new folder is created')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.autoCreate)
.onChange(async (value) => {
this.plugin.settings.autoCreate = value;
await this.plugin.saveSettings();
this.display();
})
);
new Setting(containerEl)
.setName('Key for creating folder note')
.setDesc('The key combination to create a folder note')
.addDropdown((dropdown) => {
dropdown
.addOption('ctrl', 'Ctrl + Click')
.addOption('alt', 'Alt + Click')
.setValue(this.plugin.settings.ctrlKey ? 'ctrl' : 'alt')
.onChange(async (value) => {
this.plugin.settings.ctrlKey = value === 'ctrl';
this.plugin.settings.altKey = value === 'alt';
await this.plugin.saveSettings();
this.display();
});
});
new Setting(containerEl)
.setName('Hide folder note')
.setDesc('Hide the folder note in the file explorer')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.hideFolderNote)
.onChange(async (value) => {
this.plugin.settings.hideFolderNote = value;
await this.plugin.saveSettings();
if (value) {
document.body.classList.add('hide-folder-note');
} else {
document.body.classList.remove('hide-folder-note');
}
this.display();
})
);
new Setting(containerEl)
.setName('Sync folder name')
.setDesc('Automatically rename the folder note when the folder name is changed')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.syncFolderName)
.onChange(async (value) => {
this.plugin.settings.syncFolderName = value;
await this.plugin.saveSettings();
this.display();
})
);
new Setting(containerEl)
.setName('Auto create folder note')
.setDesc('Automatically create a folder note when a new folder is created')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.autoCreate)
.onChange(async (value) => {
this.plugin.settings.autoCreate = value;
await this.plugin.saveSettings();
this.display();
})
);
new Setting(containerEl)
.setName('Key for creating folder note')
.setDesc('The key combination to create a folder note')
.addDropdown((dropdown) => {
dropdown
.addOption('ctrl', 'Ctrl + Click')
.addOption('alt', 'Alt + Click')
.setValue(this.plugin.settings.ctrlKey ? 'ctrl' : 'alt')
.onChange(async (value) => {
this.plugin.settings.ctrlKey = value === 'ctrl';
this.plugin.settings.altKey = value === 'alt';
await this.plugin.saveSettings();
this.display();
});
});
new Setting(containerEl)
.setName('Template path')
.setDesc('The path to the template file')
.addSearch((cb) => {
new TemplateSuggest(cb.inputEl, this.plugin);
cb.setPlaceholder('Template path');
cb.setValue(this.plugin.app.vault.getAbstractFileByPath(this.plugin.settings.templatePath)?.name.replace('.md', '') || '');
cb.onChange(async (value) => {
if (value.trim() === '') {
this.plugin.settings.templatePath = '';
await this.plugin.saveSettings();
this.display();
return;
}
});
});
new Setting(containerEl)
.setName('Template path')
.setDesc('The path to the template file')
.addSearch((cb) => {
new TemplateSuggest(cb.inputEl, this.plugin);
cb.setPlaceholder('Template path');
cb.setValue(this.plugin.app.vault.getAbstractFileByPath(this.plugin.settings.templatePath)?.name.replace('.md', '') || '');
cb.onChange(async (value) => {
if (value.trim() === '') {
this.plugin.settings.templatePath = '';
await this.plugin.saveSettings();
this.display();
return;
}
});
});
// Due to issue with templater it'll be disabled for now
// If you want to try it yourself make a pr
// The issue was that it only used the first folder for all of the other folder notes
/*
// Due to issue with templater it'll be disabled for now
// If you want to try it yourself make a pr
// The issue was that it only used the first folder for all of the other folder notes
/*
new Setting(containerEl)
.setName('Create folder note for every folder')
.setDesc('Create a folder note for every folder in the vault')
@ -143,122 +143,122 @@ export class SettingsTab extends PluginSettingTab {
*/
new Setting(containerEl)
.setHeading()
.setName('Manage excluded folders')
new Setting(containerEl)
.setName('Add excluded folder')
.addButton(cb => {
cb.setIcon('plus');
cb.setClass('add-exclude-folder');
cb.setTooltip('Add excluded folder');
cb.onClick(() => {
const excludedFolder = new ExcludedFolder('', this.plugin.settings.excludeFolders.length);
this.addExcludeFolderListItem(containerEl, excludedFolder);
this.addExcludedFolder(excludedFolder);
this.display();
})
})
this.plugin.settings.excludeFolders.sort((a, b) => a.position - b.position).forEach((excludedFolder) => {
this.addExcludeFolderListItem(containerEl, excludedFolder);
})
}
addExcludeFolderListItem(containerEl: HTMLElement, excludedFolder: ExcludedFolder) {
const setting = new Setting(containerEl)
setting.setClass('fn-exclude-folder-list-item')
setting.addSearch(cb => {
new FolderSuggest(
cb.inputEl,
this.plugin
);
// @ts-ignore
cb.containerEl.addClass('fn-exclude-folder-path');
cb.setPlaceholder('Folder path');
cb.setValue(excludedFolder.path);
cb.onChange((value) => {
if (!this.app.vault.getAbstractFileByPath(value)) return;
excludedFolder.path = value;
this.updateExcludedFolder(excludedFolder, excludedFolder);
})
})
setting.addButton(cb => {
cb.setIcon('edit');
cb.setTooltip('Edit folder note');
cb.onClick(() => {
new ExcludedFolderSettings(this.app, this.plugin, excludedFolder).open();
})
})
new Setting(containerEl)
.setHeading()
.setName('Manage excluded folders');
new Setting(containerEl)
.setName('Add excluded folder')
.addButton((cb) => {
cb.setIcon('plus');
cb.setClass('add-exclude-folder');
cb.setTooltip('Add excluded folder');
cb.onClick(() => {
const excludedFolder = new ExcludedFolder('', this.plugin.settings.excludeFolders.length);
this.addExcludeFolderListItem(containerEl, excludedFolder);
this.addExcludedFolder(excludedFolder);
this.display();
});
});
this.plugin.settings.excludeFolders.sort((a, b) => a.position - b.position).forEach((excludedFolder) => {
this.addExcludeFolderListItem(containerEl, excludedFolder);
});
}
addExcludeFolderListItem(containerEl: HTMLElement, excludedFolder: ExcludedFolder) {
const setting = new Setting(containerEl);
setting.setClass('fn-exclude-folder-list-item');
setting.addSearch((cb) => {
new FolderSuggest(
cb.inputEl,
this.plugin
);
// @ts-ignore
cb.containerEl.addClass('fn-exclude-folder-path');
cb.setPlaceholder('Folder path');
cb.setValue(excludedFolder.path);
cb.onChange((value) => {
if (!this.app.vault.getAbstractFileByPath(value)) return;
excludedFolder.path = value;
this.updateExcludedFolder(excludedFolder, excludedFolder);
});
});
setting.addButton((cb) => {
cb.setIcon('edit');
cb.setTooltip('Edit folder note');
cb.onClick(() => {
new ExcludedFolderSettings(this.app, this.plugin, excludedFolder).open();
});
});
setting.addButton(cb => {
cb.setIcon('up-chevron-glyph');
cb.setTooltip('Move up');
cb.onClick(() => {
if (excludedFolder.position === 0) return;
excludedFolder.position = excludedFolder.position - 1;
this.updateExcludedFolder(excludedFolder, excludedFolder);
const oldExcludedFolder = this.plugin.settings.excludeFolders.find(folder => folder.position == excludedFolder.position)
if (oldExcludedFolder) {
setting.addButton((cb) => {
cb.setIcon('up-chevron-glyph');
cb.setTooltip('Move up');
cb.onClick(() => {
if (excludedFolder.position === 0) return;
excludedFolder.position -= 1;
this.updateExcludedFolder(excludedFolder, excludedFolder);
const oldExcludedFolder = this.plugin.settings.excludeFolders.find((folder) => folder.position === excludedFolder.position);
if (oldExcludedFolder) {
oldExcludedFolder.position = oldExcludedFolder.position + 1;
this.updateExcludedFolder(oldExcludedFolder, oldExcludedFolder);
}
this.display();
})
})
setting.addButton(cb => {
cb.setIcon('down-chevron-glyph');
cb.setTooltip('Move down');
cb.onClick(() => {
if (excludedFolder.position === this.plugin.settings.excludeFolders.length - 1) return;
excludedFolder.position = excludedFolder.position + 1;
this.updateExcludedFolder(excludedFolder, excludedFolder);
const oldExcludedFolder = this.plugin.settings.excludeFolders.find(folder => folder.position == excludedFolder.position)
if (oldExcludedFolder) {
oldExcludedFolder.position = oldExcludedFolder.position - 1;
this.updateExcludedFolder(oldExcludedFolder, oldExcludedFolder);
}
this.display();
})
})
setting.addButton(cb => {
cb.setIcon('trash-2');
cb.setTooltip('Delete excluded folder');
cb.onClick(() => {
this.deleteExcludedFolder(excludedFolder);
setting.clear();
setting.settingEl.remove();
})
})
}
addExcludedFolder(excludedFolder: ExcludedFolder) {
this.plugin.settings.excludeFolders.push(excludedFolder);
this.plugin.saveSettings();
}
deleteExcludedFolder(excludedFolder: ExcludedFolder) {
this.plugin.settings.excludeFolders = this.plugin.settings.excludeFolders.filter((folder) => folder.path !== excludedFolder.path);
this.plugin.saveSettings();
}
updateExcludedFolder(excludedFolder: ExcludedFolder, newExcludeFolder: ExcludedFolder) {
this.plugin.settings.excludeFolders = this.plugin.settings.excludeFolders.filter((folder) => folder.path !== excludedFolder.path);
this.addExcludedFolder(newExcludeFolder);
}
oldExcludedFolder.position += 1;
this.updateExcludedFolder(oldExcludedFolder, oldExcludedFolder);
}
this.display();
});
});
setting.addButton((cb) => {
cb.setIcon('down-chevron-glyph');
cb.setTooltip('Move down');
cb.onClick(() => {
if (excludedFolder.position === this.plugin.settings.excludeFolders.length - 1) return;
excludedFolder.position += 1;
this.updateExcludedFolder(excludedFolder, excludedFolder);
const oldExcludedFolder = this.plugin.settings.excludeFolders.find((folder) => folder.position === excludedFolder.position);
if (oldExcludedFolder) {
oldExcludedFolder.position -= 1;
this.updateExcludedFolder(oldExcludedFolder, oldExcludedFolder);
}
this.display();
});
});
setting.addButton((cb) => {
cb.setIcon('trash-2');
cb.setTooltip('Delete excluded folder');
cb.onClick(() => {
this.deleteExcludedFolder(excludedFolder);
setting.clear();
setting.settingEl.remove();
});
});
}
addExcludedFolder(excludedFolder: ExcludedFolder) {
this.plugin.settings.excludeFolders.push(excludedFolder);
this.plugin.saveSettings();
}
deleteExcludedFolder(excludedFolder: ExcludedFolder) {
this.plugin.settings.excludeFolders = this.plugin.settings.excludeFolders.filter((folder) => folder.path !== excludedFolder.path);
this.plugin.saveSettings();
}
updateExcludedFolder(excludedFolder: ExcludedFolder, newExcludeFolder: ExcludedFolder) {
this.plugin.settings.excludeFolders = this.plugin.settings.excludeFolders.filter((folder) => folder.path !== excludedFolder.path);
this.addExcludedFolder(newExcludeFolder);
}
}
export class ExcludedFolder {
path: string;
subFolders: boolean;
disableSync: boolean;
disableAutoCreate: boolean;
disableFolderNote: boolean;
enableCollapsing: boolean;
position: number;
constructor(path: string, position: number) {
this.path = path;
this.subFolders = true;
this.disableSync = true;
this.disableAutoCreate = true;
this.disableFolderNote = false;
this.enableCollapsing = false;
this.position = position;
}
}
path: string;
subFolders: boolean;
disableSync: boolean;
disableAutoCreate: boolean;
disableFolderNote: boolean;
enableCollapsing: boolean;
position: number;
constructor(path: string, position: number) {
this.path = path;
this.subFolders = true;
this.disableSync = true;
this.disableAutoCreate = true;
this.disableFolderNote = false;
this.enableCollapsing = false;
this.position = position;
}
}

View file

@ -1,54 +1,54 @@
// Credits go to Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes and https://github.com/SilentVoid13/Templater
import { TAbstractFile, TFile } from "obsidian";
import { TextInputSuggest } from "./suggest";
import FolderNotesPlugin from "../main";
import { TAbstractFile, TFile } from 'obsidian';
import { TextInputSuggest } from './suggest';
import FolderNotesPlugin from '../main';
export enum FileSuggestMode {
TemplateFiles,
ScriptFiles,
}
export class FileSuggest extends TextInputSuggest<TFile> {
constructor(
constructor(
public inputEl: HTMLInputElement,
private plugin: FolderNotesPlugin
) {
super(inputEl);
}
) {
super(inputEl);
}
get_error_msg(mode: FileSuggestMode): string {
switch (mode) {
case FileSuggestMode.TemplateFiles:
return `Templates folder doesn't exist`;
case FileSuggestMode.ScriptFiles:
return `User Scripts folder doesn't exist`;
}
}
get_error_msg(mode: FileSuggestMode): string {
switch (mode) {
case FileSuggestMode.TemplateFiles:
return 'Templates folder doesn\'t exist';
case FileSuggestMode.ScriptFiles:
return 'User Scripts folder doesn\'t exist';
}
}
getSuggestions(input_str: string): TFile[] {
const files: TFile[] = [];
const lower_input_str = input_str.toLowerCase();
getSuggestions(input_str: string): TFile[] {
const files: TFile[] = [];
const lower_input_str = input_str.toLowerCase();
this.plugin.app.vault.getFiles().forEach((file: TAbstractFile) => {
if (
file instanceof TFile &&
this.plugin.app.vault.getFiles().forEach((file: TAbstractFile) => {
if (
file instanceof TFile &&
file.path.toLowerCase().contains(lower_input_str)
) {
files.push(file);
}
});
) {
files.push(file);
}
});
return files;
}
return files;
}
renderSuggestion(file: TFile, el: HTMLElement): void {
el.setText(file.path);
}
renderSuggestion(file: TFile, el: HTMLElement): void {
el.setText(file.path);
}
selectSuggestion(file: TFile): void {
this.inputEl.value = file.path;
this.inputEl.trigger("input");
this.close();
}
}
selectSuggestion(file: TFile): void {
this.inputEl.value = file.path;
this.inputEl.trigger('input');
this.close();
}
}

View file

@ -1,54 +1,54 @@
// Credits go to Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes and https://github.com/SilentVoid13/Templater
import { TAbstractFile, TFolder } from "obsidian";
import { TextInputSuggest } from "./suggest";
import FolderNotesPlugin from "../main";
import { TAbstractFile, TFolder } from 'obsidian';
import { TextInputSuggest } from './suggest';
import FolderNotesPlugin from '../main';
export enum FileSuggestMode {
TemplateFiles,
ScriptFiles,
}
export class FolderSuggest extends TextInputSuggest<TFolder> {
constructor(
constructor(
public inputEl: HTMLInputElement,
private plugin: FolderNotesPlugin
) {
super(inputEl);
}
) {
super(inputEl);
}
get_error_msg(mode: FileSuggestMode): string {
switch (mode) {
case FileSuggestMode.TemplateFiles:
return `Templates folder doesn't exist`;
case FileSuggestMode.ScriptFiles:
return `User Scripts folder doesn't exist`;
}
}
get_error_msg(mode: FileSuggestMode): string {
switch (mode) {
case FileSuggestMode.TemplateFiles:
return 'Templates folder doesn\'t exist';
case FileSuggestMode.ScriptFiles:
return 'User Scripts folder doesn\'t exist';
}
}
getSuggestions(input_str: string): TFolder[] {
const folders: TFolder[] = [];
const lower_input_str = input_str.toLowerCase();
this.plugin.app.vault.getAllLoadedFiles().forEach((folder: TAbstractFile) => {
if (
folder instanceof TFolder &&
getSuggestions(input_str: string): TFolder[] {
const folders: TFolder[] = [];
const lower_input_str = input_str.toLowerCase();
this.plugin.app.vault.getAllLoadedFiles().forEach((folder: TAbstractFile) => {
if (
folder instanceof TFolder &&
folder.path.toLowerCase().contains(lower_input_str) &&
!this.plugin.settings.excludeFolders.find(f => f.path === folder.path)
) {
folders.push(folder);
}
});
!this.plugin.settings.excludeFolders.find((f) => f.path === folder.path)
) {
folders.push(folder);
}
});
return folders;
}
return folders;
}
renderSuggestion(folder: TFolder, el: HTMLElement): void {
el.setText(folder.path);
}
renderSuggestion(folder: TFolder, el: HTMLElement): void {
el.setText(folder.path);
}
selectSuggestion(folder: TFolder): void {
this.inputEl.value = folder.path;
this.inputEl.trigger("input");
this.close();
}
}
selectSuggestion(folder: TFolder): void {
this.inputEl.value = folder.path;
this.inputEl.trigger('input');
this.close();
}
}

View file

@ -1,202 +1,202 @@
// Credits go to Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes and https://github.com/SilentVoid13/Templater
import { ISuggestOwner, Scope } from "obsidian";
import { createPopper, Instance as PopperInstance } from "@popperjs/core";
import { ISuggestOwner, Scope } from 'obsidian';
import { createPopper, Instance as PopperInstance } from '@popperjs/core';
const wrapAround = (value: number, size: number): number => {
return ((value % size) + size) % size;
return ((value % size) + size) % size;
};
class Suggest<T> {
private owner: ISuggestOwner<T>;
private values: T[];
private suggestions: HTMLDivElement[];
private selectedItem: number;
private containerEl: HTMLElement;
private owner: ISuggestOwner<T>;
private values: T[];
private suggestions: HTMLDivElement[];
private selectedItem: number;
private containerEl: HTMLElement;
constructor(
owner: ISuggestOwner<T>,
containerEl: HTMLElement,
scope: Scope
) {
this.owner = owner;
this.containerEl = containerEl;
constructor(
owner: ISuggestOwner<T>,
containerEl: HTMLElement,
scope: Scope
) {
this.owner = owner;
this.containerEl = containerEl;
containerEl.on(
"click",
".suggestion-item",
this.onSuggestionClick.bind(this)
);
containerEl.on(
"mousemove",
".suggestion-item",
this.onSuggestionMouseover.bind(this)
);
containerEl.on(
'click',
'.suggestion-item',
this.onSuggestionClick.bind(this)
);
containerEl.on(
'mousemove',
'.suggestion-item',
this.onSuggestionMouseover.bind(this)
);
scope.register([], "ArrowUp", (event) => {
if (!event.isComposing) {
this.setSelectedItem(this.selectedItem - 1, true);
return false;
}
});
scope.register([], 'ArrowUp', (event) => {
if (!event.isComposing) {
this.setSelectedItem(this.selectedItem - 1, true);
return false;
}
});
scope.register([], "ArrowDown", (event) => {
if (!event.isComposing) {
this.setSelectedItem(this.selectedItem + 1, true);
return false;
}
});
scope.register([], 'ArrowDown', (event) => {
if (!event.isComposing) {
this.setSelectedItem(this.selectedItem + 1, true);
return false;
}
});
scope.register([], "Enter", (event) => {
if (!event.isComposing) {
this.useSelectedItem(event);
return false;
}
});
}
scope.register([], 'Enter', (event) => {
if (!event.isComposing) {
this.useSelectedItem(event);
return false;
}
});
}
onSuggestionClick(event: MouseEvent, el: HTMLDivElement): void {
event.preventDefault();
onSuggestionClick(event: MouseEvent, el: HTMLDivElement): void {
event.preventDefault();
const item = this.suggestions.indexOf(el);
this.setSelectedItem(item, false);
this.useSelectedItem(event);
}
const item = this.suggestions.indexOf(el);
this.setSelectedItem(item, false);
this.useSelectedItem(event);
}
onSuggestionMouseover(_event: MouseEvent, el: HTMLDivElement): void {
const item = this.suggestions.indexOf(el);
this.setSelectedItem(item, false);
}
onSuggestionMouseover(_event: MouseEvent, el: HTMLDivElement): void {
const item = this.suggestions.indexOf(el);
this.setSelectedItem(item, false);
}
setSuggestions(values: T[]) {
this.containerEl.empty();
const suggestionEls: HTMLDivElement[] = [];
setSuggestions(values: T[]) {
this.containerEl.empty();
const suggestionEls: HTMLDivElement[] = [];
values.forEach((value) => {
const suggestionEl = this.containerEl.createDiv("suggestion-item");
this.owner.renderSuggestion(value, suggestionEl);
suggestionEls.push(suggestionEl);
});
values.forEach((value) => {
const suggestionEl = this.containerEl.createDiv('suggestion-item');
this.owner.renderSuggestion(value, suggestionEl);
suggestionEls.push(suggestionEl);
});
this.values = values;
this.suggestions = suggestionEls;
this.setSelectedItem(0, false);
}
this.values = values;
this.suggestions = suggestionEls;
this.setSelectedItem(0, false);
}
useSelectedItem(event: MouseEvent | KeyboardEvent) {
const currentValue = this.values[this.selectedItem];
if (currentValue) {
this.owner.selectSuggestion(currentValue, event);
}
}
useSelectedItem(event: MouseEvent | KeyboardEvent) {
const currentValue = this.values[this.selectedItem];
if (currentValue) {
this.owner.selectSuggestion(currentValue, event);
}
}
setSelectedItem(selectedIndex: number, scrollIntoView: boolean) {
const normalizedIndex = wrapAround(
selectedIndex,
this.suggestions.length
);
const prevSelectedSuggestion = this.suggestions[this.selectedItem];
const selectedSuggestion = this.suggestions[normalizedIndex];
setSelectedItem(selectedIndex: number, scrollIntoView: boolean) {
const normalizedIndex = wrapAround(
selectedIndex,
this.suggestions.length
);
const prevSelectedSuggestion = this.suggestions[this.selectedItem];
const selectedSuggestion = this.suggestions[normalizedIndex];
prevSelectedSuggestion?.removeClass("is-selected");
selectedSuggestion?.addClass("is-selected");
prevSelectedSuggestion?.removeClass('is-selected');
selectedSuggestion?.addClass('is-selected');
this.selectedItem = normalizedIndex;
this.selectedItem = normalizedIndex;
if (scrollIntoView) {
selectedSuggestion.scrollIntoView(false);
}
}
if (scrollIntoView) {
selectedSuggestion.scrollIntoView(false);
}
}
}
export abstract class TextInputSuggest<T> implements ISuggestOwner<T> {
protected inputEl: HTMLInputElement | HTMLTextAreaElement;
protected inputEl: HTMLInputElement | HTMLTextAreaElement;
private popper: PopperInstance;
private scope: Scope;
private suggestEl: HTMLElement;
private suggest: Suggest<T>;
private popper: PopperInstance;
private scope: Scope;
private suggestEl: HTMLElement;
private suggest: Suggest<T>;
constructor(inputEl: HTMLInputElement | HTMLTextAreaElement) {
this.inputEl = inputEl;
this.scope = new Scope();
constructor(inputEl: HTMLInputElement | HTMLTextAreaElement) {
this.inputEl = inputEl;
this.scope = new Scope();
this.suggestEl = createDiv("suggestion-container");
const suggestion = this.suggestEl.createDiv("suggestion");
this.suggest = new Suggest(this, suggestion, this.scope);
this.suggestEl = createDiv('suggestion-container');
const suggestion = this.suggestEl.createDiv('suggestion');
this.suggest = new Suggest(this, suggestion, this.scope);
this.scope.register([], "Escape", this.close.bind(this));
this.scope.register([], 'Escape', this.close.bind(this));
this.inputEl.addEventListener("input", this.onInputChanged.bind(this));
this.inputEl.addEventListener("focus", this.onInputChanged.bind(this));
this.inputEl.addEventListener("blur", this.close.bind(this));
this.suggestEl.on(
"mousedown",
".suggestion-container",
(event: MouseEvent) => {
event.preventDefault();
}
);
}
this.inputEl.addEventListener('input', this.onInputChanged.bind(this));
this.inputEl.addEventListener('focus', this.onInputChanged.bind(this));
this.inputEl.addEventListener('blur', this.close.bind(this));
this.suggestEl.on(
'mousedown',
'.suggestion-container',
(event: MouseEvent) => {
event.preventDefault();
}
);
}
onInputChanged(): void {
const inputStr = this.inputEl.value;
const suggestions = this.getSuggestions(inputStr);
onInputChanged(): void {
const inputStr = this.inputEl.value;
const suggestions = this.getSuggestions(inputStr);
if (!suggestions) {
this.close();
return;
}
if (!suggestions) {
this.close();
return;
}
if (suggestions.length > 0) {
this.suggest.setSuggestions(suggestions);
// @ts-ignore
this.open(app.dom.appContainerEl, this.inputEl);
} else {
this.close();
}
}
if (suggestions.length > 0) {
this.suggest.setSuggestions(suggestions);
// @ts-ignore
this.open(app.dom.appContainerEl, this.inputEl);
} else {
this.close();
}
}
open(container: HTMLElement, inputEl: HTMLElement): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
app.keymap.pushScope(this.scope);
open(container: HTMLElement, inputEl: HTMLElement): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
app.keymap.pushScope(this.scope);
container.appendChild(this.suggestEl);
this.popper = createPopper(inputEl, this.suggestEl, {
placement: "bottom-start",
modifiers: [
{
name: "sameWidth",
enabled: true,
fn: ({ state, instance }) => {
// Note: positioning needs to be calculated twice -
// first pass - positioning it according to the width of the popper
// second pass - position it with the width bound to the reference element
// we need to early exit to avoid an infinite loop
const targetWidth = `${state.rects.reference.width}px`;
if (state.styles.popper.width === targetWidth) {
return;
}
state.styles.popper.width = targetWidth;
instance.update();
},
phase: "beforeWrite",
requires: ["computeStyles"],
},
],
});
}
container.appendChild(this.suggestEl);
this.popper = createPopper(inputEl, this.suggestEl, {
placement: 'bottom-start',
modifiers: [
{
name: 'sameWidth',
enabled: true,
fn: ({ state, instance }) => {
// Note: positioning needs to be calculated twice -
// first pass - positioning it according to the width of the popper
// second pass - position it with the width bound to the reference element
// we need to early exit to avoid an infinite loop
const targetWidth = `${state.rects.reference.width}px`;
if (state.styles.popper.width === targetWidth) {
return;
}
state.styles.popper.width = targetWidth;
instance.update();
},
phase: 'beforeWrite',
requires: ['computeStyles'],
},
],
});
}
close(): void {
app.keymap.popScope(this.scope);
close(): void {
app.keymap.popScope(this.scope);
this.suggest.setSuggestions([]);
if (this.popper) this.popper.destroy();
this.suggestEl.detach();
}
this.suggest.setSuggestions([]);
if (this.popper) this.popper.destroy();
this.suggestEl.detach();
}
abstract getSuggestions(inputStr: string): T[];
abstract renderSuggestion(item: T, el: HTMLElement): void;
abstract selectSuggestion(item: T): void;
}
}

View file

@ -1,70 +1,70 @@
// Credits go to Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes and https://github.com/SilentVoid13/Templater
import { TAbstractFile, TFile, TFolder, Vault } from "obsidian";
import { TextInputSuggest } from "./suggest";
import FolderNotesPlugin from "../main";
import { getTemplatePlugins } from "src/template";
import { TAbstractFile, TFile, TFolder, Vault } from 'obsidian';
import { TextInputSuggest } from './suggest';
import FolderNotesPlugin from '../main';
import { getTemplatePlugins } from 'src/template';
export enum FileSuggestMode {
TemplateFiles,
ScriptFiles,
}
export class TemplateSuggest extends TextInputSuggest<TFile> {
constructor(
constructor(
public inputEl: HTMLInputElement,
private plugin: FolderNotesPlugin
) {
super(inputEl);
}
) {
super(inputEl);
}
get_error_msg(mode: FileSuggestMode): string {
switch (mode) {
case FileSuggestMode.TemplateFiles:
return `Templates folder doesn't exist`;
case FileSuggestMode.ScriptFiles:
return `User Scripts folder doesn't exist`;
}
}
get_error_msg(mode: FileSuggestMode): string {
switch (mode) {
case FileSuggestMode.TemplateFiles:
return 'Templates folder doesn\'t exist';
case FileSuggestMode.ScriptFiles:
return 'User Scripts folder doesn\'t exist';
}
}
getSuggestions(input_str: string): TFile[] {
const { templateFolder, templaterPlugin } = getTemplatePlugins(this.plugin.app);
if ((!templateFolder || templateFolder?.trim() === "") && !templaterPlugin) {
this.plugin.settings.templatePath = "";
this.plugin.saveSettings();
return [];
}
let folder: TFolder;
if (templaterPlugin) {
folder = this.plugin.app.vault.getAbstractFileByPath(templaterPlugin.plugin?.settings?.templates_folder as string) as TFolder;
} else {
folder = this.plugin.app.vault.getAbstractFileByPath(templateFolder) as TFolder;
}
getSuggestions(input_str: string): TFile[] {
const { templateFolder, templaterPlugin } = getTemplatePlugins(this.plugin.app);
if ((!templateFolder || templateFolder?.trim() === '') && !templaterPlugin) {
this.plugin.settings.templatePath = '';
this.plugin.saveSettings();
return [];
}
let folder: TFolder;
if (templaterPlugin) {
folder = this.plugin.app.vault.getAbstractFileByPath(templaterPlugin.plugin?.settings?.templates_folder as string) as TFolder;
const files: TFile[] = [];
const lower_input_str = input_str.toLowerCase();
} else {
folder = this.plugin.app.vault.getAbstractFileByPath(templateFolder) as TFolder;
}
Vault.recurseChildren(folder, (file: TAbstractFile) => {
if (file instanceof TFile &&
const files: TFile[] = [];
const lower_input_str = input_str.toLowerCase();
Vault.recurseChildren(folder, (file: TAbstractFile) => {
if (file instanceof TFile &&
file.path.toLowerCase().contains(lower_input_str)
) {
files.push(file);
}
});
) {
files.push(file);
}
});
return files;
}
return files;
}
renderSuggestion(file: TFile, el: HTMLElement): void {
el.setText(file.name.replace(".md", ""));
}
renderSuggestion(file: TFile, el: HTMLElement): void {
el.setText(file.name.replace('.md', ''));
}
selectSuggestion(file: TFile): void {
this.inputEl.value = file.name.replace(".md", "");
this.inputEl.trigger("input");
this.plugin.settings.templatePath = file.path;
this.plugin.saveSettings();
this.close();
}
}
selectSuggestion(file: TFile): void {
this.inputEl.value = file.name.replace('.md', '');
this.inputEl.trigger('input');
this.plugin.settings.templatePath = file.path;
this.plugin.saveSettings();
this.close();
}
}

View file

@ -5,78 +5,78 @@
import { TFile, App } from 'obsidian';
import FolderNotesPlugin from './main';
export async function applyTemplate(
plugin: FolderNotesPlugin,
file: TFile,
templatePath?: string
plugin: FolderNotesPlugin,
file: TFile,
templatePath?: string
) {
const templateFile = templatePath
? plugin.app.vault.getAbstractFileByPath(templatePath)
: null;
const templateFile = templatePath
? plugin.app.vault.getAbstractFileByPath(templatePath)
: null;
if (templateFile && templateFile instanceof TFile) {
try {
if (templateFile && templateFile instanceof TFile) {
try {
const {
templatesEnabled,
templaterEnabled,
templatesPlugin,
templaterPlugin,
} = getTemplatePlugins(plugin.app);
const templateContent = await plugin.app.vault.read(templateFile);
const {
templatesEnabled,
templaterEnabled,
templatesPlugin,
templaterPlugin,
} = getTemplatePlugins(plugin.app);
const templateContent = await plugin.app.vault.read(templateFile);
// If both plugins are enabled, attempt to detect templater first
// If both plugins are enabled, attempt to detect templater first
if (templatesEnabled && templaterEnabled) {
if (/<%/.test(templateContent)) {
return await templaterPlugin.write_template_to_file(
templateFile,
file
);
}
return await templatesPlugin.instance.insertTemplate(templateFile);
}
if (templatesEnabled && templaterEnabled) {
if (/<%/.test(templateContent)) {
return await templaterPlugin.write_template_to_file(
templateFile,
file
);
}
return await templatesPlugin.instance.insertTemplate(templateFile);
}
if (templatesEnabled) {
return await templatesPlugin.instance.insertTemplate(templateFile);
}
if (templatesEnabled) {
return await templatesPlugin.instance.insertTemplate(templateFile);
}
if (templaterEnabled) {
return await templaterPlugin.write_template_to_file(
templateFile,
file
);
}
if (templaterEnabled) {
return await templaterPlugin.write_template_to_file(
templateFile,
file
);
}
} catch (e) {
console.error(e);
}
}
} catch (e) {
console.error(e);
}
}
}
export function getTemplatePlugins(app: App) {
const templatesPlugin = (app as any).internalPlugins.plugins.templates;
const templatesEnabled = templatesPlugin.enabled;
const templaterPlugin = (app as any).plugins.plugins['templater-obsidian'];
const templaterEnabled = (app as any).plugins.enabledPlugins.has(
'templater-obsidian'
);
const templaterEmptyFileTemplate =
templaterPlugin &&
(this.app as any).plugins.plugins['templater-obsidian'].settings
?.empty_file_template;
const templatesPlugin = (app as any).internalPlugins.plugins.templates;
const templatesEnabled = templatesPlugin.enabled;
const templaterPlugin = (app as any).plugins.plugins['templater-obsidian'];
const templaterEnabled = (app as any).plugins.enabledPlugins.has(
'templater-obsidian'
);
const templaterEmptyFileTemplate =
templaterPlugin &&
(this.app as any).plugins.plugins['templater-obsidian'].settings
?.empty_file_template;
const templateFolder = templatesEnabled
? templatesPlugin.instance.options.folder
: templaterPlugin
? templaterPlugin.settings.template_folder
: undefined;
const templateFolder = templatesEnabled
? templatesPlugin.instance.options.folder
: templaterPlugin
? templaterPlugin.settings.template_folder
: undefined;
return {
templatesPlugin,
templatesEnabled,
templaterPlugin: templaterPlugin?.templater,
templaterEnabled,
templaterEmptyFileTemplate,
templateFolder,
};
}
return {
templatesPlugin,
templatesEnabled,
templaterPlugin: templaterPlugin?.templater,
templaterEnabled,
templaterEmptyFileTemplate,
templateFolder,
};
}