-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.ts
More file actions
4175 lines (3782 loc) · 156 KB
/
Copy pathmain.ts
File metadata and controls
4175 lines (3782 loc) · 156 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,
Modal,
ButtonComponent,
MarkdownView,
MarkdownRenderer,
AbstractInputSuggest,
Component,
TFile,
getAllTags,
ItemView,
WorkspaceLeaf,
} 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',
SectionHeader = 'section-header',
}
type SectionHeaderPlacement = 'top' | 'bottom';
// --- 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;
/** For 'section-header' location: the heading text to target. */
sectionHeaderText?: string;
/** For 'section-header' location: the heading level to target, e.g. h2. */
sectionHeaderLevel?: string;
/** For 'section-header' location: whether to render at the top or bottom of the section. */
sectionHeaderPlacement?: SectionHeaderPlacement;
/** Whether to show this rule's content in popover views. */
showInPopover?: boolean;
/** Whether to show this rule's content in embedded notes. */
showInEmbed?: boolean;
/** Whether to show this rule's content in canvas card previews. */
showInCanvas?: 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;
/** Whether to enable virtual content inside embedded notes. */
enableEmbedRendering?: boolean;
/** Whether to enable canvas rendering support (can be expensive). */
enableCanvasRendering?: boolean;
/** Whether to log embed/canvas resolution details for debugging. */
debugEmbedCanvas?: 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;
/** The MutationObserver for monitoring style changes. */
observer?: MutationObserver;
}
// --- 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,
sectionHeaderText: '',
sectionHeaderLevel: 'h2',
sectionHeaderPlacement: 'top',
showInPopover: true,
showInEmbed: true,
showInCanvas: true,
}],
refreshOnFileOpen: false, // Default to false
renderInSourceMode: false, // Default to false
refreshOnMetadataChange: false, // Default to false
smartPropertyLinks: false, // Default to false
enableEmbedRendering: false, // Default to false
enableCanvasRendering: false, // Default to false
debugEmbedCanvas: 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_SECTION_HEADER_GROUP_ELEMENT = 'virtual-footer-section-header-group';
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
const CSS_VIRTUAL_FOOTER_BOTTOM_PADDING_VAR = '--virtual-footer-bottom-padding';
const VIRTUAL_FOOTER_BOTTOM_PADDING_MIN = 200;
const VIRTUAL_FOOTER_BOTTOM_PADDING_MAX = 700;
const VIRTUAL_FOOTER_BOTTOM_PADDING_RATIO = 0.6;
// 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 | null = null;
component: Component = new 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 = DEFAULT_SETTINGS;
/** 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;
private canvasObserver: MutationObserver | null = null;
private sectionHeaderScrollRefreshTimeout: number | null = null;
private embedObservers: WeakMap<MarkdownView, MutationObserver> = new WeakMap();
private embedRefreshTimeouts: WeakMap<MarkdownView, number> = new WeakMap();
private embedLastScanByView: WeakMap<MarkdownView, { filePath: string; time: number }> = new WeakMap();
private footerPaddingObservers: WeakMap<MarkdownView, ResizeObserver> = new WeakMap();
private livePreviewFooterStyleApplied: WeakMap<MarkdownView, boolean> = new WeakMap();
private canvasRefreshTimeout: number | null = null;
private canvasRefreshInProgress = false;
private canvasInteractionHandler: ((event: Event) => void) | null = null;
private getActiveFileForVirtualContent(): TFile | null {
const activeLeaf = this.app.workspace.activeLeaf;
const activeView = activeLeaf?.view as { file?: unknown } | undefined;
if (activeView?.file instanceof TFile) {
return activeView.file;
}
const workspaceFile = this.app.workspace.getActiveFile();
return workspaceFile instanceof TFile ? workspaceFile : null;
}
private async processSidebarContentForFilePath(filePath: string): Promise<void> {
const applicableRulesWithContent = await this._getApplicableRulesAndContent(filePath);
const contentSeparator = "\n\n";
let combinedSidebarText = "";
this.lastSeparateTabContents.clear();
for (const { rule, contentText, index } of applicableRulesWithContent) {
if (!contentText || contentText.trim() === "" || rule.renderLocation !== RenderLocation.Sidebar) {
continue;
}
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: filePath
});
} else {
combinedSidebarText += (combinedSidebarText ? contentSeparator : "") + contentText;
}
}
this.lastSidebarContent = { content: combinedSidebarText, sourcePath: filePath };
this.updateAllSidebarViews();
}
private async processNonMarkdownActiveFile(): Promise<void> {
const activeFile = this.getActiveFileForVirtualContent();
if (!activeFile) {
if (!this.settings.refreshOnFileOpen || this.app.workspace.getLeavesOfType('markdown').length === 0) {
this.lastSidebarContent = null;
this.lastSeparateTabContents.clear();
this.updateAllSidebarViews();
}
return;
}
await this.processSidebarContentForFilePath(activeFile.path);
}
private logEmbedCanvasDebug(message: string, data?: Record<string, unknown>): void {
if (!this.settings.debugEmbedCanvas) {
return;
}
if (data) {
console.log(`VirtualContent: ${message}`, data);
} else {
console.log(`VirtualContent: ${message}`);
}
}
/**
* 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);
}
});
const handleSectionCollapseClick = (event: MouseEvent) => {
const target = event.target as HTMLElement;
const collapseIndicator = target.closest('.heading-collapse-indicator, .cm-fold-indicator, .collapse-indicator');
const sectionHeaderTarget = collapseIndicator ? this.getConfiguredSectionHeaderCollapseTarget(collapseIndicator) : null;
if (
collapseIndicator?.closest('.markdown-preview-view') &&
sectionHeaderTarget
) {
setTimeout(() => {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
this.refreshSectionHeaderContent(activeView, true, sectionHeaderTarget);
}
}, 150);
}
};
document.addEventListener('click', handleSectionCollapseClick, true);
this.register(() => document.removeEventListener('click', handleSectionCollapseClick, true));
this.registerDomEvent(document, 'scroll', (event: Event) => {
const target = event.target as HTMLElement;
if (!target.closest?.('.markdown-preview-view')) {
return;
}
if (this.sectionHeaderScrollRefreshTimeout !== null) {
window.clearTimeout(this.sectionHeaderScrollRefreshTimeout);
}
this.sectionHeaderScrollRefreshTimeout = window.setTimeout(() => {
this.sectionHeaderScrollRefreshTimeout = null;
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
this.refreshSectionHeaderContent(activeView, false);
}
}, 250);
}, true);
// 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
});
}
if (this.settings.enableCanvasRendering) {
// Observe the document for canvas node updates
this.canvasObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
const addedOrRemovedNodes = [...mutation.addedNodes, ...mutation.removedNodes];
const hasCanvasNodeChange = addedOrRemovedNodes.some((node) => {
return node instanceof HTMLElement && (node.classList.contains('canvas-node') || node.querySelector('.canvas-node'));
});
if (hasCanvasNodeChange) {
this.queueCanvasEmbedRefresh();
}
}
if (mutation.type === 'attributes' && mutation.target instanceof HTMLElement) {
const target = mutation.target;
if (target.classList.contains('canvas-node')) {
this.queueCanvasEmbedRefresh();
}
}
}
});
if (this.canvasObserver) {
this.canvasObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['class', 'data-path', 'data-href', 'data-src', 'src']
});
}
this.canvasInteractionHandler = (event: Event) => {
const target = event.target as HTMLElement | null;
if (target?.closest?.('.canvas')) {
this.queueCanvasEmbedRefresh();
}
};
this.registerDomEvent(document, 'wheel', this.canvasInteractionHandler, true);
this.registerDomEvent(document, 'pointerup', this.canvasInteractionHandler, 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.canvasObserver?.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();
this.embedObservers = new WeakMap();
this.embedRefreshTimeouts = new WeakMap();
if (this.canvasRefreshTimeout !== null) {
window.clearTimeout(this.canvasRefreshTimeout);
}
this.canvasRefreshTimeout = null;
this.canvasRefreshInProgress = false;
this.canvasInteractionHandler = null;
}
/**
* Handles changes to the active Markdown view, triggering content processing.
*/
private handleActiveViewChange = () => {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView?.file) {
void this._processView(activeView);
return;
}
void this.processNonMarkdownActiveFile();
}
/**
* 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);
}
});
}
private queueEmbedRefresh(view: MarkdownView): void {
if (!this.settings.enableEmbedRendering) {
return;
}
const existingTimeout = this.embedRefreshTimeouts.get(view);
if (existingTimeout) {
window.clearTimeout(existingTimeout);
}
const currentPath = view.file?.path;
if (currentPath) {
const lastScan = this.embedLastScanByView.get(view);
if (lastScan && lastScan.filePath === currentPath && Date.now() - lastScan.time < 750) {
return;
}
}
const timeout = window.setTimeout(() => {
this.embedRefreshTimeouts.delete(view);
void this.processEmbedsInView(view);
}, 250);
this.embedRefreshTimeouts.set(view, timeout);
}
private queueCanvasEmbedRefresh(): void {
if (!this.settings.enableCanvasRendering) {
return;
}
if (!this.isCanvasActive()) {
return;
}
if (this.canvasRefreshTimeout !== null) {
return;
}
this.canvasRefreshTimeout = window.setTimeout(() => {
this.canvasRefreshTimeout = null;
if (this.canvasRefreshInProgress) {
return;
}
this.canvasRefreshInProgress = true;
void this.processCanvasEmbeds().then(() => {
this.canvasRefreshInProgress = false;
}, () => {
this.canvasRefreshInProgress = false;
});
}, 250);
}
private ensureEmbedObserver(view: MarkdownView): void {
if (!this.settings.enableEmbedRendering) {
return;
}
if (this.embedObservers.has(view)) {
return;
}
const observer = new MutationObserver((_mutations) => {
this.queueEmbedRefresh(view);
});
observer.observe(view.containerEl, { childList: true, subtree: true });
this.embedObservers.set(view, observer);
}
private isEmbedInCanvas(embed: HTMLElement): boolean {
return !!embed.closest('.canvas, .canvas-node, .canvas-node-container, .canvas-node-content');
}
private extractEmbedFilePath(embed: HTMLElement): string | null {
const canvasNode = embed.closest('.canvas-node');
if (canvasNode) {
const canvasPath = this.extractCanvasNodePath(canvasNode as HTMLElement);
if (canvasPath) {
this.logEmbedCanvasDebug('Canvas node path resolved', {
canvasPath
});
return canvasPath;
}
}
const embedContainer = embed.closest('.markdown-embed') as HTMLElement | null;
const scopedContainer = embedContainer || embed;
const embedLink = scopedContainer.querySelector('.markdown-embed-link a.internal-link[data-href]') as HTMLAnchorElement | null;
const embedLinkHref = embedLink?.dataset?.href;
const rawCandidates = [
scopedContainer.getAttribute('data-path'),
scopedContainer.getAttribute('data-src'),
scopedContainer.getAttribute('src'),
scopedContainer.getAttribute('data-href'),
scopedContainer.dataset?.path,
scopedContainer.dataset?.src,
scopedContainer.dataset?.href,
embedLinkHref,
];
const resolved = this.resolveFirstPathCandidate(rawCandidates);
if (!resolved) {
this.logEmbedCanvasDebug('Embed candidates not resolved', {
embedClass: scopedContainer.className,
candidates: rawCandidates.filter(Boolean)
});
}
return resolved;
}
private extractCanvasNodePath(canvasNode: HTMLElement): string | null {
const rawCandidates = [
canvasNode.getAttribute('data-path'),
canvasNode.getAttribute('data-href'),
canvasNode.getAttribute('data-src'),
canvasNode.getAttribute('data-file'),
canvasNode.getAttribute('data-file-path'),
canvasNode.getAttribute('data-filepath'),
canvasNode.dataset?.path,
canvasNode.dataset?.href,
canvasNode.dataset?.src,
canvasNode.dataset?.file,
canvasNode.dataset?.filePath,
canvasNode.dataset?.filepath,
];
const linkCandidate = canvasNode.querySelector('.canvas-node-title a.internal-link[data-href]') as HTMLAnchorElement | null;
if (linkCandidate?.dataset?.href) {
rawCandidates.push(linkCandidate.dataset.href);
}
const titleEl = canvasNode.querySelector('.canvas-node-title, .canvas-node-header, .canvas-node-label') as HTMLElement | null;
const titleText = titleEl?.textContent?.trim();
if (titleText) {
rawCandidates.push(titleText);
}
const resolved = this.resolveFirstPathCandidate(rawCandidates);
if (!resolved) {
const attrDump: Record<string, string> = {};
Array.from(canvasNode.attributes).forEach(attr => {
attrDump[attr.name] = attr.value;
});
this.logEmbedCanvasDebug('Canvas node path not resolved', {
canvasNodeClass: canvasNode.className,
attributes: attrDump,
candidates: rawCandidates.filter(Boolean)
});
}
return resolved;
}
private extractPathFromElement(element: HTMLElement): string | null {
const rawCandidates = [
element.getAttribute('data-path'),
element.getAttribute('data-href'),
element.getAttribute('data-src'),
element.getAttribute('src'),
element.dataset?.path,
element.dataset?.href,
element.dataset?.src,
];
return this.resolveFirstPathCandidate(rawCandidates);
}
private resolveFirstPathCandidate(rawCandidates: Array<string | null | undefined>): string | null {
for (const raw of rawCandidates) {
if (!raw) continue;
const cleaned = raw.split('#')[0].split('^')[0].trim();
if (!cleaned) continue;
const resolved = this.app.metadataCache.getFirstLinkpathDest(cleaned, '');
if (resolved) {
return resolved.path;
}
const abstractFile = this.app.vault.getAbstractFileByPath(cleaned);
if (abstractFile instanceof TFile) {
return abstractFile.path;
}
}
return null;
}
private findMetadataContainer(container: HTMLElement): HTMLElement | null {
return container.querySelector<HTMLElement>(`${SELECTOR_METADATA_CONTAINER}, .cm-obsidian-frontmatter`);
}
private async processEmbedContainer(
container: HTMLElement,
filePath: string,
allowRule: (rule: Rule) => boolean,
context: 'embed' | 'canvas'
): Promise<void> {
container.dataset.sourcePath = filePath;
const applicableRulesWithContent = await this._getApplicableRulesAndContent(filePath);
const filteredRules = applicableRulesWithContent.filter(({ rule }) => allowRule(rule));
await this.removeInjectedContentDOM(container);
if (filteredRules.length === 0) {
return;
}
const headerContentGroups: { normal: string[], aboveProperties: string[] } = { normal: [], aboveProperties: [] };
const footerContentGroups: { normal: string[] } = { normal: [] };
const sectionHeaderRules: Array<{ rule: Rule; contentText: string; index: number }> = [];
const contentSeparator = "\n\n";
for (const { rule, contentText, index } of filteredRules) {
if (!contentText || contentText.trim() === "") continue;
if (rule.renderLocation === RenderLocation.Header) {
if (rule.renderAboveProperties) {