-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.ts
More file actions
1470 lines (1270 loc) · 60 KB
/
Copy pathsettings.ts
File metadata and controls
1470 lines (1270 loc) · 60 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, PluginSettingTab, Setting, Modal, TextComponent, ButtonComponent, Notice, TFile, TFolder, ExtraButtonComponent, MarkdownRenderer, getIcon, DropdownComponent, ToggleComponent, Scope, setIcon, AbstractInputSuggest } from "obsidian";
import { DEFAULT_METRICS, DreamMetricsSettings } from "./src/types/core";
import { LogLevel } from "./src/types/logging";
import { DreamMetric, SelectionMode } from "./src/types/core";
import DreamMetricsPlugin from "./main";
import { debug, info, error } from './src/logging';
import { ModalsManager } from './src/dom/modals/ModalsManager';
import { defaultLintingSettings } from './src/types/journal-check-defaults';
// Define the correct order for recommended metrics
export const RECOMMENDED_METRICS_ORDER = [
'Sensory Detail',
'Emotional Recall',
'Lost Segments',
'Descriptiveness',
'Confidence Score'
];
// Define the correct order for disabled metrics
export const DISABLED_METRICS_ORDER = [
'Words',
'Dream Theme',
'Symbolic Content',
'Lucidity Level',
'Dream Coherence',
'Environmental Familiarity',
'Time Distortion',
'Character Roles',
'Characters Count',
'Characters List',
'Familiar Count',
'Unfamiliar Count',
'Character Clarity/Familiarity',
'Ease of Recall',
'Recall Stability'
];
// Import settings helpers
import {
getProjectNotePath,
setProjectNotePath,
isBackupEnabled,
setBackupEnabled,
getBackupFolderPath,
setBackupFolderPath,
shouldShowRibbonButtons,
setShowRibbonButtons,
getLogMaxSize
} from './src/utils/settings-helpers';
// Import metric helpers
import {
isMetricEnabled,
setMetricEnabled,
getMetricMinValue,
getMetricMaxValue,
setMetricRange,
getMetricRange,
standardizeMetric,
createCompatibleMetric
} from './src/utils/metric-helpers';
// Import SettingsAdapter
import { SettingsAdapter } from './src/state/adapters/SettingsAdapter';
import { JournalStructureSettings as LintingSettings } from './src/types/journal-check';
interface IconCategory {
name: string;
description: string;
icons: string[];
}
export const iconCategories: IconCategory[] = [
{
name: "Metrics",
description: "Icons for core metrics",
icons: [
'eye',
'heart',
'circle-minus',
'pen-tool',
'check-circle',
'sparkles',
'wand-2',
'zap',
'glasses',
'link',
'ruler',
'layers'
]
},
{
name: "Characters",
description: "Icons for character-related metrics",
icons: [
'user-cog',
'users',
'user-check',
'user-x',
'users-round'
]
}
];
// For backward compatibility - map icon names to themselves
export const lucideIconMap: Record<string, string> = {};
iconCategories.forEach(category => {
category.icons.forEach(icon => {
lucideIconMap[icon] = icon;
});
});
// Helper function to ensure a metric has all required properties
// Uses standardizeMetric under the hood to ensure proper type compatibility
export function ensureCompleteMetric(metric: Partial<DreamMetric>): DreamMetric {
// Check if this is a text-based metric
const isTextMetric = metric.type === 'string' || metric.type === 'text';
// Start with all properties from the original metric
const metricWithRequired = {
...metric, // Include all original properties
name: metric.name || '',
icon: metric.icon || '',
// Only set minValue/maxValue for non-text metrics
minValue: isTextMetric ? undefined : (metric.minValue ?? 1),
maxValue: isTextMetric ? undefined : (metric.maxValue ?? 5),
description: metric.description || '',
enabled: metric.enabled !== undefined ? metric.enabled : true
};
// Let standardizeMetric handle all the normalization
return standardizeMetric(metricWithRequired);
}
// Validation functions
function validateMetricName(name: string, existingMetrics: DreamMetric[]): string | null {
if (!name.trim()) return "Name cannot be empty";
if (name.length > 50) return "Name must be 50 characters or less";
if (!/^[a-zA-Z0-9\s\-/]+$/.test(name)) return "Name can only contain letters, numbers, spaces, hyphens, and forward slashes";
if (existingMetrics.some(m => m.name.toLowerCase() === name.toLowerCase())) {
return "A metric with this name already exists";
}
return null;
}
function validateMetricRange(min: number, max: number): string | null {
if (min < 0 || max < 0) return "Range values cannot be negative";
if (min > max) return "Minimum value must be less than maximum value";
if (max > 100) return "Maximum value cannot exceed 100";
if (!Number.isInteger(min) || !Number.isInteger(max)) return "Range values must be integers";
return null;
}
function validateMetricDescription(description: string | undefined): string | null {
// Description is optional, so empty or undefined is valid
if (!description || !description.trim()) return null;
if (description.length > 200) return "Description must be 200 characters or less";
return null;
}
// Metric Editor Modal
export class MetricEditorModal extends Modal {
private metric: DreamMetric;
private onSubmit: (metric: DreamMetric) => void;
private existingMetrics: DreamMetric[];
private isEditing: boolean;
private previewInterval: number;
private originalName: string;
constructor(app: App, metric: DreamMetric, existingMetrics: DreamMetric[], onSubmit: (metric: DreamMetric) => void, isEditing: boolean = false) {
super(app);
// Create a complete metric with all required properties
// Then standardize it for consistency
this.metric = ensureCompleteMetric(metric);
this.existingMetrics = existingMetrics;
this.onSubmit = onSubmit;
this.isEditing = isEditing;
this.originalName = metric.name || '';
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass('oom-metric-editor-modal');
contentEl.createEl('h2', { text: this.isEditing ? 'Edit metric' : 'Add new metric', cls: 'oom-modal-title' });
const nameSection = contentEl.createEl('div', { cls: 'oom-metric-editor-section' });
const nameSetting = new Setting(nameSection)
.setName('Name')
.setDesc('The name of the metric (letters, numbers, spaces, hyphens, and forward slashes only)')
.addText(text => {
text.setValue(this.metric.name)
.onChange(value => {
const error = validateMetricName(value, this.existingMetrics);
nameSetting.setDesc(error || 'The name of the metric (letters, numbers, spaces, hyphens, and forward slashes only)');
nameSetting.controlEl.classList.toggle('is-invalid', !!error);
this.metric.name = value;
renderRangeSection();
this.updatePreview();
});
});
const iconSection = contentEl.createEl('div', { cls: 'oom-metric-editor-section' });
const iconPickerContainer = contentEl.createEl('div', { cls: 'oom-icon-picker-container' });
// Add search bar
const searchContainer = iconPickerContainer.createEl('div', { cls: 'oom-icon-picker-search' });
const searchInput = searchContainer.createEl('input', {
type: 'text',
placeholder: 'Search icons...',
cls: 'oom-icon-picker-search-input'
});
// Add category tabs
const categoryTabs = iconPickerContainer.createEl('div', { cls: 'oom-icon-picker-tabs' });
iconCategories.forEach((category, index) => {
const tab = categoryTabs.createEl('button', {
cls: 'oom-icon-picker-tab',
text: category.name,
attr: { type: 'button' }
});
if (index === 0) tab.classList.add('active');
tab.onclick = () => {
categoryTabs.querySelectorAll('.oom-icon-picker-tab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
renderIconGrid(category);
};
});
// Create icon grid container
const iconGrid = iconPickerContainer.createEl('div', { cls: 'oom-icon-picker-grid' });
// Function to render icons for a category
const renderIconGrid = (category: IconCategory) => {
iconGrid.empty();
category.icons.forEach((iconName: string) => {
const iconBtn = iconGrid.createEl('button', {
cls: 'oom-icon-picker-btn u-padding--xs',
attr: {
type: 'button',
'aria-label': iconName,
'data-icon-name': iconName
}
});
// Use Obsidian's setIcon function
setIcon(iconBtn, iconName);
if (this.metric.icon === iconName) iconBtn.classList.add('selected');
iconBtn.onclick = () => {
this.metric.icon = iconName;
Array.from(iconGrid.children).forEach(btn => btn.classList.remove('selected'));
iconBtn.classList.add('selected');
this.updatePreview();
};
});
};
// Initial render of first category
renderIconGrid(iconCategories[0]);
// Add search functionality
searchInput.oninput = (e) => {
const searchTerm = (e.target as HTMLInputElement).value.toLowerCase();
const allIcons: string[] = [];
iconCategories.forEach(category => {
allIcons.push(...category.icons);
});
iconGrid.empty();
allIcons.forEach((iconName: string) => {
if (iconName.toLowerCase().includes(searchTerm)) {
const iconBtn = iconGrid.createEl('button', {
cls: 'oom-icon-picker-btn u-padding--xs',
attr: {
type: 'button',
'aria-label': iconName,
'data-icon-name': iconName
}
});
// Use Obsidian's setIcon function
setIcon(iconBtn, iconName);
if (this.metric.icon === iconName) iconBtn.classList.add('selected');
iconBtn.onclick = () => {
this.metric.icon = iconName;
Array.from(iconGrid.children).forEach(btn => btn.classList.remove('selected'));
iconBtn.classList.add('selected');
this.updatePreview();
};
}
});
};
// Add clear button
const clearBtn = iconPickerContainer.createEl('button', {
cls: 'oom-icon-picker-clear',
text: 'No icon',
attr: { type: 'button' }
});
clearBtn.onclick = () => {
this.metric.icon = '';
Array.from(iconGrid.children).forEach(btn => btn.classList.remove('selected'));
this.updatePreview();
};
const rangeSection = contentEl.createEl('div', { cls: 'oom-metric-editor-section' });
let rangeSetting: Setting | null = null;
const renderRangeSection = () => {
// Clear the section first
rangeSection.empty();
// Check if this is a text-based metric
const textMetricNames = ['Dream Themes', 'Characters List', 'Symbolic Content'];
const isTextMetric = this.metric.type === 'string' ||
this.metric.type === 'text' ||
textMetricNames.includes(this.metric.name);
if (isTextMetric) {
// Don't show range for text metrics
return;
}
const { min, max } = getMetricRange(this.metric);
rangeSetting = new Setting(rangeSection)
.setName('Range')
.setDesc('The valid range for this metric')
.addText(text => {
text.setValue(min.toString())
.setPlaceholder('Min')
.onChange(value => {
const minVal = parseInt(value);
const error = validateMetricRange(minVal, getMetricMaxValue(this.metric));
rangeSetting!.setDesc(error || 'The valid range for this metric');
rangeSetting!.controlEl.classList.toggle('is-invalid', !!error);
if (!isNaN(minVal)) {
setMetricRange(this.metric, minVal, getMetricMaxValue(this.metric));
}
this.updatePreview();
});
})
.addText(text => {
text.setValue(max.toString())
.setPlaceholder('Max')
.onChange(value => {
const maxVal = parseInt(value);
const error = validateMetricRange(getMetricMinValue(this.metric), maxVal);
rangeSetting!.setDesc(error || 'The valid range for this metric');
rangeSetting!.controlEl.classList.toggle('is-invalid', !!error);
if (!isNaN(maxVal)) {
setMetricRange(this.metric, getMetricMinValue(this.metric), maxVal);
}
this.updatePreview();
});
});
};
renderRangeSection();
const descSection = contentEl.createEl('div', { cls: 'oom-metric-editor-section' });
const descSetting = new Setting(descSection)
.setName('Description (optional)')
.setDesc('A description of what this metric measures')
.addTextArea(text => {
text.setValue(this.metric.description || '')
.onChange(value => {
const error = validateMetricDescription(value);
descSetting.setDesc(error || 'A description of what this metric measures (optional)');
descSetting.controlEl.classList.toggle('is-invalid', !!error);
this.metric.description = value;
this.updatePreview();
});
});
// Frontmatter property
const frontmatterSection = contentEl.createEl('div', { cls: 'oom-metric-editor-section' });
new Setting(frontmatterSection)
.setName('Frontmatter property')
.setDesc('Optional: Map this metric to a frontmatter property (e.g., dream-lucidity-level)')
.addText(text => {
// Generate suggested property name based on metric name
const cleanedName = this.metric.name.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '') // Remove special characters
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-') // Replace multiple hyphens with single
.trim();
// Don't add "dream-" prefix if the name already starts with "dream"
const suggestedProperty = cleanedName.startsWith('dream')
? cleanedName
: `dream-${cleanedName}`;
text.setValue(this.metric.frontmatterProperty || '')
.setPlaceholder(suggestedProperty)
.onChange(value => {
this.metric.frontmatterProperty = value.trim() || undefined;
this.updatePreview();
});
});
// Enabled toggle
new Setting(contentEl.createEl('div', { cls: 'oom-metric-editor-section' }))
.setName('Enabled')
.setDesc('Whether this metric is visible in the UI')
.addToggle(toggle => {
toggle
.setValue(isMetricEnabled(this.metric))
.onChange(value => {
this.metric.enabled = value;
this.updatePreview();
});
});
const previewSection = contentEl.createEl('div', { cls: 'oom-metric-editor-section' });
const previewSetting = new Setting(previewSection)
.setName('Preview')
.setDesc('How this metric will appear in your dream journal:');
const previewEl = previewSection.createEl('div', { cls: 'oom-metric-preview' });
this.updatePreview(previewEl);
// Keyboard shortcuts help
const shortcutsEl = contentEl.createEl('div', { cls: 'oom-keyboard-shortcuts' });
shortcutsEl.createEl('div', { text: 'Keyboard Shortcuts:' });
shortcutsEl.createEl('div', { text: '• Enter: Save changes' });
shortcutsEl.createEl('div', { text: '• Esc: Cancel' });
shortcutsEl.createEl('div', { text: '• Tab: Next field' });
shortcutsEl.createEl('div', { text: '• Shift+Tab: Previous field' });
// Buttons
const buttonContainer = contentEl.createEl('div', { cls: 'oom-modal-button-container oom-metric-editor-buttons' });
const cancelBtn = new ButtonComponent(buttonContainer)
.setButtonText('Cancel');
cancelBtn.buttonEl.classList.add('oom-modal-button');
cancelBtn.onClick(() => this.close());
const saveBtn = new ButtonComponent(buttonContainer)
.setButtonText(this.isEditing ? 'Save changes' : 'Add metric')
.setCta();
saveBtn.buttonEl.classList.add('oom-modal-button');
saveBtn.onClick(() => {
if (this.validateAll()) {
this.onSubmit(this.metric);
this.close();
}
});
// Focus the name field
const nameInput = nameSetting.controlEl.querySelector('input');
if (nameInput) nameInput.focus();
}
private updatePreview(previewEl?: HTMLElement) {
if (!previewEl) {
previewEl = document.querySelector('.oom-metric-preview');
}
if (!previewEl) return;
previewEl.empty();
// Create preview header
previewEl.createEl('h3', { text: 'Preview' });
// Create metric line with a sample value, including icon if present
const range = getMetricRange(this.metric);
const sampleValue = Math.floor((range.min + range.max) / 2);
const metricLine = previewEl.createEl('div', { cls: 'oom-metric-preview-line' });
if (this.metric.icon) {
const iconSpan = document.createElement('span');
iconSpan.className = 'oom-metric-icon';
// Use Obsidian's setIcon function
setIcon(iconSpan, this.metric.icon);
metricLine.appendChild(iconSpan);
}
metricLine.createEl('span', {
cls: 'oom-metric-name',
text: this.metric.name + ': '
});
metricLine.createEl('span', {
cls: 'oom-metric-value',
text: sampleValue.toString()
});
if (this.metric.description) {
previewEl.createEl('div', {
cls: 'oom-preview-description',
text: this.metric.description
});
}
// Show range
if (range.min !== undefined && range.max !== undefined) {
previewEl.createEl('div', {
cls: 'oom-preview-range',
text: `Valid range: ${range.min} to ${range.max}`
});
}
// Show frontmatter property if set
if (this.metric.frontmatterProperty) {
previewEl.createEl('div', {
cls: 'oom-preview-frontmatter',
text: `Frontmatter property: ${this.metric.frontmatterProperty}`
});
}
}
private validateAll(): boolean {
// When editing, exclude the original metric from name validation
const metricsForValidation = this.isEditing
? this.existingMetrics.filter(m => m.name !== this.originalName)
: this.existingMetrics;
const nameError = validateMetricName(this.metric.name, metricsForValidation);
const rangeError = validateMetricRange(
getMetricMinValue(this.metric),
getMetricMaxValue(this.metric)
);
const descError = validateMetricDescription(this.metric.description);
if (nameError || rangeError || descError) {
// Show specific error message
const errorMsg = nameError || rangeError || descError;
new Notice(`Validation error: ${errorMsg}`);
return false;
}
return true;
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
// Add debounce utility function
function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout;
return (...args: Parameters<T>) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
}
export class DreamMetricsSettingTab extends PluginSettingTab {
id = 'oneirometrics';
plugin: DreamMetricsPlugin;
constructor(app: App, plugin: DreamMetricsPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.addClass('oneirometrics-settings');
const prevScroll = containerEl.scrollTop;
const activeElement = document.activeElement as HTMLElement;
let focusSelector = '';
if (activeElement && containerEl.contains(activeElement)) {
if (activeElement.classList.contains('oom-drag-handle')) {
focusSelector = `.oom-drag-handle[data-index="${activeElement.closest('.setting')?.getAttribute('data-index')}"]`;
} else if (activeElement.classList.contains('setting-action')) {
focusSelector = '.setting-action';
}
}
// Onboarding Banner - dismissible welcome message
if (!this.plugin.settings.onboardingDismissed) {
const onboardingBanner = containerEl.createDiv({ cls: 'oom-onboarding-banner' });
// Create content structure using DOM methods
const content = onboardingBanner.createDiv({ cls: 'oom-onboarding-content' });
// Header section
const header = content.createDiv({ cls: 'oom-onboarding-header' });
header.createSpan({ cls: 'oom-onboarding-icon', text: '🌙' });
header.createEl('h3', { text: 'Welcome to OneiroMetrics v0.17.0!' });
const dismissBtn = header.createEl('button', {
cls: 'oom-onboarding-dismiss',
attr: { 'aria-label': 'Dismiss' },
text: '×'
});
// Description paragraph
const description = content.createEl('p');
description.appendText('Get started by exploring the ');
description.createEl('strong', { text: 'OneiroMetrics Hub' });
description.appendText(' - your central command center for dream tracking and analytics.');
// Action buttons
const actions = content.createDiv({ cls: 'oom-onboarding-actions' });
const hubBtn = actions.createEl('button', {
cls: 'oom-onboarding-hub-btn',
text: 'Open OneiroMetrics Hub'
});
const dismissTextBtn = actions.createEl('button', {
cls: 'oom-onboarding-dismiss-btn',
text: 'Got it, dismiss'
});
// Handle dismiss button - no need for querySelector now
const dismissOnboarding = async () => {
this.plugin.settings.onboardingDismissed = true;
await this.plugin.saveSettings();
onboardingBanner.remove();
};
dismissBtn.addEventListener('click', dismissOnboarding);
dismissTextBtn.addEventListener('click', dismissOnboarding);
// Handle Hub button
hubBtn.addEventListener('click', () => {
// Close the settings modal first
(this.app as any).setting.close();
// Open Hub modal
const modalsManager = new ModalsManager(this.app, this.plugin, null);
modalsManager.openHubModal();
});
}
// Add Reading View requirement notice with contextual styling
const noticeEl = containerEl.createEl('div', {
cls: 'oom-notice oom-notice--info'
});
noticeEl.createEl('strong', { text: 'Note: ' });
noticeEl.createEl('span', {
text: 'OneiroMetrics requires Reading View mode to function properly. The plugin generates interactive HTML content that will only display as raw markup in Live Preview mode.'
});
// Ribbon button is now always enabled by default (as recommended by Obsidian team)
// OneiroMetrics Note Setting with Obsidian's built-in search like Templater
const oneiroMetricsNoteSetting = new Setting(containerEl)
.setName('OneiroMetrics note (Legacy)')
.setDesc('⚠️ DEPRECATED: This setting is only used for the legacy Metrics Note. Use the new OneiroMetrics Dashboard instead (accessible via the Hub). The dashboard provides real-time updates and better performance without requiring a separate note file.')
.addSearch(search => {
search.setPlaceholder('Example: Journals/Dream Diary/Metrics/Metrics.md')
.setValue(getProjectNotePath(this.plugin.settings))
.onChange(async (value) => {
setProjectNotePath(this.plugin.settings, value);
await this.plugin.saveSettings();
});
// Add file suggestions
new FileSuggest(this.app, search.inputEl);
});
// Backup Enabled toggle
const backupToggleSetting = new Setting(containerEl)
.setName('Create backups')
.setDesc('Create backups of the OneiroMetrics note before scraping operations')
.addToggle(toggle => toggle
.setValue(isBackupEnabled(this.plugin.settings))
.onChange(async (value) => {
setBackupEnabled(this.plugin.settings, value);
await this.plugin.saveSettings();
// Show/hide backup folder setting without refreshing entire page
if (backupFolderContainer) {
if (value) {
backupFolderContainer.classList.add('oom-backup-folder-container--visible');
backupFolderContainer.classList.remove('oom-backup-folder-container--hidden');
} else {
backupFolderContainer.classList.add('oom-backup-folder-container--hidden');
backupFolderContainer.classList.remove('oom-backup-folder-container--visible');
}
}
}));
// Backup Folder Path (create container but may be hidden)
const backupFolderContainer = containerEl.createEl('div', { cls: 'oomp-note-backup-folder oom-backup-folder-container' });
// Set initial visibility using CSS classes
if (isBackupEnabled(this.plugin.settings)) {
backupFolderContainer.classList.add('oom-backup-folder-container--visible');
} else {
backupFolderContainer.classList.add('oom-backup-folder-container--hidden');
}
if (true) { // Always create the setting, just hide the container if needed
const backupFolderSetting = new Setting(backupFolderContainer)
.setName('Backup folder')
.setDesc('Select an existing folder where backups will be stored')
.addSearch(search => {
search.setPlaceholder('Choose backup folder...')
.setValue(getBackupFolderPath(this.plugin.settings))
.onChange(async (value) => {
setBackupFolderPath(this.plugin.settings, value);
await this.plugin.saveSettings();
});
// Add folder suggestions
new FolderSuggest(this.app, search.inputEl);
});
}
// Add section border after basic settings
containerEl.createEl('div', { cls: 'oom-section-border' });
// Add Journal Structure Check settings
this.addJournalStructureSettings(containerEl);
// Add section border after journal structure settings
containerEl.createEl('div', { cls: 'oom-section-border' });
// Metrics Management - Redirect to Hub
new Setting(containerEl)
.setName('Metrics management')
.setDesc('Manage the metrics that are tracked in your dream diary')
.addButton(button => {
button.setButtonText('Open Metrics Settings')
.onClick(() => {
// Close the settings modal first
(this.app as any).setting.close();
// Open Hub modal and navigate to Metrics Settings tab
const modalsManager = new ModalsManager(this.app, this.plugin, null);
const hubModal = modalsManager.openHubModal() as any;
// Navigate to the metrics-settings tab
setTimeout(() => {
hubModal.selectTab('metrics-settings');
}, 100);
});
});
// This functionality has been moved to the OneiroMetrics Hub - Metrics Settings tab
// Create Advanced Settings Section (collapsed by default)
const advancedSection = containerEl.createDiv({ cls: 'oom-collapsible-section collapsed' });
// Use Setting API for consistent heading style, but make it collapsible
const advancedSetting = new Setting(advancedSection)
.setName('Advanced')
.setHeading();
// Add collapsible toggle to the setting element
const advancedToggle = advancedSetting.settingEl.createDiv({ cls: 'oom-collapsible-toggle' });
// Create chevron SVG safely
const createChevronSvg = (direction: 'right' | 'down') => {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('viewBox', '0 0 100 100');
svg.setAttribute('class', `oom-chevron-${direction}`);
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('fill', 'none');
path.setAttribute('stroke', 'currentColor');
path.setAttribute('stroke-width', '15');
path.setAttribute('d', direction === 'right' ? 'M30,10 L70,50 L30,90' : 'M10,30 L50,70 L90,30');
svg.appendChild(path);
return svg;
};
advancedToggle.appendChild(createChevronSvg('right'));
advancedToggle.addClass('oom-advanced-toggle');
// Make the setting element itself clickable
advancedSetting.settingEl.addClass('oom-advanced-setting-container');
const advancedContent = advancedSection.createDiv({
cls: 'oom-collapsible-content oom-advanced-content oom-advanced-content--collapsed'
});
const toggleAdvanced = () => {
const isCollapsed = advancedSection.hasClass('collapsed');
advancedSection.toggleClass('collapsed', !isCollapsed);
if (isCollapsed) {
advancedToggle.empty();
advancedToggle.appendChild(createChevronSvg('down'));
advancedContent.classList.add('oom-advanced-content--expanded');
advancedContent.classList.remove('oom-advanced-content--collapsed');
} else {
advancedToggle.empty();
advancedToggle.appendChild(createChevronSvg('right'));
advancedContent.classList.add('oom-advanced-content--collapsed');
advancedContent.classList.remove('oom-advanced-content--expanded');
}
};
advancedSetting.settingEl.addEventListener('click', toggleAdvanced);
advancedToggle.addEventListener('click', (e) => {
e.stopPropagation();
toggleAdvanced();
});
// Logging Settings (inside Advanced section)
// Store references to conditional settings for showing/hiding
let logManagementSetting: Setting;
let performanceSection: HTMLElement;
const updateLoggingSettingsVisibility = (logLevel: string) => {
const shouldShow = logLevel !== 'off';
if (logManagementSetting) {
if (shouldShow) {
logManagementSetting.settingEl.classList.add('oom-logging-management--visible');
logManagementSetting.settingEl.classList.remove('oom-logging-management--hidden');
} else {
logManagementSetting.settingEl.classList.add('oom-logging-management--hidden');
logManagementSetting.settingEl.classList.remove('oom-logging-management--visible');
}
}
if (performanceSection) {
if (shouldShow) {
performanceSection.classList.add('oom-performance-section--visible');
performanceSection.classList.remove('oom-performance-section--hidden');
} else {
performanceSection.classList.add('oom-performance-section--hidden');
performanceSection.classList.remove('oom-performance-section--visible');
}
}
};
new Setting(advancedContent)
.setName('Logging level')
.setDesc('Control the verbosity of logging. Set to "Off" for normal operation, "Info" for basic progress, "Debug" for detailed logging, or "Trace" for maximum verbosity.')
.addDropdown(dropdown => dropdown
.addOption('off', 'Off')
.addOption('errors', 'Errors Only')
.addOption('warn', 'Warnings')
.addOption('info', 'Info')
.addOption('debug', 'Debug')
.addOption('trace', 'Trace')
// Cast to any to avoid type issues with LogLevel
.setValue((this.plugin.settings.logging.level || 'off') as any)
.onChange(async (value) => {
this.plugin.settings.logging.level = value as any;
await this.plugin.saveSettings();
this.plugin.setLogLevel(value as any);
updateLoggingSettingsVisibility(value);
}));
// Export logs button
new Setting(advancedContent)
.setName('Export logs')
.setDesc('Export all logs to a JSON file for analysis or sharing')
.addButton(button => {
button.setButtonText('Export')
.onClick(() => {
this.exportLogsToFile();
});
});
logManagementSetting = new Setting(advancedContent)
.setName('View and manage logs')
.setDesc('Easy access to plugin logs for debugging purposes')
.addButton(button => {
button.setButtonText('Open Log Files')
.onClick(async () => {
// Open the log folder in the file explorer
const logFolder = `${this.app.vault.configDir}/plugins/oneirometrics/logs`;
const folder = this.app.vault.getAbstractFileByPath(logFolder);
if (folder) {
// Note: Obsidian doesn't provide a direct API to open folders
// Show a notice with instructions instead
new Notice('Log files are located in: ' + logFolder);
} else {
new Notice('No log files found yet. Logs will be created when logging is enabled.');
}
});
});
// Add CSS class for conditional visibility
logManagementSetting.settingEl.classList.add('oom-logging-management');
// Add section border after logging settings within Advanced
advancedContent.createEl('div', { cls: 'oom-section-border' });
// Performance Testing Settings (inside Advanced section)
performanceSection = advancedContent.createDiv({ cls: 'oom-performance-section' });
// Performance mode toggle
new Setting(performanceSection)
.setName('Enable performance testing mode')
.setDesc('Removes the normal 200-file limit during scraping operations. Use for testing with large datasets.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.performanceTesting?.enabled ?? false)
.onChange(async (value) => {
if (!this.plugin.settings.performanceTesting) {
this.plugin.settings.performanceTesting = {
enabled: false,
maxFiles: 0,
showWarnings: true
};
}
this.plugin.settings.performanceTesting.enabled = value;
await this.plugin.saveSettings();
this.display(); // Refresh to show/hide dependent settings
}));
// Show dependent settings only when performance mode is enabled
if (this.plugin.settings.performanceTesting?.enabled) {
// Max files setting
new Setting(performanceSection)
.setName('Maximum files to process')
.setDesc('Maximum number of files to process in performance mode. Set to 0 for unlimited.')
.addText(text => text
.setPlaceholder('0')
.setValue(String(this.plugin.settings.performanceTesting?.maxFiles ?? 0))
.onChange(async (value) => {
const maxFiles = parseInt(value) || 0;
if (!this.plugin.settings.performanceTesting) {
this.plugin.settings.performanceTesting = {
enabled: false,
maxFiles: 0,
showWarnings: true
};
}
this.plugin.settings.performanceTesting.maxFiles = maxFiles;
await this.plugin.saveSettings();
}));
// Show warnings toggle
new Setting(performanceSection)
.setName('Show performance warnings')
.setDesc('Display console warnings when performance testing mode is active.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.performanceTesting?.showWarnings ?? true)
.onChange(async (value) => {
if (!this.plugin.settings.performanceTesting) {
this.plugin.settings.performanceTesting = {
enabled: false,
maxFiles: 0,
showWarnings: true
};
}
this.plugin.settings.performanceTesting.showWarnings = value;
await this.plugin.saveSettings();
}));
// Status indicator
const statusText = this.plugin.settings.performanceTesting.maxFiles > 0
? `Processing up to ${this.plugin.settings.performanceTesting.maxFiles} files`
: 'Processing unlimited files';
const statusEl = performanceSection.createEl('div', {
cls: 'oom-notice oom-notice--info'
});
statusEl.createEl('span', {
text: `⚠️ Performance mode active: ${statusText}`
});
}
// Initialize visibility based on current logging level
const currentLogLevel = this.plugin.settings.logging.level || 'off';
updateLoggingSettingsVisibility(currentLogLevel);
// Add section border after the entire Advanced section
containerEl.createEl('div', { cls: 'oom-section-border' });
containerEl.scrollTop = prevScroll;
if (focusSelector) {
const toFocus = containerEl.querySelector(focusSelector) as HTMLElement;
if (toFocus) toFocus.focus();
}
}
private addJournalStructureSettings(containerEl: HTMLElement) {
// Journal Structure settings button
new Setting(containerEl)
.setName('Journal structures and templates')
.setDesc('Configure how journal and dream callouts are generated and recognized')
.addButton(button => button
.setButtonText('Open Settings')
.onClick(() => {
// Close the current settings modal first
(this.app as any).setting.close();
// Then open the Hub modal with Journal Structure tab
const modalsManager = new ModalsManager(this.app, this.plugin, this.plugin.logger);
modalsManager.openHubModal('journal-structure');
}));
}
/**
* Display template manager UI
*/
private displayTemplateManager(containerEl: HTMLElement) {
// Find or create template list container
let templateListContainer = containerEl.querySelector('.oom-template-list-container');
if (!templateListContainer) {
templateListContainer = containerEl.createDiv({ cls: 'oom-template-list-container' });
}
// Clear and reset the container
templateListContainer.empty();
templateListContainer.classList.add('oom-template-manager--visible');
templateListContainer.classList.remove('oom-template-manager--hidden');