-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.ts
More file actions
2898 lines (2616 loc) · 113 KB
/
main.ts
File metadata and controls
2898 lines (2616 loc) · 113 KB
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
import {
App,
Plugin,
PluginSettingTab,
Setting,
MarkdownView,
MarkdownRenderer,
AbstractInputSuggest,
Component,
TFile,
getAllTags,
ItemView,
WorkspaceLeaf,
debounce,
} from 'obsidian';
// --- Enums ---
/** Defines the type of a rule, determining how it matches files (e.g., by folder, tag, or property). */
enum RuleType {
Folder = 'folder',
Tag = 'tag',
Property = 'property',
Multi = 'multi',
Dataview = 'dataview',
}
/** Defines the source of the content for a rule (e.g., direct text input or a markdown file). */
enum ContentSource {
Text = 'text',
File = 'file',
}
/** Defines where the dynamic content should be rendered within the Markdown view (e.g., header or footer). */
enum RenderLocation {
Footer = 'footer',
Header = 'header',
Sidebar = 'sidebar',
}
// --- Interfaces ---
/**
* Represents a single condition for a 'Multi' rule type.
*/
interface SubCondition {
/** The type of condition (folder, tag, or property). */
type: 'folder' | 'tag' | 'property';
/** Whether this condition should be negated (not met). Defaults to false. */
negated?: boolean;
/** For 'folder' type: path to the folder. */
path?: string;
/** For 'folder' type: whether to match subfolders. */
recursive?: boolean;
/** For 'tag' type: the tag name (without '#'). */
tag?: string;
/** For 'tag' type: whether to match subtags. */
includeSubtags?: boolean;
/** For 'property' type: the name of the frontmatter property. */
propertyName?: string;
/** For 'property' type: the value the frontmatter property should have. */
propertyValue?: string;
}
/**
* Represents a rule for injecting dynamic content into Markdown views.
* Each rule specifies matching criteria (type: folder/tag/property), content source (text/file),
* the content itself, and where it should be rendered (header/footer).
*/
interface Rule {
/** A descriptive name for this rule. */
name?: string;
/** Whether this rule is currently active. */
enabled?: boolean;
/** The type of criteria for this rule (folder-based, tag-based, or property-based). */
type: RuleType;
/** Whether this rule's condition should be negated (not met). Defaults to false. */
negated?: boolean;
/** For 'folder' type: path to the folder. "" for all files, "/" for root. */
path?: string;
/** For 'tag' type: the tag name (without '#'). */
tag?: string;
/** For 'folder' type: whether to match subfolders. Defaults to true. Ignored if path is "". */
recursive?: boolean;
/** For 'tag' type: whether to match subtags (e.g., 'tag' matches 'tag/subtag'). Defaults to false. */
includeSubtags?: boolean;
/** For 'property' type: the name of the frontmatter property. */
propertyName?: string;
/** For 'property' type: the value the frontmatter property should have. */
propertyValue?: string;
/** For 'multi' type: an array of sub-conditions. */
conditions?: SubCondition[];
/** For 'multi' type: specifies whether ANY or ALL conditions must be met. Defaults to 'any'. */
multiConditionLogic?: 'any' | 'all';
/** For 'dataview' type: the Dataview query to use for matching files. */
dataviewQuery?: string;
/** The source from which to get the content (direct text or a file). */
contentSource: ContentSource;
/** Direct text content if contentSource is 'text'. */
footerText: string; // Retained name for compatibility, though it can be header or footer content.
/** Path to a .md file if contentSource is 'file'. */
footerFilePath?: string; // Retained name for compatibility.
/** Specifies whether to render in the header or footer. */
renderLocation: RenderLocation;
/** For 'sidebar' location: whether to show in a separate tab. */
showInSeparateTab?: boolean;
/** For 'sidebar' location: the name of the separate tab. */
sidebarTabName?: string;
/** For 'header' location: whether to render above the properties section. */
renderAboveProperties?: boolean;
/** For 'footer' location: whether to render above the backlinks section. */
renderAboveBacklinks?: boolean;
/** Whether to show this rule's content in popover views. */
showInPopover?: boolean;
}
/**
* Defines the settings structure for the VirtualFooter plugin.
* Contains an array of rules that dictate content injection.
*/
interface VirtualFooterSettings {
rules: Rule[];
/** Whether to refresh the view on file open. Defaults to false. */
refreshOnFileOpen?: boolean;
/** Whether to render content in source mode. Defaults to false. */
renderInSourceMode?: boolean;
/** Whether to refresh the view when note metadata changes. Defaults to false. */
refreshOnMetadataChange?: boolean;
/** Whether to treat property values as links for matching file targets. */
smartPropertyLinks?: boolean;
}
/**
* Extends HTMLElement to associate an Obsidian Component for lifecycle management.
* This allows Obsidian to manage resources tied to the DOM element.
*/
interface HTMLElementWithComponent extends HTMLElement {
/** The Obsidian Component associated with this HTML element. */
component?: Component;
}
// --- Constants ---
/** Default settings for the plugin, used when no settings are found or for new rules. */
const DEFAULT_SETTINGS: VirtualFooterSettings = {
rules: [{
name: 'Default Rule',
enabled: true,
type: RuleType.Folder,
negated: false,
path: '', // Matches all files by default
recursive: true,
contentSource: ContentSource.Text,
footerText: '', // Default content is empty
renderLocation: RenderLocation.Footer,
showInSeparateTab: false,
sidebarTabName: '',
multiConditionLogic: 'any',
renderAboveProperties: false,
renderAboveBacklinks: false,
showInPopover: true,
}],
refreshOnFileOpen: false, // Default to false
renderInSourceMode: false, // Default to false
refreshOnMetadataChange: false, // Default to false
smartPropertyLinks: false, // Default to false
};
// CSS Classes for styling and identifying plugin-generated elements
const CSS_DYNAMIC_CONTENT_ELEMENT = 'virtual-footer-dynamic-content-element';
const CSS_HEADER_GROUP_ELEMENT = 'virtual-footer-header-group';
const CSS_FOOTER_GROUP_ELEMENT = 'virtual-footer-footer-group';
const CSS_HEADER_RENDERED_CONTENT = 'virtual-footer-header-rendered-content';
const CSS_FOOTER_RENDERED_CONTENT = 'virtual-footer-footer-rendered-content';
const CSS_VIRTUAL_FOOTER_CM_PADDING = 'virtual-footer-cm-padding'; // For CodeMirror live preview footer spacing
const CSS_VIRTUAL_FOOTER_REMOVE_FLEX = 'virtual-footer-remove-flex'; // For CodeMirror live preview footer layout
const CSS_ABOVE_BACKLINKS = 'virtual-footer-above-backlinks'; // For removing min-height when above backlinks
// DOM Selectors for targeting elements in Obsidian's interface
const SELECTOR_EDITOR_CONTENT_AREA = '.cm-editor .cm-content';
const SELECTOR_EDITOR_CONTENT_CONTAINER_PARENT = '.markdown-source-view.mod-cm6 .cm-contentContainer';
const SELECTOR_LIVE_PREVIEW_CONTENT_CONTAINER = '.cm-contentContainer';
const SELECTOR_EDITOR_SIZER = '.cm-sizer'; // Target for live preview footer injection
const SELECTOR_PREVIEW_HEADER_AREA = '.mod-header.mod-ui'; // Target for reading mode header injection
const SELECTOR_PREVIEW_FOOTER_AREA = '.mod-footer'; // Target for reading mode footer injection
const SELECTOR_EMBEDDED_BACKLINKS = '.embedded-backlinks'; // Target for positioning above backlinks
const SELECTOR_METADATA_CONTAINER = '.metadata-container'; // Target for positioning above properties
const VIRTUAL_CONTENT_VIEW_TYPE = 'virtual-content-view';
const VIRTUAL_CONTENT_SEPARATE_VIEW_TYPE_PREFIX = 'virtual-content-separate-view-';
function normalizeBoolean(value: unknown, fallback: boolean): boolean {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
if (typeof value === 'string') {
const normalized = value.trim().toLowerCase();
if (['true', '1', 'yes', 'on', 'not'].includes(normalized)) return true;
if (['false', '0', 'no', 'off', 'is', ''].includes(normalized)) return false;
}
return fallback;
}
// --- Utility Classes ---
/**
* A suggestion provider for input fields, offering autocompletion from a given set of strings.
*/
export class MultiSuggest extends AbstractInputSuggest<string> {
/**
* Creates an instance of MultiSuggest.
* @param inputEl The HTML input element to attach the suggester to.
* @param content The set of strings to use as suggestions.
* @param onSelectCb Callback function executed when a suggestion is selected.
* @param app The Obsidian App instance.
*/
constructor(
private inputEl: HTMLInputElement,
private content: Set<string>,
private onSelectCb: (value: string) => void,
app: App
) {
super(app, inputEl);
}
/**
* Filters the content set to find suggestions matching the input string.
* @param inputStr The current string in the input field.
* @returns An array of matching suggestion strings.
*/
getSuggestions(inputStr: string): string[] {
const lowerCaseInputStr = inputStr.toLocaleLowerCase();
return [...this.content].filter((contentItem) =>
contentItem.toLocaleLowerCase().includes(lowerCaseInputStr)
);
}
/**
* Renders a single suggestion item in the suggestion list.
* @param content The suggestion string to render.
* @param el The HTMLElement to render the suggestion into.
*/
renderSuggestion(content: string, el: HTMLElement): void {
el.setText(content);
}
/**
* Handles the selection of a suggestion.
* @param content The selected suggestion string.
* @param _evt The mouse or keyboard event that triggered the selection.
*/
selectSuggestion(content: string, _evt: MouseEvent | KeyboardEvent): void {
this.onSelectCb(content);
this.inputEl.value = content; // Update input field with selected value
this.inputEl.blur(); // Remove focus from input
this.close(); // Close the suggestion popover
}
}
// --- Sidebar View Class ---
export class VirtualContentView extends ItemView {
plugin: VirtualFooterPlugin;
viewContent: HTMLElement;
component: Component;
private contentProvider: () => { content: string, sourcePath: string } | null;
private viewId: string;
private tabName: string;
constructor(leaf: WorkspaceLeaf, plugin: VirtualFooterPlugin, viewId: string, tabName: string, contentProvider: () => { content: string, sourcePath: string } | null) {
super(leaf);
this.plugin = plugin;
this.viewId = viewId;
this.tabName = tabName;
this.contentProvider = contentProvider;
}
getViewType() {
return this.viewId;
}
getDisplayText() {
return this.tabName;
}
getIcon() {
return 'text-select';
}
protected async onOpen(): Promise<void> {
this.component = new Component();
this.component.load();
const container = this.containerEl.children[1];
container.empty();
this.viewContent = container.createDiv({ cls: 'virtual-content-sidebar-view' });
this.update();
}
protected async onClose(): Promise<void> {
this.component.unload();
}
update() {
if (!this.viewContent) return;
// Clean up previous content and component
this.viewContent.empty();
this.component.unload();
this.component = new Component();
this.component.load();
const data = this.contentProvider();
if (data && data.content && data.content.trim() !== '') {
MarkdownRenderer.render(this.app, data.content, this.viewContent, data.sourcePath, this.component);
this.plugin.attachInternalLinkHandlers(this.viewContent, data.sourcePath, this.component);
} else {
this.viewContent.createEl('p', {
text: 'No virtual content to display for the current note.',
cls: 'virtual-content-sidebar-empty'
});
}
}
}
// --- Main Plugin Class ---
/**
* VirtualFooterPlugin dynamically injects content into the header or footer of Markdown views
* based on configurable rules.
*/
export default class VirtualFooterPlugin extends Plugin {
settings: VirtualFooterSettings;
/** Stores pending content injections for preview mode, awaiting DOM availability. */
private pendingPreviewInjections: WeakMap<MarkdownView, {
headerDiv?: HTMLElementWithComponent,
footerDiv?: HTMLElementWithComponent,
headerAbovePropertiesDiv?: HTMLElementWithComponent,
footerAboveBacklinksDiv?: HTMLElementWithComponent,
filePath?: string
}> = new WeakMap();
/** Manages MutationObservers for views in preview mode to detect when injection targets are ready. */
private previewObservers: WeakMap<MarkdownView, MutationObserver> = new WeakMap();
private initialLayoutReadyProcessed = false;
private lastSidebarContent: { content: string, sourcePath: string } | null = null;
private lastSeparateTabContents: Map<string, { content: string, sourcePath: string }> = new Map();
private lastHoveredLink: HTMLElement | null = null;
private popoverObserver: MutationObserver | null = null;
/**
* Called when the plugin is loaded.
*/
async onload() {
await this.loadSettings();
this.addSettingTab(new VirtualFooterSettingTab(this.app, this));
this.registerView(
VIRTUAL_CONTENT_VIEW_TYPE,
(leaf) => new VirtualContentView(leaf, this, VIRTUAL_CONTENT_VIEW_TYPE, 'Virtual Content', () => this.getLastSidebarContent())
);
this.registerDynamicViews();
this.addRibbonIcon('text-select', 'Open virtual content in sidebar', () => {
this.activateView(VIRTUAL_CONTENT_VIEW_TYPE);
});
this.addCommand({
id: 'open-virtual-content-sidebar',
name: 'Open virtual content in sidebar',
callback: () => {
this.activateView(VIRTUAL_CONTENT_VIEW_TYPE);
},
});
this.addCommand({
id: 'open-all-virtual-content-sidebar-tabs',
name: 'Open all virtual footer sidebar tabs',
callback: () => {
this.activateAllSidebarViews();
},
});
// Define event handlers
const handleViewUpdate = () => {
// Always trigger an update if the layout is ready.
// Used for file-open and layout-change.
if (this.initialLayoutReadyProcessed) {
this.handleActiveViewChange();
}
};
const handleFocusChange = () => {
// This is the "focus change" or "switching files" part, conditional on the setting.
// Used for active-leaf-change.
if (this.settings.refreshOnFileOpen && this.initialLayoutReadyProcessed) {
this.handleActiveViewChange();
}
};
// Register event listeners
this.registerEvent(
this.app.workspace.on('file-open', handleViewUpdate)
);
this.registerEvent(
this.app.workspace.on('layout-change', handleViewUpdate)
);
this.registerEvent(
this.app.workspace.on('active-leaf-change', handleFocusChange)
);
// Listen for metadata changes on the current file
this.registerEvent(
this.app.metadataCache.on('changed', (file) => {
// Only refresh if the metadata change setting is enabled
if (this.settings.refreshOnMetadataChange && this.initialLayoutReadyProcessed) {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
// Only refresh if the changed file is the currently active one
if (activeView && activeView.file && file.path === activeView.file.path) {
this.handleActiveViewChange();
}
}
})
);
// Listen for hover events to detect when popovers are created
this.registerDomEvent(document, 'mouseover', (event: MouseEvent) => {
const target = event.target as HTMLElement;
// Check if the target is a link that could trigger a popover
if (target.matches('a.internal-link, .internal-link a, [data-href]')) {
// Store the last hovered link for popover file path extraction
this.lastHoveredLink = target;
// Delay to allow popover to be created
setTimeout(() => {this.processPopoverViews();}, 100);
}
});
// Listen for clicks to detect when popovers might switch to editing mode
this.registerDomEvent(document, 'click', (event: MouseEvent) => {
const target = event.target as HTMLElement;
// Check if the click is within a popover
const popover = target.closest('.popover.hover-popover');
if (popover) {
//console.log("VirtualContent: Click detected in popover, checking for mode change");
// Delay to allow any mode changes to complete
setTimeout(() => {this.processPopoverViews();}, 150);
}
});
// Also listen for DOM mutations to catch dynamically created popovers
this.popoverObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
mutation.addedNodes.forEach(node => {
if (node instanceof HTMLElement) {
// Check if a popover was added
if (node.classList.contains('popover') && node.classList.contains('hover-popover')) {
//console.log("VirtualContent: Popover created, processing views");
// Small delay to ensure the popover content is fully loaded
setTimeout(() => {this.processPopoverViews();}, 50);
}
// Also check for popovers added within other elements
const popovers = node.querySelectorAll('.popover.hover-popover');
if (popovers.length > 0) {
//console.log("VirtualContent: Popover(s) found in added content, processing views");
setTimeout(() => {this.processPopoverViews();}, 50);
}
}
});
}
// Listen for attribute changes that might indicate mode switching in popovers
if (mutation.type === 'attributes' && mutation.target instanceof HTMLElement) {
const target = mutation.target;
// Check if this is a popover that gained or lost the is-editing class
if (target.classList.contains('popover') && target.classList.contains('hover-popover')) {
if (mutation.attributeName === 'class') {
const hasEditingClass = target.classList.contains('is-editing');
//console.log(`VirtualContent: Popover mode changed, is-editing: ${hasEditingClass}`);
//setTimeout(() => {this.processPopoverViews();}, 100); // Slightly longer delay for mode changes
}
}
}
}
});
// Observe the entire document for popover creation
if (this.popoverObserver) {
this.popoverObserver.observe(document.body, {
childList: true,
subtree: true
});
}
// Initial processing for any currently active view, once layout is ready
this.app.workspace.onLayoutReady(() => {
if (!this.initialLayoutReadyProcessed) {
this.handleActiveViewChange(); // Process the initially open view
this.initialLayoutReadyProcessed = true;
}
});
}
/**
* Called when the plugin is unloaded.
* Cleans up all injected content and observers.
*/
async onunload() {
this.popoverObserver?.disconnect();
this.app.workspace.detachLeavesOfType(VIRTUAL_CONTENT_VIEW_TYPE);
this.settings.rules.forEach((rule, index) => {
if (rule.renderLocation === RenderLocation.Sidebar && rule.showInSeparateTab) {
this.app.workspace.detachLeavesOfType(this.getSeparateViewId(index));
}
});
this.clearAllViewsDynamicContent();
// Clean up any remaining DOM elements and components directly
document.querySelectorAll(`.${CSS_DYNAMIC_CONTENT_ELEMENT}`).forEach(el => {
const componentHolder = el as HTMLElementWithComponent;
if (componentHolder.component) {
componentHolder.component.unload();
}
el.remove();
});
// Remove custom CSS classes applied for styling
document.querySelectorAll(`.${CSS_VIRTUAL_FOOTER_CM_PADDING}`).forEach(el => el.classList.remove(CSS_VIRTUAL_FOOTER_CM_PADDING));
document.querySelectorAll(`.${CSS_VIRTUAL_FOOTER_REMOVE_FLEX}`).forEach(el => el.classList.remove(CSS_VIRTUAL_FOOTER_REMOVE_FLEX));
// WeakMaps will be garbage collected, but explicit clearing is good practice if needed.
// Observers and pending injections are cleared per-view in `removeDynamicContentFromView`.
this.previewObservers = new WeakMap();
this.pendingPreviewInjections = new WeakMap();
}
/**
* Handles changes to the active Markdown view, triggering content processing.
*/
private handleActiveViewChange = () => {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
this._processView(activeView);
}
/**
* Checks if a MarkdownView is displayed within a popover (hover preview).
* @param view The MarkdownView to check.
* @returns True if the view is in a popover, false otherwise.
*/
private isInPopover(view: MarkdownView): boolean {
// Check if the view's container element is within a popover
let element: HTMLElement | null = view.containerEl;
// Debug: Log the container element and its classes
//console.log("VirtualContent: Checking popover for view container:", view.containerEl.className);
while (element) {
// Check for popover classes
if (element.classList.contains('popover') && element.classList.contains('hover-popover')) {
//console.log("VirtualContent: Found popover via direct popover classes");
return true;
}
// Also check for markdown-embed class which indicates an embedded view (often in popovers)
if (element.classList.contains('markdown-embed')) {
// console.log("VirtualContent: Found markdown-embed, checking for parent popover");
// If it's a markdown-embed, check if it's inside a popover
let parent = element.parentElement;
while (parent) {
if (parent.classList.contains('popover') && parent.classList.contains('hover-popover')) {
// console.log("VirtualContent: Found popover via markdown-embed parent");
return true;
}
parent = parent.parentElement;
}
}
element = element.parentElement;
}
//console.log("VirtualContent: Not a popover view");
return false;
}
/**
* Processes any popover views that might be open but haven't been processed yet.
*/
private processPopoverViews(): void {
// Find all popover elements in the DOM
const popovers = document.querySelectorAll('.popover.hover-popover');
popovers.forEach(popover => {
// Look for markdown views within each popover
const markdownEmbed = popover.querySelector('.markdown-embed');
if (markdownEmbed) {
//console.log("VirtualContent: Found markdown-embed in popover, processing directly");
// Process the popover content directly
this.processPopoverDirectly(popover as HTMLElement);
}
});
}
/**
* Process popover content directly when we can't find the MarkdownView
*/
private processPopoverDirectly(popover: HTMLElement): void {
// console.log("VirtualContent: Processing popover directly");
// Try to extract the file path from the popover
const markdownEmbed = popover.querySelector('.markdown-embed');
if (!markdownEmbed) {
//console.log("VirtualContent: No markdown-embed found in popover");
return;
}
let filePath: string | null = null;
// Method 1: Get the title from inline-title and resolve to file path
const inlineTitle = popover.querySelector('.inline-title');
if (inlineTitle) {
const title = inlineTitle.textContent?.trim();
//console.log("VirtualContent: Found inline-title:", title);
if (title) {
// Try to resolve the title to a file path using Obsidian's API
const file = this.app.metadataCache.getFirstLinkpathDest(title, '');
if (file) {
filePath = file.path;
//console.log("VirtualContent: Resolved title to file path:", filePath);
} else {
// If direct resolution fails, try with .md extension
const fileWithExt = this.app.metadataCache.getFirstLinkpathDest(title + '.md', '');
if (fileWithExt) {
filePath = fileWithExt.path;
//console.log("VirtualContent: Resolved title with .md extension to file path:", filePath);
} else {
//console.log("VirtualContent: Could not resolve title to file path");
}
}
}
}
//console.log("VirtualContent: Final extracted file path for direct processing:", filePath);
if (filePath) {
// Remove any hash fragments or block references
const cleanPath = filePath.split('#')[0].split('^')[0];
//console.log("VirtualContent: Cleaned file path:", cleanPath);
// Process the popover content directly
this.injectContentIntoPopover(popover, cleanPath);
} else {
// console.log("VirtualContent: Could not determine file path for popover");
// // Log the DOM structure for debugging
// console.log("VirtualContent: Popover DOM structure:", popover.innerHTML.substring(0, 1000));
}
}
/**
* Directly inject virtual content into a popover
*/
private async injectContentIntoPopover(popover: HTMLElement, filePath: string): Promise<void> {
//console.log("VirtualContent: Directly injecting content into popover for:", filePath);
try {
const applicableRulesWithContent = await this._getApplicableRulesAndContent(filePath);
// Filter rules based on popover visibility setting
const filteredRules = applicableRulesWithContent.filter(({ rule }) => {
return rule.showInPopover !== false; // Show by default unless explicitly disabled
});
if (filteredRules.length === 0) {
//console.log("VirtualContent: No applicable rules for popover");
return;
}
// Find the markdown embed container
const markdownEmbed = popover.querySelector('.markdown-embed');
if (!markdownEmbed) return;
// Group content by render location
const headerContentGroups: { normal: string[], aboveProperties: string[] } = { normal: [], aboveProperties: [] };
const footerContentGroups: { normal: string[], aboveBacklinks: string[] } = { normal: [], aboveBacklinks: [] };
const contentSeparator = "\n\n";
for (const { rule, contentText } of filteredRules) {
if (!contentText || contentText.trim() === "") continue;
if (rule.renderLocation === RenderLocation.Header) {
if (rule.renderAboveProperties) {
headerContentGroups.aboveProperties.push(contentText);
} else {
headerContentGroups.normal.push(contentText);
}
} else if (rule.renderLocation === RenderLocation.Footer) {
// For popovers, treat all footer content the same regardless of renderAboveBacklinks setting
// since backlinks don't exist in popovers
footerContentGroups.normal.push(contentText);
}
// Skip sidebar rules for popovers
}
// Inject header content
if (headerContentGroups.normal.length > 0) {
const combinedContent = headerContentGroups.normal.join(contentSeparator);
await this.injectContentIntoPopoverSection(markdownEmbed as HTMLElement, combinedContent, 'header', false, filePath);
}
if (headerContentGroups.aboveProperties.length > 0) {
const combinedContent = headerContentGroups.aboveProperties.join(contentSeparator);
await this.injectContentIntoPopoverSection(markdownEmbed as HTMLElement, combinedContent, 'header', true, filePath);
}
// Inject footer content
if (footerContentGroups.normal.length > 0) {
const combinedContent = footerContentGroups.normal.join(contentSeparator);
await this.injectContentIntoPopoverSection(markdownEmbed as HTMLElement, combinedContent, 'footer', false, filePath);
}
} catch (error) {
console.error("VirtualContent: Error processing popover directly:", error);
}
}
/**
* Inject content into a specific section of a popover
*/
private async injectContentIntoPopoverSection(
container: HTMLElement,
content: string,
location: 'header' | 'footer',
special: boolean,
filePath: string
): Promise<void> {
const isHeader = location === 'header';
const cssClass = isHeader ? CSS_HEADER_GROUP_ELEMENT : CSS_FOOTER_GROUP_ELEMENT;
const specialClass = isHeader ? 'virtual-footer-above-properties' : 'virtual-footer-above-backlinks';
// Create new content container
const groupDiv = document.createElement('div') as HTMLElementWithComponent;
groupDiv.className = `${CSS_DYNAMIC_CONTENT_ELEMENT} ${cssClass}`;
if (special) {
groupDiv.classList.add(specialClass);
}
// Add additional CSS classes for consistency with main view injection
if (isHeader) {
groupDiv.classList.add(CSS_HEADER_RENDERED_CONTENT);
} else {
groupDiv.classList.add(CSS_FOOTER_RENDERED_CONTENT);
if (special) {
groupDiv.classList.add(CSS_ABOVE_BACKLINKS);
}
}
// Create component for lifecycle management
const component = new Component();
component.load();
groupDiv.component = component;
try {
// Render the content
await MarkdownRenderer.render(this.app, content, groupDiv, filePath, component);
this.attachInternalLinkHandlers(groupDiv, filePath, component);
// Use the same logic as main view injection - find target parent using standard selectors
let targetParent: HTMLElement | null = null;
// First, detect if we're in editing mode or preview mode
// Check if the popover container has the is-editing class
const popoverContainer = container.closest('.popover.hover-popover');
const isEditingMode = popoverContainer?.classList.contains('is-editing') ||
container.querySelector(SELECTOR_EDITOR_SIZER) !== null;
//console.log(`VirtualContent: Popover is in ${isEditingMode ? 'editing' : 'preview'} mode`);
if (isHeader) {
if (special) {
// Try to find metadata container first (same as main view logic)
targetParent = container.querySelector<HTMLElement>(SELECTOR_METADATA_CONTAINER);
}
// If no metadata container or special is false, use appropriate header area
if (!targetParent) {
if (isEditingMode) {
// In editing mode, we need to find the content container and insert before it
const cmContentContainer = container.querySelector<HTMLElement>(SELECTOR_LIVE_PREVIEW_CONTENT_CONTAINER);
if (cmContentContainer?.parentElement) {
// We'll handle the insertion differently for editing mode headers
targetParent = cmContentContainer.parentElement;
}
} else {
// In preview mode, use regular header area
targetParent = container.querySelector<HTMLElement>(SELECTOR_PREVIEW_HEADER_AREA);
}
}
} else { // Footer
if (special) {
// Try to find embedded backlinks first (same as main view logic)
targetParent = container.querySelector<HTMLElement>(SELECTOR_EMBEDDED_BACKLINKS);
}
// If no backlinks or special is false, use appropriate footer area
if (!targetParent) {
if (isEditingMode) {
// In editing mode, use editor sizer
targetParent = container.querySelector<HTMLElement>(SELECTOR_EDITOR_SIZER);
} else {
// In preview mode, try standard footer area first
targetParent = container.querySelector<HTMLElement>(SELECTOR_PREVIEW_FOOTER_AREA);
// Fallback for popovers: use markdown-preview-sizer if standard footer selectors don't exist
if (!targetParent) {
targetParent = container.querySelector<HTMLElement>('.markdown-preview-sizer.markdown-preview-section');
}
}
}
}
if (targetParent) {
// Remove existing content of this type (same cleanup logic as main view)
if (isHeader && special) {
// Remove existing header content above properties
container.querySelectorAll(`.${CSS_HEADER_GROUP_ELEMENT}.virtual-footer-above-properties`).forEach(el => {
const holder = el as HTMLElementWithComponent;
holder.component?.unload();
el.remove();
});
} else if (isHeader && !special) {
// Remove existing normal header content
targetParent.querySelectorAll(`.${CSS_HEADER_GROUP_ELEMENT}:not(.virtual-footer-above-properties)`).forEach(el => {
const holder = el as HTMLElementWithComponent;
holder.component?.unload();
el.remove();
});
} else if (!isHeader && special) {
// Remove existing footer content above backlinks
container.querySelectorAll(`.${CSS_FOOTER_GROUP_ELEMENT}.virtual-footer-above-backlinks`).forEach(el => {
const holder = el as HTMLElementWithComponent;
holder.component?.unload();
el.remove();
});
} else if (!isHeader && !special) {
// Remove existing normal footer content
targetParent.querySelectorAll(`.${CSS_FOOTER_GROUP_ELEMENT}:not(.virtual-footer-above-backlinks)`).forEach(el => {
const holder = el as HTMLElementWithComponent;
holder.component?.unload();
el.remove();
});
}
// Insert using mode-specific logic
if (isHeader && !special) {
if (isEditingMode && targetParent.querySelector(SELECTOR_LIVE_PREVIEW_CONTENT_CONTAINER)) {
// For editing mode headers, insert before the content container
const cmContentContainer = targetParent.querySelector<HTMLElement>(SELECTOR_LIVE_PREVIEW_CONTENT_CONTAINER);
if (cmContentContainer) {
targetParent.insertBefore(groupDiv, cmContentContainer);
} else {
targetParent.appendChild(groupDiv);
}
} else {
// For preview mode headers, append to header area
targetParent.appendChild(groupDiv);
}
} else if (!isHeader && !special) {
// For footer content
if (isEditingMode) {
// In editing mode, append to editor sizer
targetParent.appendChild(groupDiv);
} else {
// In preview mode, check if we're using the popover fallback selector
if (targetParent.matches('.markdown-preview-sizer.markdown-preview-section')) {
// Insert after the markdown-preview-sizer, not inside it
targetParent.parentElement?.insertBefore(groupDiv, targetParent.nextSibling);
} else {
// For regular footer areas, append inside
targetParent.appendChild(groupDiv);
}
}
} else {
// Insert before properties or backlinks (same as main view)
targetParent.parentElement?.insertBefore(groupDiv, targetParent);
}
//console.log(`VirtualContent: Successfully injected ${location} content into popover using standard selectors`);
} else {
//console.log(`VirtualContent: Target parent not found for ${location} injection in popover, falling back to container`);
// Fallback to simple container injection if selectors don't match
if (isHeader) {
container.insertBefore(groupDiv, container.firstChild);
} else {
container.appendChild(groupDiv);
}
}
} catch (error) {
console.error("VirtualContent: Error rendering content for popover:", error);
component.unload();
}
}
/**
* Processes a given Markdown view to inject or update dynamic content.
* @param view The MarkdownView to process.
*/
private async _processView(view: MarkdownView | null): Promise<void> {
if (!view || !view.file) {
// If 'refresh on focus' is off, we clear the sidebar when focus is lost from a markdown file.
// If it's on, we only clear the sidebar if the last markdown file has been closed,
// preserving the content when switching to non-markdown views.
if (!this.settings.refreshOnFileOpen || this.app.workspace.getLeavesOfType('markdown').length === 0) {
this.lastSidebarContent = null;
this.lastSeparateTabContents.clear();
this.updateAllSidebarViews();
}
return; // No view or file to process
}
// Check if this is a popover view
const isPopoverView = this.isInPopover(view);
await this.removeDynamicContentFromView(view); // Clear existing content first
const applicableRulesWithContent = await this._getApplicableRulesAndContent(view.file.path);
// Filter rules based on popover visibility setting
const filteredRules = applicableRulesWithContent.filter(({ rule }) => {
if (isPopoverView && rule.showInPopover === false) {
return false; // Skip this rule in popover views
}
return true;
});
const viewState = view.getState();
let combinedHeaderText = "";
let combinedFooterText = "";
let combinedSidebarText = "";
let hasFooterRule = false;
const contentSeparator = "\n\n"; // Separator between content from multiple rules
this.lastSeparateTabContents.clear();
// Combine content from all applicable rules, grouping by render location and positioning
const headerContentGroups: { normal: string[], aboveProperties: string[] } = { normal: [], aboveProperties: [] };
const footerContentGroups: { normal: string[], aboveBacklinks: string[] } = { normal: [], aboveBacklinks: [] };
for (const { rule, contentText, index } of filteredRules) {
if (!contentText || contentText.trim() === "") continue; // Skip empty content
if (rule.renderLocation === RenderLocation.Header) {
if (rule.renderAboveProperties) {
headerContentGroups.aboveProperties.push(contentText);
} else {
headerContentGroups.normal.push(contentText);
}
} else if (rule.renderLocation === RenderLocation.Footer) {
if (rule.renderAboveBacklinks) {
footerContentGroups.aboveBacklinks.push(contentText);
} else {
footerContentGroups.normal.push(contentText);
}
hasFooterRule = true;
} else if (rule.renderLocation === RenderLocation.Sidebar) {
if (rule.showInSeparateTab) {
const viewId = this.getSeparateViewId(index);
const existingContent = this.lastSeparateTabContents.get(viewId)?.content || "";
this.lastSeparateTabContents.set(viewId, {
content: (existingContent ? existingContent + contentSeparator : "") + contentText,
sourcePath: view.file.path
});
} else {
combinedSidebarText += (combinedSidebarText ? contentSeparator : "") + contentText;
}
}
}
// Store sidebar content and update the view
this.lastSidebarContent = { content: combinedSidebarText, sourcePath: view.file.path };
this.updateAllSidebarViews();
// Determine if we should render based on view mode and settings
const isLivePreview = viewState.mode === 'source' && !viewState.source;
const isSourceMode = viewState.mode === 'source' && viewState.source;
const isReadingMode = viewState.mode === 'preview';
const shouldRenderInSource = isSourceMode && this.settings.renderInSourceMode;
const shouldRenderInLivePreview = isLivePreview;
const shouldRenderInReading = isReadingMode;
// Apply specific styles for Live Preview footers if needed
if ((shouldRenderInLivePreview || shouldRenderInSource) && hasFooterRule) {
this.applyLivePreviewFooterStyles(view);
}
let pendingHeaderDiv: HTMLElementWithComponent | null = null;
let pendingFooterDiv: HTMLElementWithComponent | null = null;
let pendingHeaderAbovePropertiesDiv: HTMLElementWithComponent | null = null;
let pendingFooterAboveBacklinksDiv: HTMLElementWithComponent | null = null;
// Render and inject content based on view mode, handling each positioning group separately
if (shouldRenderInReading || shouldRenderInLivePreview || shouldRenderInSource) {
// Handle normal header content
if (headerContentGroups.normal.length > 0) {
const combinedContent = headerContentGroups.normal.join(contentSeparator);
const result = await this.renderAndInjectGroupedContent(view, combinedContent, RenderLocation.Header, false);
if (result && shouldRenderInReading) {
pendingHeaderDiv = result;
}