-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
872 lines (750 loc) · 32.1 KB
/
main.ts
File metadata and controls
872 lines (750 loc) · 32.1 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
import { App, Plugin, PluginSettingTab, Setting, SettingGroup, MarkdownView, Platform, setIcon, setTooltip } from 'obsidian';
type ModifierKeyType = 'meta' | 'ctrl' | 'alt' | 'shift';
interface ModifierKeyConfig {
meta: boolean;
ctrl: boolean;
alt: boolean;
shift: boolean;
}
interface LinkPreviewSettings {
maxPreviewHeight: number;
maxPreviewWidth: number;
hoverDelay: number;
requireModifierKey: boolean;
modifierKeys: ModifierKeyConfig;
closeOnModifierRelease: boolean;
mouseStillnessDelay: number;
stickyPopup: boolean;
showOpenInBrowser: boolean;
showCloseButton: boolean;
}
// Legacy settings interface for migration
interface LegacyLinkPreviewSettings {
modifierKey?: ModifierKeyType;
}
const DEFAULT_MODIFIER_KEYS: ModifierKeyConfig = {
meta: false,
ctrl: false,
alt: false,
shift: false,
};
const DEFAULT_SETTINGS: Readonly<Omit<LinkPreviewSettings, 'modifierKeys'>> = {
maxPreviewHeight: 960,
maxPreviewWidth: 720,
hoverDelay: 500,
requireModifierKey: true,
closeOnModifierRelease: true,
mouseStillnessDelay: 0,
stickyPopup: false,
showOpenInBrowser: true,
showCloseButton: true,
// modifierKeys default is set dynamically in loadSettings() based on platform
};
export default class LinkPreviewPlugin extends Plugin {
settings: LinkPreviewSettings;
private activePreview?: {
element: HTMLElement,
cleanup: () => void,
link: HTMLElement
};
private hoverTimeout?: number;
private lastMouseX = 0;
private lastMouseY = 0;
private modifierState: ModifierKeyConfig = { meta: false, ctrl: false, alt: false, shift: false };
private lastMovementTime = 0;
private stillnessCheckTimeout?: number;
async onload() {
await this.loadSettings();
// Defer setup until layout is ready
this.app.workspace.onLayoutReady(() => {
this.registerGlobalHandler();
});
this.addSettingTab(new LinkPreviewSettingTab(this.app, this));
}
private registerGlobalHandler() {
const handleWindow = (doc: Document) => {
this.registerDomEvent(doc, 'mouseover', (e: MouseEvent) => this.handleLinkHover(e));
this.registerDomEvent(doc, 'mousemove', (e: MouseEvent) => {
// Track mouse stillness - only update time if mouse moved significantly (>2px)
const dx = Math.abs(e.clientX - this.lastMouseX);
const dy = Math.abs(e.clientY - this.lastMouseY);
if (dx > 2 || dy > 2) {
this.lastMovementTime = Date.now();
}
this.lastMouseX = e.clientX;
this.lastMouseY = e.clientY;
});
this.registerDomEvent(doc, 'keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape' && this.activePreview) {
this.cleanupActivePreview();
}
// Update modifier state
this.updateModifierState(e);
// Handle modifier key press while hovering over link
if (this.settings.requireModifierKey && this.isModifierKeyEvent(e)) {
this.handleModifierKeyDown();
}
});
this.registerDomEvent(doc, 'keyup', (e: KeyboardEvent) => {
// Update modifier state
this.updateModifierState(e);
// Close preview when any required modifier key is released
if (this.settings.requireModifierKey && this.isModifierKeyEvent(e)) {
this.handleModifierKeyUp();
}
});
// Reset modifier state on window blur
this.registerDomEvent(doc.defaultView ?? window, 'blur', () => {
this.modifierState = { meta: false, ctrl: false, alt: false, shift: false };
});
};
handleWindow(document);
this.registerEvent(
this.app.workspace.on('window-open', ({win}) => handleWindow(win.document))
);
}
private updateModifierState(e: KeyboardEvent) {
this.modifierState.meta = e.metaKey;
this.modifierState.ctrl = e.ctrlKey;
this.modifierState.alt = e.altKey;
this.modifierState.shift = e.shiftKey;
}
private handleLinkHover(event: MouseEvent) {
const target = event.target as Element | null;
if (!(target instanceof Element)) return;
// Skip if event is from inside the active preview (prevents flickering)
if (this.activePreview?.element.contains(target)) {
return;
}
// Check for modifier key requirement
if (this.settings.requireModifierKey && !this.isModifierKeyPressed(event)) {
return;
}
const linkInfo = this.findLinkElement(target, event.relatedTarget as Element | null);
if (!linkInfo) return;
const { element: linkElement, url } = linkInfo;
// Clear any existing hover timeout
if (this.hoverTimeout) {
window.clearTimeout(this.hoverTimeout);
}
// Clear any existing stillness check
if (this.stillnessCheckTimeout) {
window.clearTimeout(this.stillnessCheckTimeout);
this.stillnessCheckTimeout = undefined;
}
// If hovering the same link that has an active preview, clear any pending cleanup
if (this.activePreview?.link === linkElement) {
if (this.cleanupTimeout) {
window.clearTimeout(this.cleanupTimeout);
this.cleanupTimeout = undefined;
}
return;
}
// Clean up any existing preview
this.cleanupActivePreview();
// Set timeout for showing preview
this.hoverTimeout = window.setTimeout(() => {
this.tryShowPreview(linkElement, url);
}, this.settings.hoverDelay);
// Add mouse leave listener to target
const handleMouseLeave = (e: MouseEvent) => {
// Skip cleanup timer if sticky popup is enabled
if (this.settings.stickyPopup) {
linkElement.removeEventListener('mouseleave', handleMouseLeave);
return;
}
// Check if mouse moved to the preview
const toElement = e.relatedTarget as HTMLElement | null;
if (toElement && this.activePreview?.element.contains(toElement)) return;
this.startCleanupTimer();
linkElement.removeEventListener('mouseleave', handleMouseLeave);
};
linkElement.addEventListener('mouseleave', handleMouseLeave);
}
private tryShowPreview(linkElement: HTMLElement, url: string) {
// Check mouse stillness if delay is configured
if (this.settings.mouseStillnessDelay > 0) {
const timeSinceMovement = Date.now() - this.lastMovementTime;
if (timeSinceMovement < this.settings.mouseStillnessDelay) {
// Mouse hasn't been still long enough, reschedule check
const remainingTime = this.settings.mouseStillnessDelay - timeSinceMovement;
this.stillnessCheckTimeout = window.setTimeout(() => {
this.tryShowPreview(linkElement, url);
}, Math.min(remainingTime, 50)); // Poll at most every 50ms
return;
}
}
this.showPreview(linkElement, url);
}
private showPreview(link: HTMLElement, url: string) {
const rect = link.getBoundingClientRect();
const previewEl = this.createPreviewElement(rect);
if (this.settings.showOpenInBrowser || this.settings.showCloseButton) {
this.createButtons(previewEl, url);
}
const wrapper = previewEl.createDiv('preview-iframe-wrapper');
// GitHub-specific: add class to enable header cropping
if (url.includes('github.com')) {
wrapper.addClass('github-preview');
}
const loading = previewEl.createDiv('preview-loading');
loading.addClass('loading-spinner');
const iframe = createEl('iframe', {
attr: {
src: url
}
});
wrapper.appendChild(iframe);
const cleanup = () => {
previewEl.remove();
this.activePreview = undefined;
};
iframe.onload = () => {
// Small delay to let page render before showing
setTimeout(() => {
iframe.addClass('is-loaded');
loading.remove(); // Remove entirely to stop infinite animation
}, 50);
};
iframe.onerror = () => {
loading.textContent = 'Failed to load preview';
};
// Add preview hover handlers
previewEl.addEventListener('mouseenter', () => {
if (this.cleanupTimeout) {
window.clearTimeout(this.cleanupTimeout);
this.cleanupTimeout = undefined;
}
});
previewEl.addEventListener('mouseleave', () => {
if (!this.settings.stickyPopup) {
this.startCleanupTimer();
}
});
// Add click-outside handler for sticky popup mode
let clickOutsideHandler: ((e: MouseEvent) => void) | undefined;
if (this.settings.stickyPopup) {
clickOutsideHandler = (e: MouseEvent) => {
const target = e.target as Element;
if (!previewEl.contains(target) && !link.contains(target)) {
this.cleanupActivePreview();
}
};
// Delay adding listener to avoid immediate trigger from the click that might have opened it
setTimeout(() => {
document.addEventListener('click', clickOutsideHandler!);
}, 0);
}
// Update cleanup to remove click handler
const originalCleanup = cleanup;
const cleanupWithClickHandler = () => {
if (clickOutsideHandler) {
document.removeEventListener('click', clickOutsideHandler);
}
originalCleanup();
};
document.body.appendChild(previewEl);
this.activePreview = { element: previewEl, cleanup: cleanupWithClickHandler, link };
}
private cleanupTimeout?: number;
private startCleanupTimer() {
if (this.cleanupTimeout) {
window.clearTimeout(this.cleanupTimeout);
}
this.cleanupTimeout = window.setTimeout(() => {
// Before cleanup, verify mouse isn't over preview OR the original link
if (this.activePreview && this.isMouseOverPreviewOrLink()) {
this.cleanupTimeout = undefined;
return;
}
this.cleanupActivePreview();
this.cleanupTimeout = undefined;
}, 300);
}
private isMouseOverPreviewOrLink(): boolean {
if (!this.activePreview) return false;
// Check preview bounds
const previewRect = this.activePreview.element.getBoundingClientRect();
if (this.lastMouseX >= previewRect.left &&
this.lastMouseX <= previewRect.right &&
this.lastMouseY >= previewRect.top &&
this.lastMouseY <= previewRect.bottom) {
return true;
}
// Check original link bounds
const linkRect = this.activePreview.link.getBoundingClientRect();
if (this.lastMouseX >= linkRect.left &&
this.lastMouseX <= linkRect.right &&
this.lastMouseY >= linkRect.top &&
this.lastMouseY <= linkRect.bottom) {
return true;
}
return false;
}
private cleanupActivePreview() {
if (this.activePreview) {
this.activePreview.cleanup();
this.activePreview = undefined;
}
if (this.hoverTimeout) {
window.clearTimeout(this.hoverTimeout);
this.hoverTimeout = undefined;
}
if (this.cleanupTimeout) {
window.clearTimeout(this.cleanupTimeout);
this.cleanupTimeout = undefined;
}
if (this.stillnessCheckTimeout) {
window.clearTimeout(this.stillnessCheckTimeout);
this.stillnessCheckTimeout = undefined;
}
}
private isModifierKeyPressed(event: MouseEvent): boolean {
const keys = this.settings.modifierKeys;
// Check if ALL required modifiers are pressed
if (keys.meta && !event.metaKey) return false;
if (keys.ctrl && !event.ctrlKey) return false;
if (keys.alt && !event.altKey) return false;
if (keys.shift && !event.shiftKey) return false;
// At least one modifier must be required
return keys.meta || keys.ctrl || keys.alt || keys.shift;
}
private isModifierKeyEvent(event: KeyboardEvent): boolean {
const keys = this.settings.modifierKeys;
// Return true if any required modifier key is pressed or released
if (keys.meta && event.key === 'Meta') return true;
if (keys.ctrl && event.key === 'Control') return true;
if (keys.alt && event.key === 'Alt') return true;
if (keys.shift && event.key === 'Shift') return true;
return false;
}
private areAllModifiersPressed(): boolean {
const keys = this.settings.modifierKeys;
// Check if ALL required modifiers are currently pressed (using tracked state)
if (keys.meta && !this.modifierState.meta) return false;
if (keys.ctrl && !this.modifierState.ctrl) return false;
if (keys.alt && !this.modifierState.alt) return false;
if (keys.shift && !this.modifierState.shift) return false;
// At least one modifier must be required
return keys.meta || keys.ctrl || keys.alt || keys.shift;
}
private handleModifierKeyDown() {
// If already showing a preview, do nothing
if (this.activePreview) return;
// Check if ALL required modifiers are now pressed
if (!this.areAllModifiersPressed()) return;
// Find element under cursor
const elementUnderCursor = document.elementFromPoint(this.lastMouseX, this.lastMouseY);
if (!elementUnderCursor) return;
const linkInfo = this.findLinkElement(elementUnderCursor, null);
if (linkInfo) {
// Clear any existing timeout and show preview after delay
if (this.hoverTimeout) {
window.clearTimeout(this.hoverTimeout);
}
this.hoverTimeout = window.setTimeout(() => {
this.tryShowPreview(linkInfo.element, linkInfo.url);
}, this.settings.hoverDelay);
}
}
private handleModifierKeyUp() {
// Close preview when any required modifier key is released (unless sticky popup is enabled)
if (this.settings.closeOnModifierRelease && !this.settings.stickyPopup && !this.areAllModifiersPressed()) {
this.cleanupActivePreview();
}
}
async loadSettings() {
const loaded = (await this.loadData()) as (Partial<LinkPreviewSettings> & LegacyLinkPreviewSettings) | null;
// Create platform-aware default modifier keys
const platformDefaultKeys: ModifierKeyConfig = {
...DEFAULT_MODIFIER_KEYS,
[Platform.isMacOS ? 'meta' : 'ctrl']: true,
};
let modifierKeys: ModifierKeyConfig;
if (loaded?.modifierKeys) {
// New format exists, use it
modifierKeys = loaded.modifierKeys;
} else if (loaded?.modifierKey) {
// Migrate from old single key format
modifierKeys = { ...DEFAULT_MODIFIER_KEYS, [loaded.modifierKey]: true };
} else {
// Fresh install, use platform default
modifierKeys = platformDefaultKeys;
}
this.settings = {
...DEFAULT_SETTINGS,
...loaded,
modifierKeys,
};
// Clean up legacy field if present
if ('modifierKey' in this.settings) {
delete (this.settings as LinkPreviewSettings & LegacyLinkPreviewSettings).modifierKey;
await this.saveSettings();
}
}
async saveSettings() {
await this.saveData(this.settings);
}
onunload() {
this.cleanupActivePreview();
}
private createPreviewElement(rect: DOMRect): HTMLElement {
const el = createEl('div', { cls: 'hover-popup' });
const windowSize = {
width: window.innerWidth,
height: window.innerHeight
};
const bounds = this.calculatePreviewBounds(rect, windowSize);
el.setCssStyles({
left: `${bounds.left}px`,
top: `${bounds.top}px`,
width: `${bounds.width}px`,
height: `${bounds.height}px`,
});
return el;
}
private createButtons(container: HTMLElement, url: string) {
const buttons = container.createDiv('preview-buttons');
if (this.settings.showOpenInBrowser) {
const openBtn = buttons.createEl('button', { cls: 'clickable-icon' });
setIcon(openBtn, 'external-link');
setTooltip(openBtn, 'Open in external browser');
openBtn.addEventListener('click', (e) => {
e.stopPropagation();
window.open(url);
});
}
if (this.settings.showCloseButton) {
const closeBtn = buttons.createEl('button', { cls: 'clickable-icon' });
setIcon(closeBtn, 'x');
setTooltip(closeBtn, 'Close preview');
closeBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.cleanupActivePreview();
});
}
}
private calculatePreviewBounds(rect: DOMRect, windowSize: { width: number, height: number }): {
left: number,
top: number,
width: number,
height: number,
showAbove: boolean
} {
const margin = 5; // Margin from edges
const maxWidth = Math.min(this.settings.maxPreviewWidth, windowSize.width - margin * 2);
const maxHeight = Math.min(this.settings.maxPreviewHeight, windowSize.height - margin * 2);
// Determine if we should show above or below
const spaceBelow = windowSize.height - rect.bottom - margin;
const spaceAbove = rect.top - margin;
const showAbove = spaceBelow < maxHeight && spaceAbove > spaceBelow;
// Calculate vertical position
let top = showAbove ?
Math.max(margin, rect.top - maxHeight - margin) :
Math.min(rect.bottom + margin, windowSize.height - maxHeight - margin);
// Calculate horizontal position
let left = rect.left;
if (left + maxWidth > windowSize.width - margin) {
left = windowSize.width - maxWidth - margin;
}
left = Math.max(margin, left);
return {
left,
top,
width: maxWidth,
height: maxHeight,
showAbove
};
}
private findLinkElement(target: Element, relatedTarget: Element | null): { element: HTMLElement, url: string } | null {
const LINK_SELECTOR = 'a.external-link, a[href^="http"], span.external-link, .cm-hmd-external-link, .cm-link .cm-underline, .cm-url, [data-href], [data-url]';
let el: Element | null = target;
while (el && el !== document.body) {
if (!(el instanceof HTMLElement)) {
el = el.parentElement;
continue;
}
if (!el.matches(LINK_SELECTOR)) {
el = el.parentElement;
continue;
}
if (relatedTarget && el.contains(relatedTarget)) {
return null;
}
let url: string | null = null;
// In editor mode, use document search FIRST (DOM doesn't have URLs)
if (el.closest('.cm-editor')) {
url = this.getUrlFromEditorByText(el);
}
// Fallback to DOM extraction (works in Reader mode)
if (!url) {
url = this.extractUrlFromElement(el);
}
if (url) {
return { element: el, url };
}
el = el.parentElement;
}
return null;
}
private getUrlFromEditorByText(element: HTMLElement): string | null {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view?.editor) return null;
const displayText = element.textContent?.trim();
if (!displayText) return null;
const content = view.editor.getValue();
const linkRegex = /\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g;
let match;
let substringMatch: string | null = null;
while ((match = linkRegex.exec(content)) !== null) {
const linkText = match[1];
const url = match[2];
// Exact match — return immediately
if (linkText === displayText) {
return url;
}
// Substring match — remember first one, but keep looking for exact
if (!substringMatch &&
(linkText.includes(displayText) || displayText.includes(linkText))) {
substringMatch = url;
}
}
// No exact match found — use substring match if any
if (substringMatch) {
return substringMatch;
}
// Bare URL fallback
if (displayText.startsWith('http')) {
return this.normalizeUrl(displayText);
}
return null;
}
private extractUrlFromElement(element: HTMLElement): string | null {
// For anchor elements, use href directly
if (element instanceof HTMLAnchorElement) {
return element.href;
}
// Check element's own attributes
const attributes = ['data-href', 'data-url', 'href', 'aria-label', 'title'];
for (const attr of attributes) {
const value = element.getAttribute(attr);
const url = value ? this.normalizeUrl(value) : null;
if (url) return url;
}
// For CodeMirror elements, look for ancestor anchor or external-link
let ancestor: HTMLElement | null = element;
while (ancestor && ancestor !== document.body) {
if (ancestor instanceof HTMLAnchorElement && ancestor.href) {
return this.normalizeUrl(ancestor.href);
}
// Check for Obsidian's external-link class which wraps the anchor
if (ancestor.classList.contains('external-link') || ancestor.classList.contains('cm-link')) {
const anchor = ancestor.querySelector('a[href]');
if (anchor instanceof HTMLAnchorElement && anchor.href) {
return this.normalizeUrl(anchor.href);
}
}
ancestor = ancestor.parentElement;
}
// Fallback to text content (for bare URLs in editor)
const text = element.textContent?.trim();
return text ? this.normalizeUrl(text) : null;
}
private normalizeUrl(candidate: string): string | null {
const trimmed = candidate.trim();
if (!/^https?:\/\//i.test(trimmed)) {
return null;
}
try {
const url = new URL(trimmed);
return url.href;
} catch {
return null;
}
}
}
class LinkPreviewSettingTab extends PluginSettingTab {
plugin: LinkPreviewPlugin;
constructor(app: App, plugin: LinkPreviewPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
const isModifierKeyEnabled = this.plugin.settings.requireModifierKey;
new Setting(containerEl)
.setName('Require modifier key')
.setDesc('Only show preview when holding a modifier key while hovering')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.requireModifierKey)
.onChange(async (value) => {
this.plugin.settings.requireModifierKey = value;
await this.plugin.saveSettings();
// Refresh display to update disabled/opacity states
this.display();
}));
// Modifier key toggles
const modifierKeyNames: { key: keyof ModifierKeyConfig; label: string }[] = [
{ key: 'meta', label: Platform.isMacOS ? 'Command (⌘)' : 'Meta/Win' },
{ key: 'ctrl', label: Platform.isMacOS ? 'Control (⌃)' : 'Ctrl' },
{ key: 'alt', label: Platform.isMacOS ? 'Option (⌥)' : 'Alt' },
{ key: 'shift', label: 'Shift' },
];
const modifierGroup = new SettingGroup(containerEl)
.setHeading('Modifier keys')
.addClass('settings-group-no-margin');
if (!isModifierKeyEnabled) {
modifierGroup.addClass('setting-disabled');
}
for (const { key, label } of modifierKeyNames) {
modifierGroup.addSetting(setting => {
setting
.setName(label)
.setDesc(this.getModifierKeyDescription(key))
.addToggle(toggle => {
toggle
.setValue(this.plugin.settings.modifierKeys[key])
.onChange(async (value) => {
this.plugin.settings.modifierKeys[key] = value;
// Ensure at least one modifier is selected when requireModifierKey is enabled
if (this.plugin.settings.requireModifierKey && !this.hasAnyModifierSelected()) {
// Reset to platform default
const defaultKey = Platform.isMacOS ? 'meta' : 'ctrl';
this.plugin.settings.modifierKeys[defaultKey] = true;
}
await this.plugin.saveSettings();
this.display();
});
toggle.setDisabled(!isModifierKeyEnabled);
});
});
}
const behaviorGroup = new SettingGroup(containerEl)
.setHeading('Behavior')
.addClass('settings-group-no-margin');
behaviorGroup.addSetting(setting => {
setting
.setName('Close on key release')
.setDesc('Close preview when modifier key is released')
.addToggle(toggle => {
toggle
.setValue(this.plugin.settings.closeOnModifierRelease)
.onChange(async (value) => {
this.plugin.settings.closeOnModifierRelease = value;
await this.plugin.saveSettings();
});
toggle.setDisabled(!isModifierKeyEnabled);
});
if (!isModifierKeyEnabled) {
setting.settingEl.addClass('setting-disabled');
}
});
behaviorGroup.addSetting(setting => {
setting
.setName('Sticky popup')
.setDesc('Keep popup open until escape or click outside (instead of closing when mouse leaves)')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.stickyPopup)
.onChange(async (value) => {
this.plugin.settings.stickyPopup = value;
await this.plugin.saveSettings();
}));
});
behaviorGroup.addSetting(setting => {
setting
.setName('Show open in browser button')
.setDesc('Show a button to open the URL in the default browser')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.showOpenInBrowser)
.onChange(async (value) => {
this.plugin.settings.showOpenInBrowser = value;
await this.plugin.saveSettings();
}));
});
behaviorGroup.addSetting(setting => {
setting
.setName('Show close button')
.setDesc('Show a button to close the preview popup')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.showCloseButton)
.onChange(async (value) => {
this.plugin.settings.showCloseButton = value;
await this.plugin.saveSettings();
}));
});
new SettingGroup(containerEl)
.setHeading('Mouse settings')
.addClass('settings-group-no-margin')
.addSetting(setting => {
setting
.setName('Hover delay')
.setDesc('Delay before showing preview (in ms)')
.addText(text => text
.setPlaceholder('500')
.setValue(String(this.plugin.settings.hoverDelay))
.onChange(async (value) => {
const numValue = Number(value);
if (!isNaN(numValue) && numValue >= 0) {
this.plugin.settings.hoverDelay = numValue;
await this.plugin.saveSettings();
}
}));
})
.addSetting(setting => {
setting
.setName('Mouse stillness delay')
.setDesc('Time in ms the mouse must be stationary before showing preview (0 = disabled)')
.addText(text => text
.setPlaceholder('0')
.setValue(String(this.plugin.settings.mouseStillnessDelay))
.onChange(async (value) => {
const numValue = Number(value);
if (!isNaN(numValue) && numValue >= 0) {
this.plugin.settings.mouseStillnessDelay = numValue;
await this.plugin.saveSettings();
}
}));
});
new SettingGroup(containerEl)
.setHeading('Preview size')
.addClass('settings-group-no-margin')
.addSetting(setting => {
setting
.setName('Maximum height')
.setDesc('Maximum height of preview window (in px)')
.addText(text => text
.setPlaceholder('300')
.setValue(String(this.plugin.settings.maxPreviewHeight))
.onChange(async (value) => {
this.plugin.settings.maxPreviewHeight = Number(value);
await this.plugin.saveSettings();
}));
})
.addSetting(setting => {
setting
.setName('Maximum width')
.setDesc('Maximum width of preview window (in px)')
.addText(text => text
.setPlaceholder('400')
.setValue(String(this.plugin.settings.maxPreviewWidth))
.onChange(async (value) => {
this.plugin.settings.maxPreviewWidth = Number(value);
await this.plugin.saveSettings();
}));
});
}
private hasAnyModifierSelected(): boolean {
const keys = this.plugin.settings.modifierKeys;
return keys.meta || keys.ctrl || keys.alt || keys.shift;
}
private getModifierKeyDescription(key: keyof ModifierKeyConfig): string {
const descriptions: Record<keyof ModifierKeyConfig, string> = {
meta: Platform.isMacOS ? 'Require Command key' : 'Require Meta/Windows key',
ctrl: Platform.isMacOS ? 'Require Control key' : 'Require Ctrl key',
alt: Platform.isMacOS ? 'Require Option key' : 'Require Alt key',
shift: 'Require Shift key',
};
return descriptions[key];
}
}