-
Notifications
You must be signed in to change notification settings - Fork 853
Expand file tree
/
Copy pathClaudianView.ts
More file actions
775 lines (662 loc) · 28.4 KB
/
Copy pathClaudianView.ts
File metadata and controls
775 lines (662 loc) · 28.4 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
import type { EventRef, WorkspaceLeaf } from 'obsidian';
import { ItemView, Notice, Scope, setIcon } from 'obsidian';
import { getHiddenProviderCommandSet } from '../../core/providers/commands/hiddenCommands';
import { ProviderRegistry } from '../../core/providers/ProviderRegistry';
import { ProviderSettingsCoordinator } from '../../core/providers/ProviderSettingsCoordinator';
import { DEFAULT_CHAT_PROVIDER_ID, type ProviderId } from '../../core/providers/types';
import { VIEW_TYPE_CLAUDIAN } from '../../core/types';
import type ClaudianPlugin from '../../main';
import type { HistoryConversationOpenState } from './controllers/ConversationController';
import { getTabProviderId, onProviderAvailabilityChanged, updatePlanModeUI } from './tabs/Tab';
import { TabBar } from './tabs/TabBar';
import { TabManager } from './tabs/TabManager';
import type { TabData, TabId } from './tabs/types';
import { recalculateUsageForModel } from './utils/usageInfo';
export class ClaudianView extends ItemView {
private plugin: ClaudianPlugin;
// Tab management
private tabManager: TabManager | null = null;
private tabBar: TabBar | null = null;
private tabBarContainerEl: HTMLElement | null = null;
private tabContentEl: HTMLElement | null = null;
private navRowContent: HTMLElement | null = null;
// DOM Elements
private viewContainerEl: HTMLElement | null = null;
private headerEl: HTMLElement | null = null;
private titleSlotEl: HTMLElement | null = null;
private logoEl: HTMLElement | null = null;
private titleTextEl: HTMLElement | null = null;
private headerActionsEl: HTMLElement | null = null;
private headerActionsContent: HTMLElement | null = null;
// Header elements
private historyDropdown: HTMLElement | null = null;
// Event refs for cleanup
private eventRefs: EventRef[] = [];
// Debouncing for tab bar updates
private pendingTabBarUpdate: number | null = null;
// Debouncing for tab state persistence
private pendingPersist: ReturnType<typeof setTimeout> | null = null;
constructor(leaf: WorkspaceLeaf, plugin: ClaudianPlugin) {
super(leaf);
this.plugin = plugin;
// Hover Editor compatibility: Define load as an instance method that can't be
// overwritten by prototype patching. Hover Editor patches ClaudianView.prototype.load
// after our class is defined, but instance methods take precedence over prototype methods.
const originalLoad = Object.getPrototypeOf(this).load.bind(this);
Object.defineProperty(this, 'load', {
value: async () => {
// Ensure containerEl exists before any patched load code tries to use it
if (!this.containerEl) {
(this as any).containerEl = createDiv({ cls: 'view-content' });
}
// Wrap in try-catch to prevent Hover Editor errors from breaking our view
try {
return await originalLoad();
} catch {
// Hover Editor may throw if its DOM setup fails - continue anyway
}
},
writable: false,
configurable: false,
});
}
getViewType(): string {
return VIEW_TYPE_CLAUDIAN;
}
getDisplayText(): string {
return 'Claudian';
}
getIcon(): string {
return 'bot';
}
/** Refreshes model-dependent UI across all tabs (used after settings/env changes). */
refreshModelSelector(): void {
for (const tab of this.tabManager?.getAllTabs() ?? []) {
onProviderAvailabilityChanged(tab, this.plugin);
const providerId = getTabProviderId(tab, this.plugin);
const providerSettings = ProviderSettingsCoordinator.getProviderSettingsSnapshot(
this.plugin.settings as unknown as Record<string, unknown>,
providerId,
);
const model = providerSettings.model as string;
const uiConfig = ProviderRegistry.getChatUIConfig(providerId);
const capabilities = ProviderRegistry.getCapabilities(providerId);
const contextWindow = uiConfig.getContextWindowSize(
model,
providerSettings.customContextLimits as Record<string, number> | undefined,
);
if (tab.state.usage) {
tab.state.usage = recalculateUsageForModel(tab.state.usage, model, contextWindow);
}
tab.ui.modelSelector?.updateDisplay();
tab.ui.modelSelector?.renderOptions();
tab.ui.thinkingBudgetSelector?.updateDisplay();
tab.ui.permissionToggle?.updateDisplay();
tab.ui.serviceTierToggle?.updateDisplay();
tab.dom.inputWrapper.toggleClass(
'claudian-input-plan-mode',
this.plugin.settings.permissionMode === 'plan' && capabilities.supportsPlanMode,
);
}
}
/** Updates provider-scoped hidden commands on all tabs after settings changes. */
updateHiddenProviderCommands(): void {
for (const tab of this.tabManager?.getAllTabs() ?? []) {
tab.ui.slashCommandDropdown?.setHiddenCommands(
getHiddenProviderCommandSet(this.plugin.settings, getTabProviderId(tab, this.plugin)),
);
}
}
async onOpen() {
// Guard: Hover Editor and similar plugins may call onOpen before DOM is ready.
// containerEl must exist before we can access contentEl or create elements.
if (!this.containerEl) {
return;
}
// Use contentEl (standard Obsidian API) as primary target.
// Hover Editor and other plugins may modify the DOM structure,
// so we need fallbacks to handle non-standard scenarios.
let container: HTMLElement | null =
this.contentEl ?? (this.containerEl.children[1] as HTMLElement | null);
if (!container) {
// Last resort: create our own container inside containerEl
container = this.containerEl.createDiv();
}
this.viewContainerEl = container;
this.viewContainerEl.empty();
this.viewContainerEl.addClass('claudian-container');
const header = this.viewContainerEl.createDiv({ cls: 'claudian-header' });
this.buildHeader(header);
this.navRowContent = this.buildNavRowContent();
this.tabContentEl = this.viewContainerEl.createDiv({ cls: 'claudian-tab-content-container' });
this.tabManager = new TabManager(
this.plugin,
this.tabContentEl,
this,
{
onTabCreated: () => {
this.updateTabBar();
this.updateNavRowLocation();
this.persistTabState();
this.syncProviderBrandColor();
},
onTabSwitched: () => {
this.updateTabBar();
this.updateHistoryDropdown();
this.updateNavRowLocation();
this.persistTabState();
this.syncProviderBrandColor();
},
onTabClosed: () => {
this.updateTabBar();
this.persistTabState();
},
onTabStreamingChanged: () => this.updateTabBar(),
onTabTitleChanged: () => this.updateTabBar(),
onTabAttentionChanged: () => this.updateTabBar(),
onTabConversationChanged: () => {
this.persistTabState();
this.syncProviderBrandColor();
},
onTabProviderChanged: () => {
this.syncProviderBrandColor();
},
}
);
this.wireEventHandlers();
await this.restoreOrCreateTabs();
this.syncProviderBrandColor();
this.updateLayoutForPosition();
}
async onClose() {
if (this.pendingTabBarUpdate !== null) {
cancelAnimationFrame(this.pendingTabBarUpdate);
this.pendingTabBarUpdate = null;
}
for (const ref of this.eventRefs) {
this.plugin.app.vault.offref(ref);
}
this.eventRefs = [];
await this.persistTabStateImmediate();
await this.tabManager?.destroy();
this.tabManager = null;
this.tabBar?.destroy();
this.tabBar = null;
}
// ============================================
// UI Building
// ============================================
private buildHeader(header: HTMLElement) {
this.headerEl = header;
// Title slot container (logo + title or tabs)
this.titleSlotEl = header.createDiv({ cls: 'claudian-title-slot' });
// Logo (hidden when 2+ tabs) — populated by syncHeaderLogo()
this.logoEl = this.titleSlotEl.createSpan({ cls: 'claudian-logo' });
this.syncHeaderLogo(DEFAULT_CHAT_PROVIDER_ID);
// Title text (hidden in header mode when 2+ tabs)
this.titleTextEl = this.titleSlotEl.createEl('h4', { text: 'Claudian', cls: 'claudian-title-text' });
// Header actions container (for header mode - initially hidden)
this.headerActionsEl = header.createDiv({ cls: 'claudian-header-actions claudian-header-actions-slot' });
this.headerActionsEl.style.display = 'none';
}
/**
* Builds the nav row content (tab badges + header actions).
* This is called once and the content is moved between locations.
*/
private buildNavRowContent(): HTMLElement {
// Create a fragment to hold nav row content
const fragment = document.createDocumentFragment();
// Tab badges (left side in nav row, or in title slot for header mode)
this.tabBarContainerEl = document.createElement('div');
this.tabBarContainerEl.className = 'claudian-tab-bar-container';
this.tabBar = new TabBar(this.tabBarContainerEl, {
onTabClick: (tabId) => this.handleTabClick(tabId),
onTabClose: (tabId) => this.handleTabClose(tabId),
onNewTab: () => this.createNewTab(),
});
fragment.appendChild(this.tabBarContainerEl);
// Header actions (right side)
this.headerActionsContent = document.createElement('div');
this.headerActionsContent.className = 'claudian-header-actions';
// New tab button (plus icon)
const newTabBtn = this.headerActionsContent.createDiv({ cls: 'claudian-header-btn claudian-new-tab-btn' });
setIcon(newTabBtn, 'square-plus');
newTabBtn.setAttribute('aria-label', 'New tab');
newTabBtn.addEventListener('click', async () => {
await this.createNewTab();
});
// New conversation button (square-pen icon - new conversation in current tab)
const newBtn = this.headerActionsContent.createDiv({ cls: 'claudian-header-btn' });
setIcon(newBtn, 'square-pen');
newBtn.setAttribute('aria-label', 'New conversation');
newBtn.addEventListener('click', async () => {
await this.tabManager?.createNewConversation();
this.updateHistoryDropdown();
});
// History dropdown
const historyContainer = this.headerActionsContent.createDiv({ cls: 'claudian-history-container' });
const historyBtn = historyContainer.createDiv({ cls: 'claudian-header-btn' });
setIcon(historyBtn, 'history');
historyBtn.setAttribute('aria-label', 'Chat history');
this.historyDropdown = historyContainer.createDiv({ cls: 'claudian-history-menu' });
historyBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.toggleHistoryDropdown();
});
fragment.appendChild(this.headerActionsContent);
// Create a wrapper div to hold the fragment (for input mode nav row)
const wrapper = document.createElement('div');
wrapper.style.display = 'contents';
wrapper.appendChild(fragment);
return wrapper;
}
/**
* Moves nav row content based on tabBarPosition setting.
* - 'input' mode: Both tab badges and actions go to active tab's navRowEl
* - 'header' mode: Tab badges go to title slot (after logo), actions go to header right side
*/
private updateNavRowLocation(): void {
if (!this.tabBarContainerEl || !this.headerActionsContent) return;
const isHeaderMode = this.plugin.settings.tabBarPosition === 'header';
if (isHeaderMode) {
// Header mode: Tab badges go to title slot, actions go to header right side
if (this.titleSlotEl) {
this.titleSlotEl.appendChild(this.tabBarContainerEl);
}
if (this.headerActionsEl) {
this.headerActionsEl.appendChild(this.headerActionsContent);
this.headerActionsEl.style.display = 'flex';
}
} else {
// Input mode: Both go to active tab's navRowEl via the wrapper
const activeTab = this.tabManager?.getActiveTab();
if (activeTab && this.navRowContent) {
// Re-assemble the nav row content wrapper
this.navRowContent.appendChild(this.tabBarContainerEl);
this.navRowContent.appendChild(this.headerActionsContent);
activeTab.dom.navRowEl.appendChild(this.navRowContent);
}
// Hide header actions slot when in input mode
if (this.headerActionsEl) {
this.headerActionsEl.style.display = 'none';
}
}
}
/**
* Updates layout when tabBarPosition setting changes.
* Called from settings when user changes the tab bar position.
*/
updateLayoutForPosition(): void {
if (!this.viewContainerEl) return;
const isHeaderMode = this.plugin.settings.tabBarPosition === 'header';
// Update container class for CSS styling
this.viewContainerEl.toggleClass('claudian-container--header-mode', isHeaderMode);
// Move nav content to appropriate location
this.updateNavRowLocation();
// Update tab bar and title visibility
this.updateTabBarVisibility();
}
// ============================================
// Tab Management
// ============================================
private handleTabClick(tabId: TabId): void {
this.tabManager?.switchToTab(tabId);
}
private async handleTabClose(tabId: TabId): Promise<void> {
const tab = this.tabManager?.getTab(tabId);
// If streaming, treat close like user interrupt (force close cancels the stream)
const force = tab?.state.isStreaming ?? false;
await this.tabManager?.closeTab(tabId, force);
this.updateTabBarVisibility();
}
async createNewTab(): Promise<void> {
const tab = await this.tabManager?.createTab();
if (!tab) {
const maxTabs = this.plugin.settings.maxTabs ?? 3;
new Notice(`Maximum ${maxTabs} tabs allowed`);
return;
}
this.updateTabBarVisibility();
}
private updateTabBar(): void {
if (!this.tabManager || !this.tabBar) return;
// Debounce tab bar updates using requestAnimationFrame
if (this.pendingTabBarUpdate !== null) {
cancelAnimationFrame(this.pendingTabBarUpdate);
}
this.pendingTabBarUpdate = requestAnimationFrame(() => {
this.pendingTabBarUpdate = null;
if (!this.tabManager || !this.tabBar) return;
const items = this.tabManager.getTabBarItems();
this.tabBar.update(items);
this.updateTabBarVisibility();
});
}
private updateTabBarVisibility(): void {
if (!this.tabBarContainerEl || !this.tabManager) return;
const tabCount = this.tabManager.getTabCount();
const showTabBar = tabCount >= 2;
const isHeaderMode = this.plugin.settings.tabBarPosition === 'header';
// Hide tab badges when only 1 tab, show when 2+
this.tabBarContainerEl.style.display = showTabBar ? 'flex' : 'none';
// In header mode, badges replace logo/title in the same location
// In input mode, keep logo/title visible (badges are in nav row)
const hideBranding = showTabBar && isHeaderMode;
if (this.logoEl) {
this.logoEl.style.display = hideBranding ? 'none' : '';
}
if (this.titleTextEl) {
this.titleTextEl.style.display = hideBranding ? 'none' : '';
}
}
/** Sets `data-provider` on the root container so CSS brand color follows the active provider. */
private syncProviderBrandColor(): void {
if (!this.viewContainerEl) return;
const activeTab = this.tabManager?.getActiveTab();
const providerId = activeTab ? getTabProviderId(activeTab, this.plugin) : DEFAULT_CHAT_PROVIDER_ID;
this.viewContainerEl.dataset.provider = providerId;
this.syncHeaderLogo(providerId);
}
/** Rebuilds the header logo SVG to match the given provider. */
private syncHeaderLogo(providerId: ProviderId): void {
if (!this.logoEl) return;
const icon = ProviderRegistry.getChatUIConfig(providerId).getProviderIcon?.();
if (!icon) return;
const existing = this.logoEl.querySelector('svg');
if (existing?.getAttribute('data-provider') === providerId) return;
this.logoEl.empty();
const NS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(NS, 'svg');
svg.setAttribute('viewBox', icon.viewBox);
svg.setAttribute('width', '18');
svg.setAttribute('height', '18');
svg.setAttribute('fill', 'none');
svg.setAttribute('data-provider', providerId);
const path = document.createElementNS(NS, 'path');
path.setAttribute('d', icon.path);
path.setAttribute('fill', 'currentColor');
svg.appendChild(path);
this.logoEl.appendChild(svg);
}
// ============================================
// History Dropdown
// ============================================
private toggleHistoryDropdown(): void {
if (!this.historyDropdown) return;
const isVisible = this.historyDropdown.hasClass('visible');
if (isVisible) {
this.historyDropdown.removeClass('visible');
} else {
this.updateHistoryDropdown();
this.historyDropdown.addClass('visible');
}
}
private updateHistoryDropdown(): void {
if (!this.historyDropdown) return;
this.historyDropdown.empty();
const activeTab = this.tabManager?.getActiveTab();
const conversationController = activeTab?.controllers.conversationController;
if (conversationController) {
conversationController.renderHistoryDropdown(this.historyDropdown, {
onSelectConversation: (id) => this.openHistoryConversation(id),
onOpenConversationInNewTab: (id, activate) =>
this.openHistoryConversationInNewTab(id, activate),
getConversationOpenState: (id) => this.getHistoryConversationOpenState(id),
});
}
}
private async openHistoryConversation(conversationId: string): Promise<void> {
await this.tabManager?.openConversation(conversationId);
this.historyDropdown?.removeClass('visible');
}
private async openHistoryConversationInNewTab(
conversationId: string,
activate = true,
): Promise<void> {
await this.tabManager?.openConversation(conversationId, {
preferNewTab: true,
activate,
});
this.historyDropdown?.removeClass('visible');
}
private getHistoryConversationOpenState(conversationId: string): HistoryConversationOpenState {
const activeTab = this.tabManager?.getActiveTab();
if (activeTab?.conversationId === conversationId) {
return 'current';
}
if (this.findTabWithConversation(conversationId)) {
return 'open';
}
const crossViewResult = this.plugin.findConversationAcrossViews(conversationId);
if (crossViewResult && crossViewResult.view !== this) {
return 'open';
}
return 'closed';
}
private findTabWithConversation(conversationId: string): TabData | null {
const tabs = this.tabManager?.getAllTabs() ?? [];
return tabs.find(tab => tab.conversationId === conversationId) ?? null;
}
// ============================================
// Event Wiring
// ============================================
private wireEventHandlers(): void {
// Document-level click to close dropdowns
this.registerDomEvent(document, 'click', () => {
this.historyDropdown?.removeClass('visible');
});
// View-level Shift+Tab to toggle plan mode (works from any focused element)
this.registerDomEvent(this.containerEl, 'keydown', (e: KeyboardEvent) => {
if (e.key === 'Tab' && e.shiftKey && !e.isComposing) {
e.preventDefault();
const activeTab = this.tabManager?.getActiveTab();
if (!activeTab) return;
const providerId = getTabProviderId(activeTab, this.plugin);
if (!ProviderRegistry.getCapabilities(providerId).supportsPlanMode) return;
const current = this.plugin.settings.permissionMode;
if (current === 'plan') {
const restoreMode = activeTab.state.prePlanPermissionMode ?? 'normal';
activeTab.state.prePlanPermissionMode = null;
updatePlanModeUI(activeTab, this.plugin, restoreMode);
} else {
activeTab.state.prePlanPermissionMode = current;
updatePlanModeUI(activeTab, this.plugin, 'plan');
}
}
});
// Alt+K (Option+K on Mac): insert a line-range @mention from the current editor selection.
// Registered on document so it fires even when focus is in the editor pane.
this.registerDomEvent(document, 'keydown', (e: KeyboardEvent) => {
if (!e.altKey || e.code !== 'KeyK' || e.isComposing) return;
const activeTab = this.tabManager?.getActiveTab();
if (!activeTab) return;
const selectionController = activeTab.controllers.selectionController;
const fileContextManager = activeTab.ui.fileContextManager;
const inputEl = activeTab.dom.inputEl;
if (!selectionController || !fileContextManager || !inputEl) return;
const ctx = selectionController.getContext();
if (!ctx || ctx.mode !== 'selection') return;
// Reject the sentinel notePath set when view.file is null
if (!ctx.notePath || ctx.notePath === 'unknown') return;
const filename = ctx.notePath.split('/').pop() ?? ctx.notePath;
const current = inputEl.value;
const needsSpace = current.length > 0 && !/\s$/.test(current);
if (ctx.startLine !== undefined) {
// Source mode: line numbers are known — insert @mention token and register for send-time resolution
const start = ctx.startLine;
const end = start + (ctx.lineCount ?? 1) - 1;
const mentionText = start === end ? `@${filename}#${start}` : `@${filename}#${start}-${end}`;
inputEl.value = current + (needsSpace ? ' ' : '') + mentionText + ' ';
inputEl.selectionStart = inputEl.selectionEnd = inputEl.value.length;
fileContextManager.attachFile(ctx.notePath);
fileContextManager.attachLineRangeMention(ctx.notePath, start, end);
} else {
// Reading mode: no line numbers — inline the selected text directly as an editor_selection block
const block = `<editor_selection path="${ctx.notePath}">\n${ctx.selectedText}\n</editor_selection>`;
inputEl.value = current + (needsSpace ? '\n\n' : '') + block + '\n\n';
inputEl.selectionStart = inputEl.selectionEnd = inputEl.value.length;
fileContextManager.attachFile(ctx.notePath);
}
inputEl.dispatchEvent(new Event('input', { bubbles: true }));
inputEl.focus();
e.preventDefault();
});
// Shift+drop: capture phase on document so we intercept before Obsidian's own drop handler.
// Without Shift, the drop falls through to Obsidian's default handling.
const onDragOver = (e: DragEvent) => {
if (!e.shiftKey) return;
if (!this.containerEl.contains(e.target as Node)) return;
e.preventDefault();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'link';
};
const onDrop = (e: DragEvent) => {
if (!e.shiftKey) return;
if (!this.containerEl.contains(e.target as Node)) return;
e.preventDefault();
e.stopPropagation();
const activeTab = this.tabManager?.getActiveTab();
if (!activeTab) return;
const inputEl = activeTab.dom.inputEl;
if (!inputEl) return;
const dt = e.dataTransfer;
if (!dt) return;
const vault = this.app.vault;
const mentions: string[] = [];
// Obsidian internal drag: text/plain = "obsidian://open?vault=...&file=<encoded-path>"
const textData = dt.getData('text/plain');
if (textData) {
for (const raw of textData.split('\n')) {
const line = raw.trim();
try {
const url = new URL(line);
const filePath = url.searchParams.get('file');
if (filePath) {
const decoded = decodeURIComponent(filePath);
const vaultFile = vault.getAbstractFileByPath(decoded) ?? vault.getAbstractFileByPath(decoded + '.md');
const mentionPath = vaultFile ? vaultFile.path : decoded;
mentions.push(`@${mentionPath}`);
if (vaultFile) activeTab.ui.fileContextManager?.attachFile(vaultFile.path);
}
} catch {
// not a valid URL, skip
}
}
}
// Native OS file drop fallback (files dragged from Finder, etc.)
if (mentions.length === 0 && dt.files.length > 0) {
for (let i = 0; i < dt.files.length; i++) {
const fileName = dt.files[i].name;
const vaultFile = vault.getFiles().find((f) => f.name === fileName);
const mentionText = vaultFile ? `@${vaultFile.path}` : `@${fileName}`;
mentions.push(mentionText);
if (vaultFile) activeTab.ui.fileContextManager?.attachFile(vaultFile.path);
}
}
if (mentions.length === 0) return;
const current = inputEl.value;
const needsSpace = current.length > 0 && !/\s$/.test(current);
inputEl.value = current + (needsSpace ? ' ' : '') + mentions.join(' ') + ' ';
inputEl.selectionStart = inputEl.selectionEnd = inputEl.value.length;
inputEl.dispatchEvent(new Event('input', { bubbles: true }));
inputEl.focus();
};
document.addEventListener('dragover', onDragOver, true);
document.addEventListener('drop', onDrop, true);
this.register(() => {
document.removeEventListener('dragover', onDragOver, true);
document.removeEventListener('drop', onDrop, true);
});
// Register Escape on the view's Obsidian Scope to prevent Obsidian from
// navigating away when Claudian is open as a main-area tab.
// Returning false consumes the event (preventDefault + stops scope propagation).
this.scope = new Scope(this.app.scope);
this.scope.register([], 'Escape', () => {
const activeTab = this.tabManager?.getActiveTab();
if (activeTab?.state.isStreaming) {
activeTab.controllers.inputController?.cancelStreaming();
}
return false;
});
// Vault events - forward to active tab's file context manager
const markCacheDirty = (includesFolders: boolean): void => {
const mgr = this.tabManager?.getActiveTab()?.ui.fileContextManager;
if (!mgr) return;
mgr.markFileCacheDirty();
if (includesFolders) mgr.markFolderCacheDirty();
};
this.eventRefs.push(
this.plugin.app.vault.on('create', () => markCacheDirty(true)),
this.plugin.app.vault.on('delete', () => markCacheDirty(true)),
this.plugin.app.vault.on('rename', () => markCacheDirty(true)),
this.plugin.app.vault.on('modify', () => markCacheDirty(false))
);
// File open event
this.registerEvent(
this.plugin.app.workspace.on('file-open', (file) => {
if (file) {
this.tabManager?.getActiveTab()?.ui.fileContextManager?.handleFileOpen(file);
}
})
);
// Click outside to close mention dropdown
this.registerDomEvent(document, 'click', (e) => {
const activeTab = this.tabManager?.getActiveTab();
if (activeTab) {
const fcm = activeTab.ui.fileContextManager;
if (fcm && !fcm.containsElement(e.target as Node) && e.target !== activeTab.dom.inputEl) {
fcm.hideMentionDropdown();
}
}
});
}
// ============================================
// Persistence
// ============================================
private async restoreOrCreateTabs(): Promise<void> {
if (!this.tabManager) return;
// Try to restore from persisted state
const persistedState = await this.plugin.storage.getTabManagerState();
if (persistedState && persistedState.openTabs.length > 0) {
await this.tabManager.restoreState(persistedState);
return;
}
// Fallback: create a new empty tab
await this.tabManager.createTab();
}
private persistTabState(): void {
// Debounce persistence to avoid rapid writes (300ms delay)
if (this.pendingPersist !== null) {
clearTimeout(this.pendingPersist);
}
this.pendingPersist = setTimeout(() => {
this.pendingPersist = null;
if (!this.tabManager) return;
const state = this.tabManager.getPersistedState();
this.plugin.persistTabManagerState(state).catch(() => {
// Silently ignore persistence errors
});
}, 300);
}
/** Force immediate persistence (for onClose/onunload). */
private async persistTabStateImmediate(): Promise<void> {
// Cancel any pending debounced persist
if (this.pendingPersist !== null) {
clearTimeout(this.pendingPersist);
this.pendingPersist = null;
}
if (!this.tabManager) return;
const state = this.tabManager.getPersistedState();
await this.plugin.persistTabManagerState(state);
}
// ============================================
// Public API
// ============================================
/** Gets the currently active tab. */
getActiveTab(): TabData | null {
return this.tabManager?.getActiveTab() ?? null;
}
/** Gets the tab manager. */
getTabManager(): TabManager | null {
return this.tabManager;
}
}