generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.ts
331 lines (281 loc) · 13.9 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import {App, Plugin, PluginSettingTab, setIcon, Setting, debounce} from "obsidian";
import {CompatQuickExplorer} from "./compat/compat-quickexplorer";
export interface HideFoldersPluginSettings {
areFoldersHidden: boolean;
matchCaseInsensitive: boolean;
addHiddenFoldersToObsidianIgnoreList: boolean;
hideBottomStatusBarIndicatorText: boolean;
enableCompatQuickExplorer: boolean;
attachmentFolderNames: string[];
}
const DEFAULT_SETTINGS: HideFoldersPluginSettings = {
areFoldersHidden: true,
matchCaseInsensitive: true,
addHiddenFoldersToObsidianIgnoreList: false,
hideBottomStatusBarIndicatorText: false,
enableCompatQuickExplorer: false,
attachmentFolderNames: ["attachments"],
};
export default class HideFoldersPlugin extends Plugin {
settings: HideFoldersPluginSettings;
ribbonIconButton: HTMLElement;
statusBarItem?: HTMLElement;
mutationObserver: MutationObserver;
private processFolders = debounce(async (recheckPreviouslyHiddenFolders?: boolean) => {
if(this.settings.attachmentFolderNames.length === 0) return;
if(recheckPreviouslyHiddenFolders) {
document.querySelectorAll<HTMLElement>(".obsidian-hide-folders--hidden").forEach((folder) => {
folder.style.height = "";
folder.style.overflow = "";
folder.removeClass("obsidian-hide-folders--hidden");
});
}
this.settings.attachmentFolderNames.forEach(folderName => {
if(getFolderNameWithoutPrefix(folderName) === "") return;
const folderElements = document.querySelectorAll<HTMLElement>([
this.getQuerySelectorStringForFolderName(folderName),
this.settings.enableCompatQuickExplorer ? CompatQuickExplorer.getAdditionalDocumentSelectorStringForFolder?.(folderName, this.settings) : null,
].filter((o) => o != null).join(", "));
folderElements.forEach((folder) => {
if (!folder) {
return;
}
folder.addClass("obsidian-hide-folders--hidden");
folder.style.height = this.settings.areFoldersHidden ? "0" : "";
folder.style.display = this.settings.areFoldersHidden ? "none" : "";
folder.style.overflow = this.settings.areFoldersHidden ? "hidden" : "";
});
});
}, 10, false);
getQuerySelectorStringForFolderName(folderName: string) {
if(folderName.toLowerCase().startsWith("endswith::")) {
return `*:has(> [data-path$="${getFolderNameWithoutPrefix(folderName)}"${this.settings.matchCaseInsensitive ? " i" : ""}])`;
} else if(folderName.toLowerCase().startsWith("startswith::")) {
return `*:has(> .nav-folder-title[data-path^="${getFolderNameWithoutPrefix(folderName)}"${this.settings.matchCaseInsensitive ? " i" : ""}]), *:has(> .nav-folder-title[data-path*="/${getFolderNameWithoutPrefix(folderName)}"${this.settings.matchCaseInsensitive ? " i" : ""}])`;
} else {
return `*:has(> [data-path$="/${folderName.trim()}"${this.settings.matchCaseInsensitive ? " i" : ""}]), *:has(> [data-path="${folderName.trim()}"${this.settings.matchCaseInsensitive ? " i" : ""}])`;
}
}
async toggleFunctionality() {
this.settings.areFoldersHidden = !this.settings.areFoldersHidden;
this.ribbonIconButton.ariaLabel = this.settings.areFoldersHidden ? "Show hidden folders" : "Hide hidden folders again";
setIcon(this.ribbonIconButton, this.settings.areFoldersHidden ? "eye" : "eye-off");
if(this.statusBarItem) {
this.statusBarItem.innerHTML = this.settings.areFoldersHidden ? "Configured folders are hidden" : "";
}
await this.processFolders();
await this.saveSettings();
await this.updateObsidianIgnoreList();
}
createIgnoreListRegExpForFolderName(rawFolderName: string) {
const folderName = this.settings.matchCaseInsensitive
? getFolderNameWithoutPrefix(rawFolderName).split("").map(c => c.toLowerCase() != c.toUpperCase() ? `[${c.toLowerCase()}${c.toUpperCase()}]` : c).join("")
: getFolderNameWithoutPrefix(rawFolderName);
if(rawFolderName.toLowerCase().startsWith("endswith::")) {
return `/(${folderName}$)|(${folderName}/)/`;
} else if(rawFolderName.toLowerCase().startsWith("startswith::")) {
return `/(^${folderName})|(/${folderName})/`;
} else {
return `/${folderName}/`;
}
}
async updateObsidianIgnoreList(processFeatureDisabling?: boolean) {
if(!this.settings.addHiddenFoldersToObsidianIgnoreList && !processFeatureDisabling) return;
// @ts-ignore
let ignoreList = (this.app.vault.getConfig("userIgnoreFilters") ?? []) as string[];
if (this.settings.areFoldersHidden && !processFeatureDisabling) {
this.settings.attachmentFolderNames.forEach(folderName => {
if(getFolderNameWithoutPrefix(folderName).trim() === "") return;
if(ignoreList.contains(this.createIgnoreListRegExpForFolderName(folderName))) return;
ignoreList.push(this.createIgnoreListRegExpForFolderName(folderName));
});
} else {
const folderNameRegexes = this.settings.attachmentFolderNames.map(folderName => this.createIgnoreListRegExpForFolderName(folderName));
ignoreList = ignoreList.filter((s) => !folderNameRegexes.includes(s));
}
// @ts-ignore
this.app.vault.setConfig("userIgnoreFilters", ignoreList);
}
async removeSpecificFoldersFromObsidianIgnoreList(folderNames: string[]) {
folderNames.forEach(folderName => {
// @ts-ignore
this.app.vault.config.userIgnoreFilters?.remove(this.createIgnoreListRegExpForFolderName(folderName));
this.app.vault.trigger("config-changed");
});
}
createBottomStatusBarIndicatorTextItem() {
if(this.statusBarItem) return; // prevent multiple instantiations
// This adds a status bar item to the bottom of the app.
this.statusBarItem = this.addStatusBarItem();
this.statusBarItem.setText(this.settings.areFoldersHidden ? "Configured folders are hidden" : "");
}
async onload() {
console.log("loading plugin hide-folders");
await this.loadSettings();
// This creates an icon in the left ribbon.
this.ribbonIconButton = this.addRibbonIcon(this.settings.areFoldersHidden ? "eye" : "eye-off", this.settings.areFoldersHidden ? "Show hidden folders" : "Hide hidden folders again", (evt: MouseEvent) => {
this.toggleFunctionality();
});
if(!this.settings.hideBottomStatusBarIndicatorText) {
this.createBottomStatusBarIndicatorTextItem();
}
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: "toggle-attachment-folders",
name: "Toggle visibility of hidden folders",
callback: () => {
this.toggleFunctionality();
},
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new HideFoldersPluginSettingTab(this.app, this));
// used for re-processing folders when a folder is expanded in the file-navigator
this.mutationObserver = new MutationObserver((mutationRecord) => {
const feClasses = [
"nav-folder",
"nav-files-container",
];
// check if any of the mutationRecords fulfills the conditions for us to call processFolders
const shouldTriggerProcessFolders = mutationRecord.some((record) => {
if(feClasses.some(c => record.target?.parentElement?.classList.contains(c))) return true;
if(this.settings.enableCompatQuickExplorer && CompatQuickExplorer.shouldMutationRecordTriggerFolderReProcessing?.(record)) return true;
return false;
});
if(!shouldTriggerProcessFolders) return;
this.processFolders();
});
this.mutationObserver.observe(window.document, {childList: true, subtree: true});
// used for re-processing folders when a folder is newly created or renamed
this.registerEvent(this.app.vault.on("rename", () => {
// small delay is needed, otherwise the new folder won't get picked-up yet when calling processFolders
window.setTimeout(() => {
this.processFolders();
}, 10);
}));
this.app.workspace.onLayoutReady(() => {
if(!this.settings.areFoldersHidden) return;
window.setTimeout(() => {
this.processFolders();
}, 1000);
});
}
onunload() {
this.mutationObserver.disconnect();
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
await this.processFolders(true);
}
}
class HideFoldersPluginSettingTab extends PluginSettingTab {
plugin: HideFoldersPlugin;
constructor(app: App, plugin: HideFoldersPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
const experimentalSettingsContainerEl = document.createElement("details");
const experimentalSettingsTitleEl = document.createElement("summary");
experimentalSettingsTitleEl.innerText = "Experimental & Unstable Settings";
experimentalSettingsContainerEl.appendChild(experimentalSettingsTitleEl);
new Setting(containerEl)
.setName("Folders to hide")
.setDesc("The names of the folders to hide, one per line. Either exact folder-names, startsWith::FOLDERPREFIX, or endsWith::FOLDERSUFFIX")
.addTextArea(text => text
.setPlaceholder("attachments\nendsWith::_attachments")
.setValue(this.plugin.settings.attachmentFolderNames.join("\n"))
.onChange(async (value) => {
const newSettingsValue = value.split("\n");
// remove removed folders from exclude list too
await this.plugin.removeSpecificFoldersFromObsidianIgnoreList(this.plugin.settings.attachmentFolderNames.filter(e => !newSettingsValue.includes(e)));
this.plugin.settings.attachmentFolderNames = newSettingsValue;
await this.plugin.saveSettings();
await this.plugin.updateObsidianIgnoreList();
}));
new Setting(containerEl)
.setName("Ignore Upper/lowercase")
.setDesc("If enabled, 'SOMEFOLDER', 'someFolder', or 'sOmeFoldEr' will all be treated the same and matched.")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.matchCaseInsensitive)
.onChange(async (value) => {
// remove all folders and re-add them later in the update function
await this.plugin.removeSpecificFoldersFromObsidianIgnoreList(this.plugin.settings.attachmentFolderNames);
this.plugin.settings.matchCaseInsensitive = value;
await this.plugin.saveSettings();
await this.plugin.updateObsidianIgnoreList();
}));
new Setting(containerEl)
.setName("Hide folders")
.setDesc("If the configured folders should be hidden or not")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.areFoldersHidden)
.onChange(async (value) => {
this.plugin.settings.areFoldersHidden = value;
await this.plugin.saveSettings();
await this.plugin.updateObsidianIgnoreList();
}));
new Setting(containerEl)
.setName("Add Hidden Folders to Obsidian Exclusion-List")
.setDesc("Excluded files will be hidden in Search, Graph View, and Unlinked Mentions, less noticeable in Quick Switcher and link suggestions.")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.addHiddenFoldersToObsidianIgnoreList)
.onChange(async (value) => {
this.plugin.settings.addHiddenFoldersToObsidianIgnoreList = value;
await this.plugin.saveSettings();
await this.plugin.updateObsidianIgnoreList(!value);
}));
new Setting(containerEl)
.setName("Hide bottom status-bar \"Folders are Hidden\" indicator")
.setDesc("If enable there will be no bottom-bar indicator-text telling you if this plugin is active.")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.hideBottomStatusBarIndicatorText)
.onChange(async (value) => {
this.plugin.settings.hideBottomStatusBarIndicatorText = value;
if(value) {
this.plugin.statusBarItem?.remove();
this.plugin.statusBarItem = undefined;
} else {
this.plugin.createBottomStatusBarIndicatorTextItem();
}
await this.plugin.saveSettings();
}));
new Setting(experimentalSettingsContainerEl)
.setName("[EXPERIMENTAL] Compatibility: quick-explorer by pjeby")
.setDesc("[WARNING: UNSTABLE] Also hide hidden folders in the https://github.com/pjeby/quick-explorer plugin. Not affiliated with quick-explorer's author.")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.enableCompatQuickExplorer)
.onChange(async (value) => {
this.plugin.settings.enableCompatQuickExplorer = value;
await this.plugin.saveSettings();
}));
containerEl.appendChild(document.createElement("br"));
new Setting(containerEl)
.setName("GitHub")
.setDesc("Report Issues or Ideas, see the Source Code and Contribute.")
.addButton(button => button
.buttonEl.innerHTML = '<a href="https://github.com/JonasDoesThings/obsidian-hide-folders" target="_blank">obsidian-hide-folders</a>'
);
new Setting(containerEl)
.setName("Donate")
.setDesc("If you like this open-source plugin, consider a small tip to support my unpaid work.")
.addButton((button) => button
.buttonEl.outerHTML = "<a href='https://www.buymeacoffee.com/jonasdoesthings' target='_blank'><img src='https://cdn.buymeacoffee.com/buttons/default-orange.png' alt='Buy Me A Coffee' height='27' width='116'></a>"
);
containerEl.appendChild(document.createElement("br"));
containerEl.appendChild(experimentalSettingsContainerEl);
}
}
export function getFolderNameWithoutPrefix(folderName: string) {
if (folderName.toLowerCase().startsWith("endswith::")) {
return folderName.substring("endsWith::".length).trim();
} else if (folderName.toLowerCase().startsWith("startswith::")) {
return folderName.substring("startsWith::".length).trim();
} else {
return folderName;
}
}