generated from Quorafind/Obsidian-Custom-Plugin-Starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbetterDefaultSetting.ts
336 lines (285 loc) · 9.89 KB
/
betterDefaultSetting.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
332
333
334
335
336
import {
Plugin,
setIcon,
SettingTab,
Setting,
PluginManifest,
ExtraButtonComponent,
App,
Modal,
Notice,
normalizePath
} from 'obsidian';
import {around} from "monkey-around";
declare module "obsidian" {
interface App {
internalPlugins: {
plugins: Record<string,
{ _loaded: boolean; instance: { name: string; id: string } }>;
};
plugins: {
manifests: Record<string, PluginManifest>;
plugins: Record<string, Plugin>;
};
setting: {
activeTab: SettingTab;
lastTabId: string;
pluginTabs: PluginSettingTab[];
settingTabs: SettingTab[];
tabContentContainer: HTMLDivElement;
tabHeadersEl: HTMLDivElement;
};
customCss: any;
showInFolder(path: string): void;
openWithDefaultApp(path: string): void;
}
interface Plugin {
_loaded: boolean;
}
interface PluginSettingTab {
name: string;
}
interface SettingTab {
id: string;
name: string;
navEl: HTMLElement;
}
}
export interface BetterDefaultSettingPluginSettings {
filter: boolean;
}
export const DEFAULT_SETTINGS: BetterDefaultSettingPluginSettings = {
filter: false,
}
export default class BetterDefaultSettingPlugin extends Plugin {
settings: BetterDefaultSettingPluginSettings;
private applyDebounceTimer = 0;
async onload() {
await this.loadSettings();
app.workspace.onLayoutReady(this.onLayoutReadyForAppearance.bind(this));
app.workspace.onLayoutReady(this.onLayoutReadyForPlugin.bind(this));
}
onunload() {
}
public applySettingsUpdate() {
clearTimeout(this.applyDebounceTimer);
this.applyDebounceTimer = window.setTimeout(async () => {
await this.saveSettings();
}, 100);
}
onLayoutReadyForAppearance(): void {
const addButton = (container: HTMLElement) => {
const reloadSnippetsElement = container.querySelector('[aria-label="Reload snippets"]') as HTMLButtonElement;
if(!reloadSnippetsElement) return;
const btn = reloadSnippetsElement?.parentElement?.createEl("button");
if(!btn) return;
btn.className = "btn btn-tertiary";
setIcon(btn, "plus");
btn.onclick = () => {
new SnippetCreatorModal(app, ()=>{
reloadSnippetsElement.click();
}).open();
}
}
const hideCssSnippetsElements = (element: HTMLDivElement) => {
const headings = element.querySelectorAll('.setting-item.setting-item-heading') as NodeListOf<HTMLDivElement>;
const lastHeading = headings[headings.length - 1];
let sibling = lastHeading.nextElementSibling as HTMLDivElement;
while (sibling) {
if (sibling.classList.contains('mod-toggle') && !sibling.classList.contains('css-creator')) {
sibling.style.display = 'none';
}
sibling = sibling.nextElementSibling as HTMLDivElement;
}
}
const updateSetting = (setting: Setting, snippet: string, enabled: boolean, display: ()=>{}) => {
setting.setName(snippet as string).setDesc("Apply CSS snippet at " + "vault/".concat(app.customCss.getSnippetPath(snippet as string))).addExtraButton((t)=>{
t.setIcon('folder').onClick(async () => {
const path = app.customCss.getSnippetPath(snippet);
const normalizedPath = normalizePath(path);
const checkExist = await app.vault.adapter.exists(normalizedPath);
if(checkExist){
app.showInFolder(path);
}
})
}).addExtraButton((t)=>{
t.setIcon('settings').onClick(async () => {
const path = app.customCss.getSnippetPath(snippet);
const normalizedPath = normalizePath(path);
const checkExist = await app.vault.adapter.exists(normalizedPath);
if (checkExist) {
app.openWithDefaultApp(path);
}
})
}).addToggle(((t) => {
return t.setValue(enabled).onChange(((l) => {
app.customCss.setCssEnabledStatus(snippet, l);
display();
}
))
}
))
}
const addEnabledSnippets = (container: HTMLElement, display: ()=>{}) => {
const enabledHeading = new Setting(container).setHeading().setName("Enabled CSS Snippets");
enabledHeading.settingEl.classList.add('css-creator');
const enabledSnippets = Array.from(app.customCss.enabledSnippets);
const allSnippets = app.customCss.snippets;
enabledSnippets.forEach((snippet: string) => {
const setting = new Setting(container);
setting.settingEl.classList.add('css-creator');
updateSetting(setting, snippet, true, display);
});
const disabledHeading = new Setting(container).setHeading().setName("Disabled CSS Snippets");
disabledHeading.settingEl.classList.add('css-creator');
const disabledSnippets = allSnippets.filter((snippet: string) => !enabledSnippets.includes(snippet));
if(disabledSnippets.length === 0) return;
disabledSnippets.forEach((snippet: string) => {
const setting = new Setting(container);
setting.settingEl.classList.add('css-creator');
updateSetting(setting, snippet, false, display);
});
}
// Capture Hotkey events
const appearance = this.getSettingsTab("appearance");
if (appearance) this.register(around(appearance, { display: this.addPluginSettingEvents.bind(this, appearance.id) }));
const appearanceTab = this.getSettingsTab("appearance") as SettingTab;
if (appearanceTab) {
this.register(around(appearanceTab, {
display(old) {
return function () {
old.call(this);
addButton(this.containerEl);
hideCssSnippetsElements(this.containerEl);
addEnabledSnippets(this.containerEl, this.display.bind(this));
};
},
}));
}
}
onLayoutReadyForPlugin(): void {
const updatePlugins = (container: HTMLElement) => {
const plugins = container.querySelectorAll('.installed-plugins-container .setting-item.mod-toggle');
plugins.forEach((plugin: HTMLElement) => {
const isEnabled = plugin.querySelector('.checkbox-container.is-enabled') === null;
if (this.settings.filter) {
if (!isEnabled) {
plugin.style.display = 'none';
}
} else {
plugin.style.display = '';
}
});
}
const addFilter = (container: HTMLElement, display: ()=>void) => {
const heading = container.querySelector('.setting-item.setting-item-heading .setting-item-control') as HTMLDivElement;
if (!heading) return;
// Create a checkbox to filter out Plugins that are not enabled
const btnComponent = new ExtraButtonComponent(heading).setIcon(this.settings.filter ? 'eye-off' : 'eye' ).onClick(() => {
this.settings.filter = !this.settings.filter;
this.applySettingsUpdate();
updatePlugins(container);
btnComponent.setIcon(this.settings.filter ? 'eye-off' : 'eye');
}).setTooltip('Filter out disabled plugins');
updatePlugins(container);
};
const plugins = this.getSettingsTab("community-plugins");
if (plugins) this.register(around(plugins, { display: this.addPluginSettingEvents.bind(this, plugins.id) }));
const pluginsTab = this.getSettingsTab("community-plugins") as SettingTab;
if (pluginsTab) {
this.register(around(pluginsTab, {
display(old) {
return function () {
old.call(this);
addFilter(this.containerEl, this.display.bind(this));
};
},
}));
}
}
getSettingsTab(id: string) {
return app.setting.settingTabs.filter(t => t.id === id).shift() as SettingTab & { name: string };
}
addPluginSettingEvents(tabId: string, old: SettingTab["display"]) {
const app = this.app;
let in_event = false;
function trigger(name: string, ...args: any[]) {
in_event = true;
try {
app.workspace.trigger(name, ...args);
} catch (e) {
console.error(e);
}
in_event = false;
}
// Wrapper to add plugin-settings events
return function display(...args: any[]) {
if (in_event) return;
trigger("plugin-settings:before-display", this, tabId);
// Track which plugin each setting is for
const remove = around(Setting.prototype, {
addExtraButton(old) {
return function (cb) {
return old.call(this, function (b: ExtraButtonComponent) {
cb(b);
});
}
}
});
try {
return old.apply(this, args);
} finally {
remove();
trigger("plugin-settings:after-display", this);
}
}
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SnippetCreatorModal extends Modal {
cb: ()=> void;
constructor(app: App, cb: ()=> void) {
super(app);
this.cb = cb;
}
onOpen() {
const {contentEl} = this;
const headerEl = contentEl.createEl('div', {cls: 'css-creator modal-header'});
headerEl.createEl("h2", {text: "Snippet Creator", cls: "css-creator-title"});
headerEl.createEl("p", {text: "Create a new snippet;", cls: "css-creator-description"});
headerEl.createEl("p", {text: "File name cannot contain any of the following characters: * \" \\ / < > : | ?", cls: "css-creator-description"});
headerEl.createEl("p", {text: "Don't add duplicate name to file", cls: "css-creator-description"});
const inputGroupEl = contentEl.createEl('div', {cls: 'css-creator modal-body'});
const inputEl = inputGroupEl.createEl('input', {placeholder: "Input file name here", cls:"css-creator-input"});
const textareaEl = inputGroupEl.createEl('textarea', {placeholder: "Paste snippet here", cls:"css-creator-textarea"});
const footerEl = contentEl.createEl('div', {cls: 'css-creator modal-footer'});
const cancelBtnEl = footerEl.createEl('button', {text: "Cancel", cls: "css-creator-cancel"});
const createBtnEl = footerEl.createEl('button', {text: "Create", cls: "css-creator-create"});
cancelBtnEl.addEventListener('click', () => {
this.close();
});
createBtnEl.addEventListener('click', () => {
const fileName = inputEl.value;
const snippet = textareaEl.value;
if(!(fileName.trim()) || !(snippet.trim())) {
new Notice("Please fill in all fields");
return;
}
this.close();
const filePath = normalizePath(app.customCss.getSnippetsFolder()) + "\\" + fileName.trim() + ".css";
console.log(filePath);
app.vault.adapter.write(filePath, snippet);
new Notice("Snippet created successfully");
});
}
onClose() {
const {contentEl} = this;
contentEl.empty();
this.cb();
}
}