generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
507 lines (415 loc) · 13.6 KB
/
main.js
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
let obsidian = require('obsidian');
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
let DEFAULT_SETTINGS = {
// do we show the "#" for tags
showHash: true,
// do we create a css for the shortened tags
cssForShorten: true,
// add a css class based on the tag parents
cssForParent: false,
// add a css class based on the tag
cssForAll: false,
shortenAll:false,
tags: []
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
let CSS = {
"exspan": "snsvrno-tags-example",
"extext": "snsvrno-tags-example-text",
"exdiv": "snsvrno-tags-example-container",
"class": "snsvrno-tags-class",
"count": "snsvrno-tags-matches-count",
"def": "snsvrno-tags-def",
"defpreview": "snsvrno-tags-def-preview",
// used for things like the wildcards or other things
// that that I would put in `t` to show the literal char.
"key": "snsvrno-tags-keyword",
"keydiv": "snsvrno-tags-keyword-div"
}
let STRINGS = {
"headings" : {
"classes": "Classes",
"tags": "Tag Definitions"
},
"buttons" : {
"add" : "+",
"remove" : "X"
},
"cssDoesNotOverwrite": "Does not overwrite any other CSS.",
"cssForAll" : {
"name": "Add a CSS Class for All Tags",
"desc": "Creates a CSS class for each tag, based on that tag name."
},
"cssForParent" : {
"name": "Add a CSS Class for Parents",
"desc": "Creates a CSS class for each tag based on its parents."
},
"cssForShorten" : {
"name": "Add a CSS Class for Shortened",
"desc": "Creates a CSS class for each tag that is shortened.",
"desc2": "Only creates classes for the shorten definitions below, not shorten all."
},
"notag" : "No matching tags currently found in vault.",
"preview" : {
"text": "Preview: ",
"css": "CSS class: "
},
"shortenAll" : {
"name": "Shorten All Tags",
"desc": "Shorten the display of all tags to only the lowest level child.",
"desc2": "Shorten definitions will still apply, and will take priority over this shortening methodology."
},
"showHash" : {
"name": "Show Hash",
"desc": "Show the '#' for tags in preview."
},
"tags" : {
"name": "Tags",
"desc": "List of tag parents for shortening in preview mode."
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class SnsvrnoTagsPlugin extends obsidian.Plugin {
// CORE //////////////////////
async onload() {
await this.loadSettings();
this.addSettingTab(new SnsvrnoTagsSettingsTab(this.app, this));
this.registerMarkdownPostProcessor((e) => {
e.querySelectorAll("a.tag").forEach((a) => this.formatTag(a));
});
}
onunload() {
// nothing to unload for now?
}
// SETTINGS RELATED /////
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
// PLUGIN SPECIFIC ////////////
// formats the string as if it were a tag by checking
// if we should display the "#" or not
formatTagHash(str) {
if (this.settings.showHash) {
if (str.charAt(0) == "#") return str;
else return "#" + str;
} else {
if (str.charAt(0) == "#") return str.substring(1);
else return str;
}
}
// runs the processing on the given tag, will check that
// it is actually a tag before doing anything.
//
// el : HTMLElement - the tag in question, should be an 'a.tag'
formatTag(el) {
///////////////////////////////////
// double checks that these are tags, will not
// continue processing if its not
if (el.text.substring(0,1) != "#") return;
var original = el.text;
if (this.settings.cssForAll)
el.className += " " + fn.generateClassName(original);
if (this.settings.cssForParent)
el.className += " " + fn.generateClassName(fn.parents(original));
/////////////////////////////////
// shortens the tag if applicable
for (let i = 0; i < this.settings.tags.length; i++) {
// [OTGI0004] look at caching these so that we are not calculating
// it for every page and tag
const reftag = fn.makeReg(this.settings.tags[i]);
if (el.text.match(reftag)) {
el.text = el.text.replace(reftag, "");
///////////////////////////////////
// adds the class
if (this.settings.cssForShorten)
el.className += " " + fn.generateClassName(this.settings.tags[i]);
break;
}
}
// things to do if we didn't shorten by def
if (el.text == original) {
if (this.settings.shortenAll) {
el.text = el.text.split("/").pop();
}
}
// the mouse over text
if (el.text != original) el.title = original;
el.text = this.formatTagHash(el.text);
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class SnsvrnoTagsSettingsTab extends obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display(focusId) {
this.containerEl.empty();
this.opShowHash();
this.createSettingBool(this.containerEl, "shortenAll");
this.containerEl.createEl("h2", {text:STRINGS.headings.classes});
this.createSettingBool(this.containerEl, "cssForShorten");
this.opCreateCssForParent();
this.opCreateCssForAll();
this.containerEl.createEl("h2", {text:STRINGS.headings.tags});
this.opTags(this.containerEl, focusId);
}
////////////////////////////////////
opCreateCssForAll() {
const setting = this.createSettingBool(this.containerEl, "cssForAll");
setting.descEl.createEl("div", {text: STRINGS.cssDoesNotOverwrite});
// the preview showing if and how the hash will be
// displayed
let previewBlock = this.createExampleBlock(setting.descEl);
let tag = this.getTagsSingle("#example-tag");
let cls = fn.generateClassName(tag);
this.createTagEl(
previewBlock,
this.plugin.formatTagHash(tag),
cls
);
let cssClass = this
.createExampleBlock(setting.descEl,STRINGS.preview.css)
.createEl("span", {
text: cls,
cls: CSS.class
});
}
////////////////////////////////////
opCreateCssForParent() {
const setting = this.createSettingBool(this.containerEl, "cssForParent");
setting.descEl.createEl("div", {text: STRINGS.cssDoesNotOverwrite});
// the preview showing if and how the hash will be
// displayed
let previewBlock = this.createExampleBlock(setting.descEl);
let tag = this.getTagsLong("#example/tag");
let cls = fn.generateClassName(fn.parents(tag));
this.createTagEl(
previewBlock,
this.plugin.formatTagHash(tag),
cls
);
let cssClass = this
.createExampleBlock(setting.descEl, STRINGS.preview.css)
.createEl("span", {
text: cls,
cls: CSS.class
});
}
////////////////////////////////////
opShowHash() {
let exampleTag;
let setting = this.createSettingBool(this.containerEl, "showHash");
// the preview showing if and how the hash will be
// displayed
let previewTagName = this.getTagsLong("#example/tag");
this.createTagEl(
this.createExampleBlock(setting.descEl),
this.plugin.formatTagHash(previewTagName)
);
}
// el : HTMLElement - the container element that holds the settings items
// ?focusId : string - the name of the tag item that requested a "diplay()"
// update. (used so that we can have live previews of the
// settings update as the user types)
opTags(el, focusId) {
let setting = new obsidian.Setting(el)
.setName(STRINGS.tags.name)
.setDesc(STRINGS.tags.desc);
setting.descEl.createEl("div", {text:"Available wildcards:"});
// rules
let line1 = setting.descEl.createEl("div", { cls:CSS.keydiv });
line1.createEl("span", { text:"*", cls:CSS.key });
line1.createEl("span", { text:" matches all characters except for " });
line1.createEl("span", { text:"/", cls:CSS.key });
// creates a new line for each user tag setting
this.plugin.settings.tags.forEach(
(tagDef) => this.createSettingTag(tagDef, el, focusId)
);
// creates the "add" button at the end
let div = el.createDiv();
new obsidian.Setting(div)
.addButton((btn) => {
btn.setButtonText(STRINGS.buttons.add);
btn.setTooltip("Add another matching expression.");
btn.onClick(async (_) => {
this.plugin.settings.tags.push("#parent/tag");
this.plugin.saveSettings();
this.display();
});
});
}
////////////////////////////////////
// creates the basic elements for the "preview" that is displayed
// under setting to immediately show their impact.
createExampleBlock(el, text, spanclass) {
let example = el.createEl("span", {
cls: CSS.exspan + (spanclass != undefined ? " " + spanclass : "")
});
let exampletext = example.createEl("p", {
text: text ? text : STRINGS.preview.text,
cls: CSS.extext
});
let examplecontainer = example.createEl("div", {
cls: CSS.exdiv
});
return examplecontainer;
}
// creates the tag element with the correct classes
createTagEl(el, text, otherClass) {
let tag = el.createEl("a", {
text: text,
cls: "tag" + (otherClass ? " " + otherClass : "")
})
return tag;
}
// creates the boilerplate settings stuff
// element : HTMLElement
// section : string - the name of the section in STRING that contains name,desc
createSettingBool(element, section) {
const opt = new obsidian.Setting(element);
opt.setName(STRINGS[section].name);
opt.setDesc(STRINGS[section].desc);
opt.addToggle(t => t
.setValue(this.plugin.settings[section])
.onChange(async (v) => {
this.plugin.settings[section] = v;
this.plugin.saveSettings();
this.display();
})
);
// adds additional divs to the desc based on the number
// of desc# that are in the str section
let i = 2;
while (STRINGS[section]["desc" + i] != undefined) {
opt.descEl.createEl("div", {text:STRINGS[section]["desc" + i]});
i += 1;
}
return opt;
}
createSettingTag(def, parent, focusId) {
const index = this.plugin.settings.tags.indexOf(def);
let div = parent.createDiv();
div.className = CSS.def;
let setting = new obsidian.Setting(div)
.addText(txt => {
txt.setValue(def);
txt.onChange(async (v) => {
this.plugin.settings.tags[index] = v;
this.plugin.saveSettings();
this.display("tags_"+v);
});
// focus on this text box so we can continue to type
// and update the previews
if (focusId == "tags_" + def) txt.inputEl.focus();
})
.addButton(btn => {
btn.setButtonText(STRINGS.buttons.remove);
btn.setTooltip("Remove rule '" + def + "'");
btn.onClick(async (_) => {
this.plugin.settings.tags.splice(index, 1);
this.plugin.saveSettings();
this.display();
});
});
// preview
let preview = this.createExampleBlock(setting.descEl, null, CSS.defpreview);
const tagDefReg = fn.makeReg(def);
let foundMatch = false;
let matchCount = 0;
let vaultTags = Object.keys(this.plugin.app.metadataCache.getTags());
for (let i = 0; i < vaultTags.length; i++) {
if (vaultTags[i].match(tagDefReg)) {
// this happens on the 2nd+ match so we can get the
// counts but don't need to make the preview anymore
if (foundMatch) matchCount += 1;
else {
let newTag = vaultTags[i].replace(tagDefReg,"");
this.createTagEl(preview, this.plugin.formatTagHash(vaultTags[i]));
preview.createEl("span", { text: "=>" });
let newcls;
if (this.plugin.settings.createCssForShorten)
newcls = fn.generateClassName(def);
this.createTagEl(preview,this.plugin.formatTagHash(newTag), newcls);
foundMatch = true;
matchCount = 1;
}
}
}
// if no tags exist, let the user know in the case there is a typo
// or that no matches is unexpected.
if (!foundMatch) {
preview.createEl("span", {
text: STRINGS.notag,
cls: "setting-item-description"
});
} else {
let matchesEl = this
.createExampleBlock(setting.descEl, "Unique tag matches:")
.createEl("span", {
text: matchCount,
cls: CSS.count
});
if (this.plugin.settings.cssForShorten) {
let cls = fn.generateClassName(def);
let cssClass = this
.createExampleBlock(setting.descEl,STRINGS.preview.css)
.createEl("span", {
text: cls,
cls: CSS.class
});
}
}
return setting;
}
// gets a tag that has parents
// ifnull : string - what to return if we don't find anything
getTagsLong(ifnull) {
const tags = Object.keys(this.app.metadataCache.getTags());
for (let i = 0; i < tags.length; i++) {
if (tags[i].split("/").length > 1) {
return tags[i];
}
}
return ifnull;
}
// gets a tag that has no parents
// ifnull : string - what to return if we don't find anything
getTagsSingle(ifnull) {
const tags = Object.keys(this.app.metadataCache.getTags());
for (let i = 0; i < tags.length; i++) {
if (tags[i].split("/").length == 1) {
return tags[i];
}
}
return ifnull;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class fn {
static makeReg(def) {
if (def.substring(def.length-1,1) != "/") def = def += "/";
let reg = new RegExp(def.replaceAll("*", "[^\/]*"))
return reg;
}
static generateClassName(def) {
let name = def.substring(1);
name = name.replaceAll("*","wc");
name = name.replaceAll("/","_");
return "tag-"+ name;
}
static parents(tag) {
return tag.split("/").slice(0,tag.split("/").length-1).join("/");
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
module.exports = SnsvrnoTagsPlugin