-
Notifications
You must be signed in to change notification settings - Fork 1
/
Krakor.js
3290 lines (2765 loc) · 134 KB
/
Krakor.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class Krakor {
AudioManager = class {
constructor({
enableSimultaneousPlaying = false,
autoplay = true,
stopAutoplayWhenReachingLastMusic = true,
defaultVolume = 0.5,
logger, utils, icons,
} = {}) {
this.logger = logger
this.icons = icons
this.utils = utils
this.os = utils.getOS()
this.enableSimultaneousPlaying = enableSimultaneousPlaying
this.autoplay = autoplay
this.stopAutoplayWhenReachingLastMusic = stopAutoplayWhenReachingLastMusic
this.currentAudioPlaying = -1
this.numberOfAudiosLoaded = -1
this.defaultVolume = defaultVolume
}
/**
* @param {HTMLInputElement} timeline
* @param {HTMLAudioElement} audio
*/
onChangeTimelinePosition = (timeline, audio) => {
const percentagePosition = (100 * audio.currentTime) / audio.duration;
timeline.style.backgroundSize = `${percentagePosition}% 100%`;
timeline.value = percentagePosition;
}
/**
* @param {HTMLInputElement} timeline
* @param {HTMLAudioElement} audio
*/
onChangeSeek = (timeline, audio) => {
const time = (timeline.value * audio.duration) / 100;
audio.currentTime = time;
}
/**
* @param {object} _
* @param {number} _.index
* @param {HTMLAudioElement[]} _.audios
* @param {HTMLButtonElement[]} _.playButtons
*/
onPlayAudio = async ({ index, audios, playButtons }) => {
if (!this.enableSimultaneousPlaying && this.currentAudioPlaying !== -1 && this.currentAudioPlaying !== index) {
audios[this.currentAudioPlaying].pause()
}
// Handle volume
const dataVolume = parseFloat(audios[index].dataset.volume)
if (!isNaN(dataVolume)) {
audios[index].volume = this.utils.clamp(this.defaultVolume + dataVolume, 0.1, 1)
} else {
audios[index].volume = this.utils.clamp(this.defaultVolume, 0.1, 1)
}
this.currentAudioPlaying = index;
await this.reloadMp3IfCorrupt(audios[index])
playButtons[index].innerHTML = this.icons.pauseIcon;
}
/**
*
* @param {object} _
* @param {HTMLButtonElement} _.playButton
* @param {HTMLAudioElement} _.audio
*/
onPauseAudio = ({ playButton, audio, index }) => {
if (this.currentAudioPlaying === index) {
// This if check is needed to not break the 'disable simultaneous playing of mp3' feature
this.currentAudioPlaying = -1;
}
audio.pause();
playButton.innerHTML = this.icons.playIcon;
}
/**
* @param {object} _
* @param {number} _.index
* @param {HTMLAudioElement[]} _.audios
*/
onPlayButtonClick = async ({ index, audios }) => {
if (audios[index].paused) {
await audios[index].play()
} else {
audios[index].pause()
}
}
onEnded = async ({audios, index, timeline, playButton,}) => {
this.currentAudioPlaying = -1
playButton.innerHTML = this.icons.playIcon
timeline.value = 0
timeline.style.backgroundSize = "0% 100%"
if (!this.autoplay
|| audios.length === 1
|| (this.stopAutoplayWhenReachingLastMusic && index + 1 === audios.length)) {
return;
}
let nextIndex = 0
if (index + 1 != audios.length) nextIndex = index + 1
if (this.os === "Android") {
this.checkLoadedMp3Status(audios[nextIndex])
}
await audios[nextIndex].play()
}
/**
* This function should be called every time new scores are added at the end of the grid (because of scroll)
* or if the grid of score is re-arranged because of new filters ?
* It:
* - Binds the update of the audio to the progress of the timeline
* - Handle what happened when you click on the custom button
* - Make possible to drag the timeline to change the audio timecode
* - Supports automatic playback of the next found mp3 (which is already loaded in the grid of course)
*
* I'm using on... properties here because I only need one handler per audio at all time
* and I don't want to handle the adding and removing of eventListener manually
*
* @param {import('./view').CollectionManager} collectionManager - An object responsible of a collection of DomElement
* It must implement a function getParent() that returns the parent DomElement of the collection
*/
manageMp3Scores(collectionManager) {
this.logger?.reset()
/** @type {HTMLAudioElement[]} */
const audios = collectionManager.parent.querySelectorAll('audio')
/** @type {HTMLButtonElement[]} */
const playButtons = collectionManager.parent.querySelectorAll('.audio-player button')
/** @type {HTMLInputElement[]} */
const trackTimelines = collectionManager.parent.querySelectorAll('input.timeline')
if (this.numberOfAudiosLoaded === audios.length) return;
this.numberOfAudiosLoaded = audios.length
// Must never happen
if (audios.length !== playButtons.length) {
console.error("The number of play buttons doesn't match the number of audios")
}
for (let i = 0; i < audios.length; i++) {
if (this.os === "Android") {
audios[i].onloadedmetadata = () => this.checkLoadedMp3Status(audios[i])
}
audios[i].ontimeupdate = () => this.onChangeTimelinePosition(trackTimelines[i], audios[i])
audios[i].onplay = () => this.onPlayAudio({ index: i, audios, playButtons })
audios[i].onpause = () => this.onPauseAudio({ playButton: playButtons[i], audio: audios[i], index: i })
playButtons[i].onclick = () => this.onPlayButtonClick({ index: i, audios })
trackTimelines[i].onchange = () => this.onChangeSeek(trackTimelines[i], audios[i])
audios[i].onended = () => this.onEnded({
audios,
index: i,
timeline: trackTimelines[i],
playButton: playButtons[i],
})
}
this.logger?.logPerf("Reloading all the mp3 management")
}
/**
* @description Since Android audios are sometimes corrupted, this function flag them (by coloring the timecode tag) to:
* - Skip them on autoplay
* - Visually mark them so that the user know they didn't load correctly
* Edit: Big twist as of today (2023-01-04). Even mp3 with correct loading time may not play completely. I've experienced this with Elegia today, i was flabbergasted...
* So it truly is unreliable on Android after all 😥. I still keep this function though because i'm sure it's still better than nothing
* @param {HTMLAudioElement} audio
*/
checkLoadedMp3Status = (audio) => {
const timecodeTag = audio.parentNode.parentNode.querySelector(".timecode")
if (!timecodeTag) return;
const timecodeDuration = this.utils.convertTimecodeToDuration(timecodeTag.querySelector("span").innerText)
// Even in this state, the audio may not play completely...
if (Math.abs(timecodeDuration - audio.duration) <= 1) {
timecodeTag.style.backgroundColor = "#060D"
return true;
}
if (audio.classList.contains("corrupt")) {
timecodeTag.style.backgroundColor = "#600D"
return
}
// Modifying the src property after it has been loaded doesn't do anything (https://stackoverflow.com/a/68797896)
audio.classList.add("corrupt")
timecodeTag.style.backgroundColor = "#F808"
return false;
}
/**
* @description I don't know why but most of the time, audios fail to load on Android for no specific reasons
* I tried to:
* - Remove the <source> and replace it with a new one but it doesn't load it
* - Set the src of the audio tag to the one of the source to override it but that doesn't work either
*
* I guess it can't be patched like that 😕, so i should report this bug on obsidian forum
* Edit: Here is the link to the issue i've created : https://forum.obsidian.md/t/bug-audio-files-fail-to-load-randomly-on-android/49684
* Edit 2: Hahaha nobody cares (as expected 😅)
* Edit 3: @Majed6 on Discord said he had the same problem and he found a workaround, unfortunately, it doesn't completely solve the issue 😞
* @param {HTMLAudioElement} audio
*/
reloadMp3IfCorrupt = async (audio) => {
if (!audio.classList.contains("corrupt")) return;
// from: https://github.com/Majed6/android-audio-fixer/blob/master/main.ts
if (!audio.classList.contains("processed")) {
audio.classList.add('processed');
const file = await fetch(audio.firstElementChild.src);
const fileBlob = await file.blob();
audio.src = URL.createObjectURL(fileBlob);
}
}
}
ButtonBar = class {
constructor({
buttonsOrder = [],
buttonsMap = new Map(),
logger,
} = {}) {
this.logger = logger
/** @type{string[]} */
this.buttonsOrder = buttonsOrder
/** @type {Map<string, import('./view').ViewButton>} */
this.buttonsMap = buttonsMap
}
addButton({name, icon, event}) {
this.buttonsMap.set(name, { icon, event })
this.buttonsOrder.push(name)
}
buildHTMLButtons() {
let html = ''
for (const buttonId of this.buttonsOrder) {
if (!buttonId) continue
const button = this.buttonsMap.get(buttonId)
if (!button) {
console.warn(`${buttonId} isn't a valid view button`)
continue
}
html += `<button class='${buttonId}'>
${button.icon}
</button>
`
}
return html
}
/**
*
* @param {HTMLButtonElement[]} buttons
*/
setEvents(buttons) {
for (const btn of buttons) {
btn.onclick = (async (e) => {
const button = this.buttonsMap.get(btn.className)
await button?.event()
e.stopPropagation() // used for preventing callout default behavior in live preview
btn.blur()
})
}
}
}
/**
* A function that takes an `HTMLElement` as input and do some computation on it
* @typedef {Function} HTMLCallback
* @property {HTMLElement} element
*/
/**
* The object that should be returned by the `pageToChild` method of this class
* @typedef {object} PageToHTML
* @property {string} html
* @property {object} extra - A set of selectors to html. Needed for specific HTML tags behavior to happen on tag insertion
* @property {HTMLCallback} postInsertionCb - Used to do some computation on the element after it has been inserted in the DOM
*/
/**
* @abstract
* @warning This class need CustomJS enabled to work since it uses `MarkdownRenderer.renderMarkdown` which is exposed by the plugin.
* It is also needed because of the way the static generator functions are written
*
* @description
* This class is no longer Dataview dependant. This makes it agnostic of the engine its running on
* It might be Dataview, Datacore or even JS-Engine, this class shouldn't care
*
* This class is the blueprint to use for classes that manage a collection of children node in the DOM
* Don't instantiate directly from its constructor. You should use one of the static methods at the bottom instead
* It handles:
* - Lazy rendering of a bunch of DOM elements for blazing fast performance
* - Custom rendering that bypass `MarkdownRenderer.renderMarkdown` capacity
* - Image fallback
*
* @example
* // Initializes the collection manager with all its needed dependencies
* const gridManager = CollectionManager.makeGridManager({
* container,
* component,
* currentFilePath,
* logger, icons, utils,
* numberOfElementsPerBatch: 20,
* })
*
* // Internaly build the HTML representation of every elements thanks to blueprint
* await gridManager.buildChildrenHTML({pages, pageToChild: async (p) => {...}})
*
* // Creates the HTML element that will hold every children and push it in the DOM
* gridManager.buildParent()
*
* // Appends a chunk of element inside the DOM as children of the parent
* await gridManager.insertNewChunk()
*
* // Initializes the infinite rendering that happens on scroll
* gridManager.initInfiniteLoading()
*/
CollectionManager = class {
/**
* @param {object} _
* @param {Function} _.buildParent - a function that build, insert in the DOM and set this.parent (must be a regular function)
*/
constructor({
//Dependencies
container,
component,
currentFilePath,
logger,
utils,
icons,
//Optional
disableSet,
numberOfElementsPerBatch = 20,
extraLogicOnNewChunk = [],
//Child class injection
childTag,
buildParent,
}) {
/**
* The parent element of this collection (most of the time, the codeblock div itself)
* @type {HTMLElement}
*/
this.container = container
/** Correspond to the current plugin component where this object is instantiated */
this.component = component
/** @type {string} */
this.currentFilePath = currentFilePath
this.logger = logger
this.icons = icons
this.utils = utils
this.disableSet = disableSet
this.childTag = childTag
this.buildParent = buildParent.bind(this)
/** @type {HTMLElement} */
this.collection = null
/** @type {(string|object)[]} */
this.children = []
this.batchesFetchedCount = 0
this.numberOfElementsPerBatch = numberOfElementsPerBatch
/** @type {Array<function(CollectionManager): Promise<void>>} */
this.extraLogicOnNewChunk = extraLogicOnNewChunk
const intersectionOptions = {
root: null, // relative to the viewport
rootMargin: '200px', // 200px below the viewport
threshold: 0,
}
this.childObserver = new IntersectionObserver(this.handleLastChildIntersection.bind(this), intersectionOptions);
}
everyElementsHaveBeenInsertedInTheDOM = () => (this.batchesFetchedCount * this.numberOfElementsPerBatch >= this.children.length)
/**
* Susceptible to be overriden by a more specialized Collection instance
*
* *What are the differences with `this.collection`?*
*
* this.collection is the main container of the Collection (`<table>` for Table, `<div>` for Grid, ...)
* this.parent is the container that directly contains the children (for example, it should be `<tbody>` for Table)
* Both can refer to the same HTML element but not necessarly
*/
get parent() {
return this.collection
}
/**
* Build the complete list of children that will eventually be rendered on the screen
* (if you scroll all the way down)
* This method params can be quite obscure and for a reason: The `MarkdownRenderer.renderMarkdown` method
*
* @param {object} _
* @param {*} _.pages - dataview pages (https://blacksmithgu.github.io/obsidian-dataview/api/data-array/#raw-interface)
* @param {Function} _.pageToChild - This function get a page as its parameter and is suppose to return an html string or an array of html strings
* @returns {string[]} Each value of the array contains some HTML equivalent to a cell on the grid
*/
buildChildrenHTML = async ({ pages, pageToChild }) => {
let children = []
for (const p of pages) {
const child = await pageToChild(p)
if (Array.isArray(child)) {
children = [...children, ...child]
} else {
children.push(child)
}
}
this.children = children
this.logger?.log({ children })
}
/**
* TODO: finish this generator/yield implementation to have a true lazy generation of HTML
* Hence I need to modify handleLastChildIntersection and insertNewChunk
* Is it really worth it though? The current buildChildrenHTML isn't that slow
*/
async *generateChildrenHTML({ pages, pageToChild }) {
let pageIndex = 0;
while (pageIndex < pages.length) {
const batchPages = pages.slice(pageIndex, pageIndex + this.numberOfElementsPerBatch);
const batchHTML = [];
for (const page of batchPages) {
const child = await pageToChild(page)
if (Array.isArray(child)) {
batchHTML = [...batchHTML, ...child]
} else {
batchHTML.push(child)
}
}
pageIndex += this.numberOfElementsPerBatch;
this.batchChildrenHTML = batchHTML
yield this.batchChildrenHTML; // Yield the batch of HTML strings
}
}
initInfiniteLoading() {
if (this.everyElementsHaveBeenInsertedInTheDOM()) return
const lastChild = this.parent.querySelector(`${this.childTag}:last-of-type`);
this.logger?.log({ lastChild })
if (lastChild) {
this.childObserver.observe(lastChild)
}
}
#handleImageFallback(img) {
if (!img) return
img.onerror = () => {
this.logger?.log({ img })
img.onerror = null;
const threeDigitColor = (Math.floor(Math.random() * 999)).toString()
img.outerHTML = this.icons.customObsidianIcon(`#${threeDigitColor.padStart(3, 0)}`);
}
}
/**
* @warning CustomJS plugin is needed to run this function
*
* It might be difficult to understand what's going on but it could be reduced to a 20 lines long function max
* if `MarkdownRenderer.renderMarkdown` had a consistent behavior no matter what tags were passed to it
*/
async insertNewChunk() {
const fromSliceIndex = this.batchesFetchedCount * this.numberOfElementsPerBatch
const toSliceIndex = (this.batchesFetchedCount + 1) * this.numberOfElementsPerBatch
const newChunk = this.children.slice(fromSliceIndex, toSliceIndex).reduce((acc, cur) => {
if (typeof cur === "string") {
return acc + cur
}
// Here cur must be an object with an `html` property in it
return acc + cur.html
}, "")
// Needed for metadata-menu to trigger and render extra buttons
const extraChunkDOM = this.container.createEl('div')
let extraChunkHTML = ''
for (let i = fromSliceIndex; i < toSliceIndex; i++) {
if (!this.children[i]?.extra) {
extraChunkHTML += `<div></div>`
continue;
}
extraChunkHTML += `<div>`
for (const [selector, html] of Object.entries(this.children[i].extra)) {
extraChunkHTML += `<div data-selector="${selector}">`
extraChunkHTML += html
extraChunkHTML += `</div>`
}
extraChunkHTML += `</div>`
}
/** The root cause of all this madness. I could use dv.el instead but it would add an extra level of abstraction I don't control */
await customJS.obsidian.MarkdownRenderer.renderMarkdown(extraChunkHTML, extraChunkDOM, this.currentFilePath, this.component)
// ---
if (!this.parent) {
return console.error("Something went wrong, the collection parent element doesn't exist in the DOM")
}
this.parent.insertAdjacentHTML('beforeend', newChunk)
// 2nd part with the extraChunkDOm
for (let i = 0; i < this.numberOfElementsPerBatch; i++) {
const extra = extraChunkDOM.children[i]
if (!extra) continue
const currentChild = this.parent.children[i + fromSliceIndex]
// That means we've reach the end of the infinite loading
if (!currentChild) break
for (const extraChild of extra.children) {
const targetEl = currentChild.querySelector(extraChild.dataset.selector)
if (!targetEl) continue
while (extraChild.hasChildNodes()) {
targetEl.appendChild(extraChild.firstChild)
}
}
// Fallback for images that don't load
for (const imgNode of currentChild.querySelectorAll("img")) {
this.#handleImageFallback(imgNode)
}
}
extraChunkDOM.remove()
// ---
this.batchesFetchedCount++
this.logger?.log({ batchesFetchedCount: this.batchesFetchedCount })
for (const fn of this.extraLogicOnNewChunk) {
await fn(this)
}
}
handleLastChildIntersection(entries) {
entries.map(async (entry) => {
if (entry.isIntersecting) {
this.logger.log(entry)
this.logger.reset()
this.childObserver.unobserve(entries[0].target);
await this.insertNewChunk()
this.logger.logPerf("Appending new children at the end of the grid")
if (this.batchesFetchedCount * this.numberOfElementsPerBatch < this.children.length) {
this.logger?.log(`Batch to load next: ${this.batchesFetchedCount * this.numberOfElementsPerBatch}`)
const lastChild = this.parent.querySelector(`${this.childTag}:last-of-type`)
this.childObserver.observe(lastChild)
}
}
});
}
static makeTableManager(dependencies) {
function buildParent(headers) {
const buildTHead = (headers) => {
const trFragment = document.createDocumentFragment();
headers.forEach(header => {
const headerHTML = `<p>${header}</p>`
const th = this.container.createEl("th", { cls: "table-view-th" })
th.insertAdjacentHTML('beforeend', headerHTML)
trFragment.appendChild(th)
})
const tr = this.container.createEl("tr", { cls: "table-view-tr-header" })
tr.appendChild(trFragment)
const thead = this.container.createEl("thead", { cls: "table-view-thead" })
thead.appendChild(tr)
return thead
}
const thead = buildTHead(headers)
const tbody = this.container.createEl("tbody", { cls: "table-view-tbody" })
const table = this.container.createEl("table", { cls: "table-view-table" })
table.appendChild(thead)
table.appendChild(tbody)
this.collection = table
}
const tableManager = new customJS["Krakor"].CollectionManager({
...dependencies,
buildParent,
childTag: 'tr',
})
Object.defineProperty(tableManager, "parent", {
get: function () {
return tableManager.collection?.lastChild;
},
});
return tableManager
}
static makeGridManager(dependencies) {
function buildParent() {
this.collection = this.container.createEl("div", { cls: "grid" })
}
return new customJS["Krakor"].CollectionManager({
...dependencies,
buildParent,
childTag: 'article',
})
}
}
/**
* TODO: see if I can easily remove dv dependency and use Obsidian internal API instead to access the created file
* Class used to create files and automatically insert metadata
* based on the filters present in the view where the file creation is triggered
*/
FileManager = class {
/**
* @param {object} _
* @param {string?} _.directoryWhereToAddFile
* @param {Array<Function>} _.logicOnAddFile
*/
constructor({ dv, app, utils, currentFilePath, properties, userFields, directoryWhereToAddFile, logicOnAddFile = [] }) {
this.dv = dv,
this.app = app
this.utils = utils
this.currentFilePath = currentFilePath
this.directoryWhereToAddFile = directoryWhereToAddFile
this.properties = properties
this.userFields = userFields
this.logicOnAddFile = logicOnAddFile
}
/**
* from there : https://github.com/vanadium23/obsidian-advanced-new-file/blob/master/src/CreateNoteModal.ts
* Handles creating the new note
* A new markdown file will be created at the given file path {input}
* @param {string} input
* @param {"current-pane"|"new-pane"|"new-tab"} mode - current-pane / new-pane / new-tab
* @returns {TFile}
*/
createNewNote = async (input, mode = "new-tab") => {
const { vault } = this.app;
const { adapter } = vault;
const filePath = `${input}.md`;
try {
const fileExists = await adapter.exists(filePath);
if (fileExists) {
// If the file already exists, respond with error
throw new Error(`${filePath} already exists`);
}
const file = await vault.create(filePath, '');
// Create the file and open it in the active leaf
let leaf = this.app.workspace.getLeaf(false);
if (mode === "new-pane") {
leaf = this.app.workspace.splitLeafOrActive();
} else if (mode === "new-tab") {
leaf = this.app.workspace.getLeaf(true);
} else if (!leaf) {
// default for active pane
leaf = this.app.workspace.getLeaf(true);
}
await leaf.openFile(file);
console.log({ file, leaf })
return file;
} catch (error) {
alert(error.toString());
}
}
/**
* Didn't find a better way for now to wait until the metadata are loaded inside a newly created file
* @param {string} pathToFile
*/
#waitUntilFileMetadataAreLoaded = async (pathToFile) => {
let dvFile = null
while (!dvFile) {
await this.utils.delay(20); // very important to wait a little to not overload the cpu
console.log("Metadata in the newly created file hasn't been loaded yet")
dvFile = this.dv.page(pathToFile)
if (!dvFile) continue; // the file isn't even referenced by dataview api yet
if (Object.keys(dvFile).length === 1) { // metadata hasn't been loaded yet in the page, so we continue
dvFile = null
}
}
}
handleAddFile = async ({directoryWhereToAddFile, properties, userFields} = {}) => {
const computed = {
directoryWhereToAddFile: directoryWhereToAddFile ?? this.directoryWhereToAddFile,
properties: properties ?? this.properties,
userFields: userFields ?? this.userFields,
}
const newFilePath = `${computed.directoryWhereToAddFile}/Untitled`
const newFile = await this.createNewNote(newFilePath)
const mmenuPlugin = this.app.plugins.plugins["metadata-menu"]?.api
if (!mmenuPlugin) {
return console.warn("You don't have metadata-menu enabled so you can't benefit from the smart tag completion")
}
await this.#waitUntilFileMetadataAreLoaded(newFilePath)
// If I don't wait long enough to apply auto-complete, it's sent into oblivion by some mystical magic I can't control.
await this.utils.delay(2500)
console.log("At last, we can start the autocomplete")
const fieldsPayload = []
for (const fn of this.logicOnAddFile) {
await fn(this, fieldsPayload)
}
const current = this.dv.page(this.currentFilePath)
if (computed.properties?.current) {
fieldsPayload.push({
name: computed.properties.current,
payload: { value: `[[${current.file.name}]]` }
})
delete computed.properties.current
}
for (const field in computed.properties) {
console.log(`${field}: ${computed.properties[field]}`)
if (computed.userFields.get(field) === "date") continue;
fieldsPayload.push({
name: field,
payload: {
value: Array.isArray(computed.properties[field])
? `[${computed.properties[field].join(", ")}]`
: computed.properties[field]
}
})
}
await mmenuPlugin.postValues(newFile.path, fieldsPayload)
}
}
/**
* Class that contains svg icons directly in string format or sizable via a function
* TODO: See if I can directly use Obsidian internal way of rendering Lucide icons instead of doing this mess
*/
IconManager = class {
constructor({hide} = {}) {
this.hide = !!hide
}
// ------------------------
// - Company/Service icons
// ------------------------
// youtubeIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#aa0000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6 0 0 0 0 0 0z"></path><polygon points="10 15 15 12 10 9"></polygon></svg>'
youtubeIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#aa0000${this.hide ? "00" : ""}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6 0 0 0 0 0 0z"></path><polygon points="10 15 15 12 10 9"></polygon></svg>`
// from: https://www.svgrepo.com/svg/89412/soundcloud-logo
soundcloudIcon = `<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="24" height="24" viewBox="0 0 317.531 317.531" stroke-width="4" stroke="#ff5400${this.hide ? "00" : ""}" fill="#ff5400${this.hide ? "00" : ""}" style="enable-background:new 0 0 317.531 317.531;" xml:space="preserve"><g><path d="M270.275,141.93c-3.134,0-6.223,0.302-9.246,0.903c-3.289-15.779-11.423-30.182-23.436-41.249c-14.363-13.231-33.037-20.518-52.582-20.518c-9.533,0-19.263,1.818-28.139,5.256c-3.862,1.497-5.78,5.841-4.284,9.703c1.496,3.863,5.838,5.781,9.703,4.284c7.165-2.776,15.022-4.244,22.72-4.244c32.701,0,59.532,24.553,62.411,57.112c0.211,2.386,1.548,4.527,3.6,5.763c2.052,1.236,4.571,1.419,6.778,0.49c3.948-1.66,8.146-2.501,12.476-2.501c17.786,0,32.256,14.475,32.256,32.267c0,17.792-14.473,32.268-32.263,32.268c-1.002,0-106.599-0.048-110.086-0.061c-3.841-0.084-7.154,2.778-7.591,6.659c-0.464,4.116,2.497,7.829,6.613,8.292c0.958,0.108,109.962,0.109,111.064,0.109c26.061,0,47.263-21.205,47.263-47.268C317.531,163.134,296.332,141.93,270.275,141.93z"/><path d="M7.5,153.918c-4.142,0-7.5,3.358-7.5,7.5v60.039c0,4.142,3.358,7.5,7.5,7.5s7.5-3.358,7.5-7.5v-60.039C15,157.276,11.642,153.918,7.5,153.918z"/><path d="M45.917,142.037c-4.142,0-7.5,3.358-7.5,7.5v71.07c0,4.142,3.358,7.5,7.5,7.5s7.5-3.358,7.5-7.5v-71.07C53.417,145.395,50.059,142.037,45.917,142.037z"/><path d="M85.264,110.21c-4.142,0-7.5,3.358-7.5,7.5v111c0,4.142,3.358,7.5,7.5,7.5c4.142,0,7.5-3.358,7.5-7.5v-111C92.764,113.568,89.406,110.21,85.264,110.21z"/><path d="M125.551,111.481c-4.142,0-7.5,3.358-7.5,7.5v109.826c0,4.142,3.358,7.5,7.5,7.5c4.142,0,7.5-3.358,7.5-7.5V118.981C133.051,114.839,129.693,111.481,125.551,111.481z"/></g></svg>`
dailymotionIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 1024 1024">
<g fill="none" fill-rule="evenodd">
<path fill="#232323${this.hide ? "00" : ""}" d="M310.744275,457.219014 C290.104691,478.116711 264.241017,488.566555 233.154248,488.566555 C202.576055,488.566555 177.222946,478.372629 157.091937,457.983783 C136.961923,437.594936 126.896916,411.344856 126.896916,379.232547 C126.896916,348.648779 137.216708,323.289934 157.856292,303.15601 C178.496872,283.022086 203.84998,272.955622 233.918604,272.955622 C254.303403,272.955622 272.777313,277.669703 289.340336,287.099855 C305.903358,296.530008 318.771001,309.400623 327.94426,325.7117 C337.117519,342.021782 341.703651,359.8614 341.703651,379.232547 C341.703651,410.324169 331.383859,436.320322 310.744275,457.219014 Z M334.823458,27.524694 L334.823458,204.907162 C316.98651,187.067543 298.004024,174.196928 277.874011,166.296313 C257.743001,158.395697 235.192529,154.445389 210.220603,154.445389 C169.95958,154.445389 133.777109,164.384391 101.670205,184.264388 C69.5633006,204.142393 44.5923698,231.284703 26.7554219,265.691317 C8.91847395,300.097932 0,338.199931 0,379.99632 C0,422.8124 8.7910814,461.424245 26.3732442,495.829864 C43.955407,530.236478 68.9263379,557.378788 101.288027,577.257789 C133.649717,597.137786 170.724931,607.076788 212.513669,607.076788 C273.159491,607.076788 315.457799,587.197787 339.41158,547.439785 L340.939296,547.439785 L340.939296,601.809047 L461.720374,601.809047 L461.720374,0 L334.823458,27.524694 Z" transform="translate(248 202)"/>
</g>
</svg>`
// #0061d1
// #324b73
// - https://lucide.dev/icon/package-open?search=package-open
dropboxIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#0061fe${this.hide ? "00" : ""}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.91 8.84 8.56 2.23a1.93 1.93 0 0 0-1.81 0L3.1 4.13a2.12 2.12 0 0 0-.05 3.69l12.22 6.93a2 2 0 0 0 1.94 0L21 12.51a2.12 2.12 0 0 0-.09-3.67Z"></path><path d="m3.09 8.84 12.35-6.61a1.93 1.93 0 0 1 1.81 0l3.65 1.9a2.12 2.12 0 0 1 .1 3.69L8.73 14.75a2 2 0 0 1-1.94 0L3 12.51a2.12 2.12 0 0 1 .09-3.67Z"></path><line x1="12" y1="22" x2="12" y2="13"></line><path d="M20 13.5v3.37a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13.5"></path></svg>`
// #0061fe
// from: https://www.flaticon.com/free-icon/spotify_1946539
spotifyIcon = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0 0 512 512" stroke="#1ed760${this.hide ? "00" : ""}" fill="#1ed760${this.hide ? "00" : ""}" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><path d="M436.8,75.2C390.5,28.8,326.4,0,255.6,0C114.5,0,0,114.5,0,255.6c0,70.8,28.8,134.8,75.2,181.1c46.3,46.5,110.4,75.2,181.1,75.2C397.5,512,512,397.5,512,256.4C512,185.6,483.2,121.5,436.8,75.2z M256,475.1c-120.8,0-219.1-98.3-219.1-219.1S135.2,36.9,256,36.9S475.1,135.2,475.1,256S376.8,475.1,256,475.1z"/><path d="M406.5,195.9c-81.3-48.3-210-52.8-287.4-29.3c-8.5,2.6-14.6,10.4-14.6,19.6c0,11.3,9.2,20.5,20.5,20.5l6.1-0.9l-0.1,0c67.4-20.5,183.9-16.6,254.6,25.3c3,1.8,6.6,2.9,10.5,2.9c11.3,0,20.5-9.2,20.5-20.5C416.6,206.1,412.6,199.5,406.5,195.9L406.5,195.9L406.5,195.9z"/><path d="M351.9,334.1c-57.8-35.3-129.3-43.5-212.8-24.4c-6.1,1.4-10.6,6.9-10.6,13.3c0,7.5,6.1,13.7,13.7,13.7l3.1-0.4l-0.1,0c76.3-17.4,141-10.3,192.5,21.1c2,1.3,4.5,2,7.2,2c7.5,0,13.7-6.1,13.7-13.7C358.5,340.9,355.9,336.6,351.9,334.1L351.9,334.1z"/><path d="M377.7,269.8c-67.6-41.6-166.5-53.3-246.1-29.1c-7.1,2.2-12.1,8.7-12.1,16.3c0,9.4,7.6,17.1,17.1,17.1l5.1-0.8l-0.1,0c69.7-21.2,159.4-10.7,218.3,25.5c2.5,1.6,5.6,2.5,8.9,2.5c6.1,0,11.5-3.2,14.5-8.1l0-0.1c1.6-2.5,2.5-5.6,2.5-8.9C385.9,278.2,382.6,272.8,377.7,269.8L377.7,269.8L377.7,269.8z"/></g></svg>`
// manually edited this one: https://upload.wikimedia.org/wikipedia/commons/thumb/d/db/Deezer_logo.svg/2560px-Deezer_logo.svg.png
// The icon doesn't hide when this.hide is set to true...
// deezerIcon = `<svg version="1.1" id="Calque_1" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="22" height="22" viewBox="0 0 198.4 129.7" xml:space="preserve"><style type="text/css">.st0{fill-rule:evenodd;clip-rule:evenodd;fill:#40AB5D${this.hide ? "00" : ""};}.st1{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8192_1_);}.st2{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8199_1_);}.st3{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8206_1_);}.st4{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8213_1_);}.st5{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8220_1_);}.st6{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8227_1_);}.st7{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8234_1_);}.st8{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8241_1_);}.st9{fill-rule:evenodd;clip-rule:evenodd;fill:url(#rect8248_1_);}</style><g id="g8252" transform="translate(0,25.2)"><rect id="rect8185" x="155.5" y="-25.1" class="st0" width="42.9" height="25.1"/><linearGradient id="rect8192_1_" gradientUnits="userSpaceOnUse" x1="-111.7225" y1="241.8037" x2="-111.9427" y2="255.8256" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"><stop offset="0" style="stop-color:#358C7B${this.hide ? "00" : ""}"/><stop offset="0.5256" style="stop-color:#33A65E${this.hide ? "00" : ""}"/></linearGradient><rect id="rect8192" x="155.5" y="9.7" class="st1" width="42.9" height="25.1"/><linearGradient id="rect8199_1_" gradientUnits="userSpaceOnUse" x1="-123.8913" y1="223.6279" x2="-99.7725" y2="235.9171" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"><stop offset="0" style="stop-color:#222B90${this.hide ? "00" : ""}"/><stop offset="1" style="stop-color:#367B99${this.hide ? "00" : ""}"/></linearGradient><rect id="rect8199" x="155.5" y="44.5" class="st2" width="42.9" height="25.1"/><linearGradient id="rect8206_1_" gradientUnits="userSpaceOnUse" x1="-208.4319" y1="210.7725" x2="-185.0319" y2="210.7725" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"><stop offset="0" style="stop-color:#FF9900${this.hide ? "00" : ""}"/><stop offset="1" style="stop-color:#FF8000${this.hide ? "00" : ""}"/></linearGradient><rect id="rect8206" x="0" y="79.3" class="st3" width="42.9" height="25.1"/> <linearGradient id="rect8213_1_" gradientUnits="userSpaceOnUse" x1="-180.1319" y1="210.7725" x2="-156.7319" y2="210.7725" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"> <stop offset="0" style="stop-color:#FF8000${this.hide ? "00" : ""}"/> <stop offset="1" style="stop-color:#CC1953${this.hide ? "00" : ""}"/> </linearGradient> <rect id="rect8213" x="51.8" y="79.3" class="st4" width="42.9" height="25.1"/> <linearGradient id="rect8220_1_" gradientUnits="userSpaceOnUse" x1="-151.8319" y1="210.7725" x2="-128.4319" y2="210.7725" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"> <stop offset="0" style="stop-color:#CC1953${this.hide ? "00" : ""}"/> <stop offset="1" style="stop-color:#241284${this.hide ? "00" : ""}"/> </linearGradient> <rect id="rect8220" x="103.7" y="79.3" class="st5" width="42.9" height="25.1"/> <linearGradient id="rect8227_1_" gradientUnits="userSpaceOnUse" x1="-123.5596" y1="210.7725" x2="-100.1596" y2="210.7725" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"> <stop offset="0" style="stop-color:#222B90${this.hide ? "00" : ""}"/> <stop offset="1" style="stop-color:#3559A6${this.hide ? "00" : ""}"/> </linearGradient> <rect id="rect8227" x="155.5" y="79.3" class="st6" width="42.9" height="25.1"/> <linearGradient id="rect8234_1_" gradientUnits="userSpaceOnUse" x1="-152.7555" y1="226.0811" x2="-127.5083" y2="233.4639" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"> <stop offset="0" style="stop-color:#CC1953${this.hide ? "00" : ""}"/> <stop offset="1" style="stop-color:#241284${this.hide ? "00" : ""}"/> </linearGradient> <rect id="rect8234" x="103.7" y="44.5" class="st7" width="42.9" height="25.1"/> <linearGradient id="rect8241_1_" gradientUnits="userSpaceOnUse" x1="-180.9648" y1="234.3341" x2="-155.899" y2="225.2108" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"> <stop offset="2.669841e-03" style="stop-color:#FFCC00${this.hide ? "00" : ""}"/> <stop offset="0.9999" style="stop-color:#CE1938${this.hide ? "00" : ""}"/> </linearGradient> <rect id="rect8241" x="51.8" y="44.5" class="st8" width="42.9" height="25.1"/> <linearGradient id="rect8248_1_" gradientUnits="userSpaceOnUse" x1="-178.1651" y1="257.7539" x2="-158.6987" y2="239.791" gradientTransform="matrix(1.8318 0 0 -1.8318 381.8134 477.9528)"> <stop offset="2.669841e-03" style="stop-color:#FFD100${this.hide ? "00" : ""}"/> <stop offset="1" style="stop-color:#FD5A22${this.hide ? "00" : ""}"/> </linearGradient> <rect id="rect8248" x="51.8" y="9.7" class="st9" width="42.9" height="25.1"/> </g> </svg>`
// ----------------
// - Other icons
// ----------------
linkIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="${this.hide ? "transparent" : "currentColor"}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg>`
mediaIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#888" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12a5 5 0 0 0 5 5 8 8 0 0 1 5 2 8 8 0 0 1 5-2 5 5 0 0 0 5-5V7h-5a8 8 0 0 0-5 2 8 8 0 0 0-5-2H2Z"></path><path d="M6 11c1.5 0 3 .5 3 2-2 0-3 0-3-2Z"></path><path d="M18 11c-1.5 0-3 .5-3 2 2 0 3 0 3-2Z"></path></svg>`
playIcon = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd" />
</svg>`
pauseIcon = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
</svg>`
filePlusIcon = (size) => `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="12" y1="18" x2="12" y2="12"></line><line x1="9" y1="15" x2="15" y2="15"></line></svg>`
filterIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"></polygon></svg>';
// Taken from Alexandru Dinu Sortable plugin
sortIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 100 100" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path fill="currentColor" d="M49.792 33.125l-5.892 5.892L33.333 28.45V83.333H25V28.45L14.438 39.017L8.542 33.125L29.167 12.5l20.625 20.625zm41.667 33.75L70.833 87.5l-20.625 -20.625l5.892 -5.892l10.571 10.567L66.667 16.667h8.333v54.883l10.567 -10.567l5.892 5.892z"></path></svg>'
saveIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>'
listMusicIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15V6"></path><path d="M18.5 18a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z"></path><path d="M12 12H3"></path><path d="M16 6H3"></path><path d="M12 18H3"></path></svg>'
micOffIcon = (size) => `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"></line><path d="M18.89 13.23A7.12 7.12 0 0 0 19 12v-2"></path><path d="M5 10v2a7 7 0 0 0 12 5"></path><path d="M15 9.34V5a3 3 0 0 0-5.68-1.33"></path><path d="M9 9v3a3 3 0 0 0 5.12 2.12"></path><line x1="12" y1="19" x2="12" y2="22"></line></svg>`
mic2Icon = (size) => `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 8-9.04 9.06a2.82 2.82 0 1 0 3.98 3.98L16 12"></path><circle cx="17" cy="7" r="5"></circle></svg>`
venetianMaskIcon = (size) => `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12a5 5 0 0 0 5 5 8 8 0 0 1 5 2 8 8 0 0 1 5-2 5 5 0 0 0 5-5V7h-5a8 8 0 0 0-5 2 8 8 0 0 0-5-2H2Z"></path><path d="M6 11c1.5 0 3 .5 3 2-2 0-3 0-3-2Z"></path><path d="M18 11c-1.5 0-3 .5-3 2 2 0 3 0 3-2Z"></path></svg>`
imageOffIcon = (size) => `<svg xmlns='http://www.w3.org/2000/svg' width='${size}' height='${size}' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='lucide lucide-image-off'><line x1='2' x2='22' y1='2' y2='22'/><path d='M10.41 10.41a2 2 0 1 1-2.83-2.83'/><line x1='13.5' x2='6' y1='13.5' y2='21'/><line x1='18' x2='21' y1='12' y2='15'/><path d='M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59'/><path d='M21 15V5a2 2 0 0 0-2-2H9'/></svg>`
eraserIcon = (size) => `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-eraser"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>`
customObsidianIcon = (color = "#6C31E3", id="") => `<svg id="custom-logo" width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg" style="height:100%;width:100%;">
<defs>
<radialGradient id="b${id}" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-48 -185 123 -32 179 429.7)"><stop stop-color="#fff" stop-opacity=".4"/><stop offset="1" stop-opacity=".1"/></radialGradient>
<radialGradient id="c${id}" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(41 -310 229 30 341.6 351.3)"><stop stop-color="#fff" stop-opacity=".6"/><stop offset="1" stop-color="#fff" stop-opacity=".1"/></radialGradient>
<radialGradient id="d${id}" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(57 -261 178 39 190.5 296.3)"><stop stop-color="#fff" stop-opacity=".8"/><stop offset="1" stop-color="#fff" stop-opacity=".4"/></radialGradient>
<radialGradient id="e${id}" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-79 -133 153 -90 321.4 464.2)"><stop stop-color="#fff" stop-opacity=".3"/><stop offset="1" stop-opacity=".3"/></radialGradient>
<radialGradient id="f${id}" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-29 136 -92 -20 300.7 149.9)"><stop stop-color="#fff" stop-opacity="0"/><stop offset="1" stop-color="#fff" stop-opacity=".2"/></radialGradient>
<radialGradient id="g${id}" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(72 73 -155 153 137.8 225.2)"><stop stop-color="#fff" stop-opacity=".2"/><stop offset="1" stop-color="#fff" stop-opacity=".4"/></radialGradient>
<radialGradient id="h${id}" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(20 118 -251 43 215.1 273.7)"><stop stop-color="#fff" stop-opacity=".1"/><stop offset="1" stop-color="#fff" stop-opacity=".3"/></radialGradient>
<radialGradient id="i${id}" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-162 -85 268 -510 374.4 371.7)"><stop stop-color="#fff" stop-opacity=".2"/><stop offset=".5" stop-color="#fff" stop-opacity=".2"/><stop offset="1" stop-color="#fff" stop-opacity=".3"/></radialGradient>
<filter id="a${id}" x="80.1" y="37" width="351.1" height="443.2" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="6.5" result="effect1_foregroundBlur_744_9191"/></filter>
</defs>
<g filter="url(#a${id})"><path d="M359.2 437.5c-2.6 19-21.3 33.9-40 28.7-26.5-7.2-57.2-18.6-84.8-20.7l-42.4-3.2a28 28 0 0 1-18-8.3l-73-74.8a27.7 27.7 0 0 1-5.4-30.7s45-98.6 46.8-103.7c1.6-5.1 7.8-49.9 11.4-73.9a28 28 0 0 1 9-16.5L249 57.2a28 28 0 0 1 40.6 3.4l72.6 91.6a29.5 29.5 0 0 1 6.2 18.3c0 17.3 1.5 53 11.2 76a301.3 301.3 0 0 0 35.6 58.2 14 14 0 0 1 1 15.6c-6.3 10.7-18.9 31.3-36.6 57.6a142.2 142.2 0 0 0-20.5 59.6Z" fill="#000" fill-opacity=".3"/></g>
<path id="arrow" d="M359.9 434.3c-2.6 19.1-21.3 34-40 28.9-26.4-7.3-57-18.7-84.7-20.8l-42.3-3.2a27.9 27.9 0 0 1-18-8.4l-73-75a27.9 27.9 0 0 1-5.4-31s45.1-99 46.8-104.2c1.7-5.1 7.8-50 11.4-74.2a28 28 0 0 1 9-16.6l86.2-77.5a28 28 0 0 1 40.6 3.5l72.5 92a29.7 29.7 0 0 1 6.2 18.3c0 17.4 1.5 53.2 11.1 76.3a303 303 0 0 0 35.6 58.5 14 14 0 0 1 1.1 15.7c-6.4 10.8-18.9 31.4-36.7 57.9a143.3 143.3 0 0 0-20.4 59.8Z" fill="${color}"/>
<path d="M182.7 436.4c33.9-68.7 33-118 18.5-153-13.2-32.4-37.9-52.8-57.3-65.5-.4 1.9-1 3.7-1.8 5.4L96.5 324.8a27.9 27.9 0 0 0 5.5 31l72.9 75c2.3 2.3 5 4.2 7.8 5.6Z" fill="url(#b${id})"/>
<path d="M274.9 297c9.1.9 18 2.9 26.8 6.1 27.8 10.4 53.1 33.8 74 78.9 1.5-2.6 3-5.1 4.6-7.5a1222 1222 0 0 0 36.7-57.9 14 14 0 0 0-1-15.7 303 303 0 0 1-35.7-58.5c-9.6-23-11-58.9-11.1-76.3 0-6.6-2.1-13.1-6.2-18.3l-72.5-92-1.2-1.5c5.3 17.5 5 31.5 1.7 44.2-3 11.8-8.6 22.5-14.5 33.8-2 3.8-4 7.7-5.9 11.7a140 140 0 0 0-15.8 58c-1 24.2 3.9 54.5 20 95Z" fill="url(#c${id})"/>
<path d="M274.8 297c-16.1-40.5-21-70.8-20-95 1-24 8-42 15.8-58l6-11.7c5.8-11.3 11.3-22 14.4-33.8a78.5 78.5 0 0 0-1.7-44.2 28 28 0 0 0-39.4-2l-86.2 77.5a28 28 0 0 0-9 16.6L144.2 216c0 .7-.2 1.3-.3 2 19.4 12.6 44 33 57.3 65.3 2.6 6.4 4.8 13.1 6.4 20.4a200 200 0 0 1 67.2-6.8Z" fill="url(#d${id})"/>
<path d="M320 463.2c18.6 5.1 37.3-9.8 39.9-29a153 153 0 0 1 15.9-52.2c-21-45.1-46.3-68.5-74-78.9-29.5-11-61.6-7.3-94.2.6 7.3 33.1 3 76.4-24.8 132.7 3.1 1.6 6.6 2.5 10.1 2.8l43.9 3.3c23.8 1.7 59.3 14 83.2 20.7Z" fill="url(#e${id})"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M255 200.5c-1.1 24 1.9 51.4 18 91.8l-5-.5c-14.5-42.1-17.7-63.7-16.6-88 1-24.3 8.9-43 16.7-59 2-4 6.6-11.5 8.6-15.3 5.8-11.3 9.7-17.2 13-27.5 4.8-14.4 3.8-21.2 3.2-28 3.7 24.5-10.4 45.8-21 67.5a145 145 0 0 0-17 59Z" fill="url(#f${id})"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M206 285.1c2 4.4 3.7 8 4.9 13.5l-4.3 1c-1.7-6.4-3-11-5.5-16.5-14.6-34.3-38-52-57-65 23 12.4 46.7 31.9 61.9 67Z" fill="url(#g${id})"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M211.1 303c8 37.5-1 85.2-27.5 131.6 22.2-46 33-90.1 24-131l3.5-.7Z" fill="url(#h${id})"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M302.7 299.5c43.5 16.3 60.3 52 72.8 81.9-15.5-31.2-37-65.7-74.4-78.5-28.4-9.8-52.4-8.6-93.5.7l-.9-4c43.6-10 66.4-11.2 96 0Z" fill="url(#i${id})"/>
</svg>`
}
/**
* Class that contains functions used to measure performance and log things in file
* TODO: Ease the writing of nested callout inside debug file
*/
Logger = class {
/**
* @param {object} _
* @param {'console' | 'file' | 'both'} _.output
* TODO: Fails silently if output is set to 'file' or 'both' yet the filepath isn't specified
* TODO: Supports "level" property
*/
constructor({app, output = 'console', filepath = '', level = "debug", dry = false} = {}) {
this.inceptionTime = performance.now()
this.startTime = this.inceptionTime
this.perfTime = null
this.app = app
this.dry = dry
this.level = level
this.output = output
this.filepath = filepath
/** @private */
this.methods = new Map()
this.methods.set("console", {
log: (...vargs) => console.log.apply(this, vargs),
info: (...vargs) => console.info.apply(this, vargs),
warn: (...vargs) => console.warn.apply(this, vargs),
error: (...vargs) => console.error.apply(this, vargs),
clear: () => console.clear(),
})
this.methods.set("file", {
log: (...vargs) => this.#fileLoggingMethod("", ...vargs),
info: (...vargs) => this.#fileLoggingMethod("info", ...vargs),
warn: (...vargs) => this.#fileLoggingMethod("warning", ...vargs),
error: (...vargs) => this.#fileLoggingMethod("error", ...vargs),
clear: () => this.clearNote(this.filepath),
})
}
#fileLoggingMethod(calloutType, ...vargs) {
if (calloutType) {
this.appendCalloutHeadToNote({
path: this.filepath,
text: vargs[0],
type: calloutType.toUpperCase(),
mode: '+',
})
}
for (let i = 0; i < vargs.length; i++) {
if (i === 0 && calloutType) continue
this.appendTextToNote(this.filepath, vargs[i])
}
}
#method(method, ...vargs) {
if (this.dry) return
if (this.output !== 'file') {
this.methods.get("console")[method](...vargs)
}
if (this.output !== 'console') {
this.methods.get("file")[method](...vargs)
}
}
log(...vargs) { this.#method("log", ...vargs) }
info(...vargs) { this.#method("info", ...vargs) }
warn(...vargs) { this.#method("warn", ...vargs) }
error(...vargs) { this.#method("error", ...vargs) }
clear() { this.#method("clear") }
/**
* Hacky but it's for debug purposes
* @param {number} duration
* @returns {string} The duration expressed as a string
*/
#buildDurationLog = (duration) => {
if (duration >= 1000) {
return `${(duration / 1000.0).toPrecision(3)} seconds`
}
return `${duration.toPrecision(3)} milliseconds`
}
/**
* Log how many time occured since the last time this function was called
* or since inception time if this function was called for the first time
* @param {string} label
*/
logPerf = (label) => {
if (this.dry) return
this.perfTime = performance.now()
this.info(
`${label} took ${this.#buildDurationLog(
this.perfTime - this.startTime
)}`
)
this.startTime = this.perfTime
}