-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmain.ts
More file actions
executable file
·1280 lines (1116 loc) · 48.3 KB
/
Copy pathmain.ts
File metadata and controls
executable file
·1280 lines (1116 loc) · 48.3 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
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- Obsidian API returns any-typed surfaces (frontmatter, file caches, plugin state); project policy accepts these. */
import { ItemView, Plugin, Notice, TFile, TFolder, EventRef, WorkspaceLeaf, ObsidianProtocolData } from 'obsidian';
import { CanvasRootsSettings, DEFAULT_SETTINGS, CanvasRootsSettingTab } from './src/settings';
import { LoggerFactory, getLogger } from './src/core/logging';
import { getErrorMessage } from './src/core/error-utils';
import type { NumberingSystem } from './src/core/reference-numbering';
import { FamilyGraphService } from './src/core/family-graph';
import { BidirectionalLinker } from './src/core/bidirectional-linker';
import { RelationshipService } from './src/relationships';
import { MobileClassManager } from './src/core/mobile-class-manager';
import { cleanupPersonReferencesAfterDelete, getDeletedPersonCrId } from './src/core/person-delete-cleanup';
import { RelationshipHistoryService, RelationshipHistoryData, formatChangeDescription } from './src/core/relationship-history';
import { RelationshipHistoryModal } from './src/ui/relationship-history-modal';
import { FamilyChartView, VIEW_TYPE_FAMILY_CHART } from './src/ui/views/family-chart-view';
import { MapView, VIEW_TYPE_MAP } from './src/maps/map-view';
import { StatisticsView, VIEW_TYPE_STATISTICS } from './src/statistics';
import { CalendarView, VIEW_TYPE_CALENDAR } from './src/calendar/calendar-view';
import { RelationshipsView, VIEW_TYPE_RELATIONSHIPS } from './src/relationships/ui/relationships-view';
import { PeopleView, VIEW_TYPE_PEOPLE } from './src/ui/views/people-view';
import { EventsView, VIEW_TYPE_EVENTS } from './src/dates/ui/events-view';
import { PlacesView, VIEW_TYPE_PLACES } from './src/ui/views/places-view';
import { OrganizationsView, VIEW_TYPE_ORGANIZATIONS } from './src/organizations/ui/organizations-view';
import { SourcesView, VIEW_TYPE_SOURCES } from './src/sources/ui/sources-view';
import { UniversesView, VIEW_TYPE_UNIVERSES } from './src/universes/ui/universes-view';
import { CollectionsView, VIEW_TYPE_COLLECTIONS } from './src/ui/collections-view';
import { DataQualityView, VIEW_TYPE_DATA_QUALITY } from './src/ui/data-quality-view';
import { FolderFilterService } from './src/core/folder-filter';
import { TemplateFilterService } from './src/core/template-filter';
import { PersonIndexService } from './src/core/person-index-service';
import { PlaceGraphService } from './src/core/place-graph';
import { EvidenceService, ProofSummaryService, SourceService } from './src/sources';
import { EventService } from './src/events/services/event-service';
import { DateService, createDateService } from './src/dates';
import { TimelineProcessor, RelationshipsProcessor, MediaProcessor, SourceRolesProcessor, TransfersProcessor, MembersProcessor, SourcesProcessor, ExtractionsProcessor, NegativeFindingsProcessor, ResearchTimelineProcessor, UniverseEntitiesProcessor, UniverseMapsProcessor } from './src/dynamic-content';
import { RecentFilesService, RecentEntityType } from './src/core/recent-files-service';
import { registerCustomIcons } from './src/ui/lucide-icons';
import { MediaService } from './src/core/media-service';
import { MigrationNoticeView, VIEW_TYPE_MIGRATION_NOTICE } from './src/ui/views/migration-notice-view';
import { ProfileView, VIEW_TYPE_ENTITY_PROFILE } from './src/profile-view/profile-view';
import { WebClipperService } from './src/core/web-clipper-service';
import { createUniverseService } from './src/universes/services/universe-service';
import { PluginRenameMigrationService, showMigrationNotice } from './src/migration/plugin-rename-migration-service';
import { registerContextMenus } from './src/plugin/context-menus';
import {
activateFamilyChartView as _activateFamilyChartView,
activateMapView as _activateMapView,
activateStatisticsView as _activateStatisticsView,
activateCalendarView as _activateCalendarView,
activateRelationshipsView as _activateRelationshipsView,
activatePeopleView as _activatePeopleView,
activateEventsView as _activateEventsView,
activatePlacesView as _activatePlacesView,
activateOrganizationsView as _activateOrganizationsView,
activateSourcesView as _activateSourcesView,
activateUniversesView as _activateUniversesView,
activateCollectionsView as _activateCollectionsView,
activateDataQualityView as _activateDataQualityView,
activateProfileView as _activateProfileView,
moveFamilyChartToMainWorkspace as _moveFamilyChartToMainWorkspace,
} from './src/plugin/activation';
import {
createBaseTemplate as _createBaseTemplate,
createPlacesBaseTemplate as _createPlacesBaseTemplate,
createOrganizationsBaseTemplate as _createOrganizationsBaseTemplate,
createSourcesBaseTemplate as _createSourcesBaseTemplate,
createUniversesBaseTemplate as _createUniversesBaseTemplate,
createNotesBaseTemplate as _createNotesBaseTemplate,
createResearchBaseTemplate as _createResearchBaseTemplate,
createEventsBaseTemplate as _createEventsBaseTemplate,
createAllBases as _createAllBases,
} from './src/plugin/base-templates';
import {
openLinkMediaModal as _openLinkMediaModal,
openEditPlaceModal as _openEditPlaceModal,
openEditEventModal as _openEditEventModal,
openEditPersonModal as _openEditPersonModal,
promptAssignReferenceNumbers as _promptAssignReferenceNumbers,
promptClearReferenceNumbers as _promptClearReferenceNumbers,
promptAssignLineage as _promptAssignLineage,
promptRemoveLineage as _promptRemoveLineage,
generateTreeForCurrentNote as _generateTreeForCurrentNote,
regenerateCanvas as _regenerateCanvas,
createPersonNote as _createPersonNote,
generateAllTrees as _generateAllTrees,
insertDynamicBlocks as _insertDynamicBlocks,
generateExcalidrawTreeForPerson as _generateExcalidrawTreeForPerson,
} from './src/plugin/bulk-operations';
import { registerCommandsAndEvents as _registerCommandsAndEvents } from './src/plugin/commands';
const logger = getLogger('CanvasRootsPlugin');
export default class CanvasRootsPlugin extends Plugin {
declare settings: CanvasRootsSettings;
private fileModifyEventRef: EventRef | null = null;
private fileDeleteEventRef: EventRef | null = null;
private universeRenameEventRef: EventRef | null = null;
private bidirectionalSnapshotTimer: number | null = null;
public bidirectionalLinker: BidirectionalLinker | null = null;
public mobileClassManager: MobileClassManager = new MobileClassManager();
private relationshipHistory: RelationshipHistoryService | null = null;
private folderFilter: FolderFilterService | null = null;
private templateFilter: TemplateFilterService | null = null;
public personIndex: PersonIndexService | null = null;
private eventService: EventService | null = null;
private sourceService: SourceService | null = null;
private proofSummaryService: ProofSummaryService | null = null;
private recentFilesService: RecentFilesService | null = null;
private mediaService: MediaService | null = null;
private webClipperService: WebClipperService | null = null;
private dateService: DateService | null = null;
/**
* Flag to temporarily disable bidirectional sync during bulk operations (e.g., import)
* This prevents the file watcher from adding duplicate relationships while importing
*/
private _syncDisabled: boolean = false;
/**
* Temporarily disable bidirectional sync (for use during bulk imports)
*/
disableBidirectionalSync(): void {
this._syncDisabled = true;
logger.debug('sync-control', 'Bidirectional sync temporarily disabled');
}
/**
* Re-enable bidirectional sync after bulk operation
*/
enableBidirectionalSync(): void {
this._syncDisabled = false;
logger.debug('sync-control', 'Bidirectional sync re-enabled');
}
/**
* Check if bidirectional sync is currently disabled
*/
isSyncDisabled(): boolean {
return this._syncDisabled;
}
/**
* Get the folder filter service for filtering person notes by folder
*/
getFolderFilter(): FolderFilterService | null {
return this.folderFilter;
}
/**
* Get the template filter service for detecting template folders
*/
getTemplateFilter(): TemplateFilterService | null {
return this.templateFilter;
}
/**
* Resolve a frontmatter property value, checking aliases if canonical property not found.
* Canonical property takes precedence over aliased property.
* @param frontmatter The frontmatter object from a note
* @param canonicalProperty The canonical property name (e.g., 'cr_id', 'born', 'died')
* @returns The property value, or undefined if not found
*/
resolveFrontmatterProperty<T>(frontmatter: Record<string, unknown> | undefined, canonicalProperty: string): T | undefined {
if (!frontmatter) return undefined;
// Canonical property takes precedence
if (frontmatter[canonicalProperty] !== undefined) {
return frontmatter[canonicalProperty] as T;
}
// Check aliases - find user property that maps to this canonical property
const aliases = this.settings.propertyAliases ?? {};
for (const [userProp, canonicalProp] of Object.entries(aliases)) {
if (canonicalProp === canonicalProperty && frontmatter[userProp] !== undefined) {
return frontmatter[userProp] as T;
}
}
return undefined;
}
/**
* Get the event service for managing event notes
*/
getEventService(): EventService | null {
return this.eventService;
}
/**
* Get the bidirectional linker (singleton). Two call sites were
* constructing it inline with identical setup code (folder filter +
* inclusive-parents + DNA-tracking toggles); the singleton hoists
* that setup into one place. Settings-staleness risk is unchanged
* from the prior `if (!this.bidirectionalLinker)` guards both call
* sites already used — neither path re-configured the linker on
* settings changes.
*/
getBidirectionalLinker(): BidirectionalLinker {
if (!this.bidirectionalLinker) {
this.bidirectionalLinker = new BidirectionalLinker(this.app);
if (this.folderFilter) {
this.bidirectionalLinker.setFolderFilter(this.folderFilter);
}
this.bidirectionalLinker.setEnableInclusiveParents(this.settings.enableInclusiveParents);
this.bidirectionalLinker.setEnableDnaTracking(this.settings.enableDnaTracking);
// Provide the symmetric custom relationship type ids so the linker can
// strip orphaned reciprocals when those fields are deleted (#675).
// Scope: symmetric types stored as flat `<typeId>` properties (those
// without a familyGraphMapping), excluding dna_match which the
// dedicated DNA path already cleans up. Re-reads settings live each
// call, so newly-added custom types are picked up automatically.
const relationshipService = new RelationshipService(this);
this.bidirectionalLinker.setSymmetricCustomTypeProvider(() =>
relationshipService.getAllRelationshipTypes()
.filter(type => type.symmetric && !type.familyGraphMapping && type.id !== 'dna_match')
.map(type => type.id)
);
}
return this.bidirectionalLinker;
}
/**
* Get the Source service (singleton)
*/
getSourceService(): SourceService {
if (!this.sourceService) {
this.sourceService = new SourceService(this.app, this.settings);
this.sourceService.setupVaultListeners(this);
}
return this.sourceService;
}
/**
* Get the Proof Summary service (singleton). Hoisted to a singleton
* (#519) so the metadata-cache listeners stay attached for the
* plugin lifetime; previously each consumer constructed its own
* instance and any one of them could observe the cache race.
*/
getProofSummaryService(): ProofSummaryService {
if (!this.proofSummaryService) {
this.proofSummaryService = new ProofSummaryService(this.app, this.settings);
if (this.personIndex) {
this.proofSummaryService.setPersonIndex(this.personIndex);
}
this.proofSummaryService.setupVaultListeners(this);
}
return this.proofSummaryService;
}
/**
* Get the Web Clipper service for detecting clipped notes
*/
getWebClipperService(): WebClipperService | null {
return this.webClipperService;
}
/**
* Get the recent files service for Dashboard tracking
*/
getRecentFilesService(): RecentFilesService | null {
return this.recentFilesService;
}
/**
* Get the media service for entity media operations
*/
getMediaService(): MediaService | null {
return this.mediaService;
}
/**
* Get the date service for parsing standard and fictional dates.
*/
getDateService(): DateService | null {
return this.dateService;
}
/**
* Track a file access for the Dashboard recent files list
*/
async trackRecentFile(file: TFile, type: RecentEntityType): Promise<void> {
if (this.recentFilesService) {
await this.recentFilesService.trackFile(file, type);
}
}
/**
* Create a FamilyGraphService configured with the folder filter
* and optionally populated with research coverage and conflict data when fact tracking is enabled
*/
createFamilyGraphService(): FamilyGraphService {
const graphService = new FamilyGraphService(this.app);
if (this.folderFilter) {
graphService.setFolderFilter(this.folderFilter);
}
if (this.personIndex) {
graphService.setPersonIndex(this.personIndex);
}
// Set settings for note type detection
graphService.setSettings(this.settings);
graphService.setPropertyAliases(this.settings.propertyAliases);
graphService.setValueAliases(this.settings.valueAliases);
graphService.setDateService(this.getDateService());
// Populate research coverage and conflict counts when fact-level tracking is enabled
if (this.settings.trackFactSourcing) {
this.populateResearchCoverage(graphService);
this.populateConflictCounts(graphService);
}
return graphService;
}
/**
* Populate research coverage percentages for all people in the graph
*/
private populateResearchCoverage(graphService: FamilyGraphService): void {
const evidenceService = new EvidenceService(this.app, this.settings);
const people = graphService.getAllPeople();
for (const person of people) {
const coverage = evidenceService.getFactCoverageForFile(person.file);
if (coverage) {
graphService.setResearchCoverage(person.crId, coverage.coveragePercent);
}
}
}
/**
* Populate conflict counts for all people in the graph
* Counts proof summaries with status 'conflicted' or evidence with 'conflicts' support
*/
private populateConflictCounts(graphService: FamilyGraphService): void {
const proofService = this.getProofSummaryService();
const people = graphService.getAllPeople();
for (const person of people) {
const proofs = proofService.getProofsForPerson(person.crId);
// Count conflicts: proofs with status 'conflicted' OR proofs with any conflicting evidence
let conflictCount = 0;
for (const proof of proofs) {
if (proof.status === 'conflicted') {
conflictCount++;
} else if (proof.evidence.some(e => e.supports === 'conflicts')) {
conflictCount++;
}
}
if (conflictCount > 0) {
graphService.setConflictCount(person.crId, conflictCount);
}
}
}
/**
* Create a PlaceGraphService configured with folder filter and settings
*/
createPlaceGraphService(): PlaceGraphService {
const placeGraph = new PlaceGraphService(this.app);
if (this.folderFilter) {
placeGraph.setFolderFilter(this.folderFilter);
}
placeGraph.setSettings(this.settings);
placeGraph.setValueAliases(this.settings.valueAliases);
return placeGraph;
}
async onload() {
console.debug('Loading Charted Roots plugin');
// Register custom icons for visual tree reports
registerCustomIcons();
await this.loadSettings();
// Initialize logger with saved log level
LoggerFactory.setLogLevel(this.settings.logLevel);
// Initialize folder filter service
this.folderFilter = new FolderFilterService(this.settings);
// Initialize template filter service (connects to folder filter)
this.templateFilter = new TemplateFilterService(this.app, this.settings);
this.folderFilter.setTemplateFilter(this.templateFilter);
// Initialize person index service (for wikilink resolution)
this.personIndex = new PersonIndexService(this.app, this.settings);
this.personIndex.setFolderFilter(this.folderFilter);
// Initialize event service
this.eventService = new EventService(this.app, this.settings);
// Initialize recent files service
this.recentFilesService = new RecentFilesService(this);
// Initialize media service
this.mediaService = new MediaService(this.app, this.settings);
// Initialize Web Clipper service (watcher starts after layout-ready)
this.webClipperService = new WebClipperService(this.app, this.settings);
// Initialize date service (standard + fictional parsing with universe context)
this.dateService = createDateService({
enableFictionalDates: this.settings.enableFictionalDates,
showBuiltInDateSystems: this.settings.showBuiltInDateSystems,
fictionalDateSystems: this.settings.fictionalDateSystems
});
// Let fictional-date parsing honor a universe's chosen default calendar
// (the universe note's `default_calendar`), resolving the note's universe
// reference by name or cr_id. Kept as an injected closure so the dates
// layer stays decoupled from the universes layer (#650). The UniverseService
// is memoized so repeated date parsing doesn't re-scan universe notes; its
// own cache picks up universe edits via the metadata-cache.
let universeCalendarService: ReturnType<typeof createUniverseService> | null = null;
this.dateService.setUniverseCalendarResolver((universeRef) => {
if (!universeRef) return null;
if (!universeCalendarService) universeCalendarService = createUniverseService(this);
const universe = universeCalendarService.getUniverseByName(universeRef) ?? universeCalendarService.getUniverse(universeRef);
return universe?.defaultCalendar ?? null;
});
// Run migration for property rename (collection_name -> group_name)
await this.migrateCollectionNameToGroupName();
// Run migration for plugin rename (Charted Roots -> Charted Roots)
// This updates canvas metadata and code block types in vault files
await this.migrateCanvasRootsToChartedRoots();
// Add settings tab
this.addSettingTab(new CanvasRootsSettingTab(this.app, this));
// Trigger Style Settings plugin to parse our CSS settings block
// Delay to ensure Style Settings plugin is loaded first
this.app.workspace.onLayoutReady(() => {
this.app.workspace.trigger('parse-style-settings');
// Initialize template folder detection after plugins are loaded
if (this.templateFilter) {
this.templateFilter.initialize();
}
});
this.registerViews();
this.registerCodeBlockProcessors();
this.registerCommandsAndEvents();
this.registerContextMenus();
// Check for version upgrade and show migration notice if needed
this.app.workspace.onLayoutReady(() => {
void this.checkVersionUpgrade();
});
// Defer vault-listener registration and watcher start to layout-ready
// so plugin load doesn't block on these handlers. File events that
// fire between onload-finish and layout-ready (a sub-second window
// right after the vault opens) are accepted as missed — they don't
// happen in real usage.
this.app.workspace.onLayoutReady(() => {
this.eventService?.setupVaultListeners(this);
this.webClipperService?.startWatching();
this.registerFileModificationHandler();
this.registerFileDeleteHandler();
this.registerUniverseRenameHandler();
});
// Initialize bidirectional relationship snapshots
// This enables deletion detection from the first edit after plugin load
if (this.settings.enableBidirectionalSync) {
this.initializeBidirectionalSnapshots();
}
// Initialize relationship history service (fire-and-forget; consumers
// already null-guard `plugin.relationshipHistory`)
void this.initializeRelationshipHistory();
}
// =========================================================================
// View registrations
// =========================================================================
/**
* Wrapper around `registerView` that also applies the platform-state
* CSS classes (`cr-mobile` / `cr-desktop` / `cr-phone` / `cr-tablet`)
* to the view's container element after construction. Phase 4a
* groundwork — Phase 4b's per-file CSS migration consumes these
* classes so component stylesheets can scope on platform rather than
* the unreliable-on-mobile `@media (max-width: 768px)` selectors.
*/
private registerCRView<T extends ItemView>(
viewType: string,
factory: (leaf: WorkspaceLeaf) => T
): void {
this.registerView(viewType, (leaf) => {
const view = factory(leaf);
this.mobileClassManager.applyPlatformClasses(view.containerEl);
return view;
});
}
private registerViews(): void {
// Register family chart view
this.registerCRView(
VIEW_TYPE_FAMILY_CHART,
(leaf) => new FamilyChartView(leaf, this)
);
// Register map view
this.registerCRView(
VIEW_TYPE_MAP,
(leaf) => new MapView(leaf, this)
);
// Register statistics view
this.registerCRView(
VIEW_TYPE_STATISTICS,
(leaf) => new StatisticsView(leaf, this)
);
// Register calendar view
this.registerCRView(
VIEW_TYPE_CALENDAR,
(leaf) => new CalendarView(leaf, this)
);
// Register relationships view
this.registerCRView(
VIEW_TYPE_RELATIONSHIPS,
(leaf) => new RelationshipsView(leaf, this)
);
// Register people view
this.registerCRView(
VIEW_TYPE_PEOPLE,
(leaf) => new PeopleView(leaf, this)
);
// Register events view
this.registerCRView(
VIEW_TYPE_EVENTS,
(leaf) => new EventsView(leaf, this)
);
// Register places view
this.registerCRView(
VIEW_TYPE_PLACES,
(leaf) => new PlacesView(leaf, this)
);
// Register organizations view
this.registerCRView(
VIEW_TYPE_ORGANIZATIONS,
(leaf) => new OrganizationsView(leaf, this)
);
// Register sources view
this.registerCRView(
VIEW_TYPE_SOURCES,
(leaf) => new SourcesView(leaf, this)
);
// Register universes view
this.registerCRView(
VIEW_TYPE_UNIVERSES,
(leaf) => new UniversesView(leaf, this)
);
// Register collections view
this.registerCRView(
VIEW_TYPE_COLLECTIONS,
(leaf) => new CollectionsView(leaf, this)
);
// Register data quality view
this.registerCRView(
VIEW_TYPE_DATA_QUALITY,
(leaf) => new DataQualityView(leaf, this)
);
// Register migration notice view (for upgrade notifications)
this.registerCRView(
VIEW_TYPE_MIGRATION_NOTICE,
(leaf) => new MigrationNoticeView(leaf, this)
);
// Register entity profile view
this.registerCRView(
VIEW_TYPE_ENTITY_PROFILE,
(leaf) => new ProfileView(leaf, this)
);
// Register URI protocol handler for opening map at specific coordinates
// Usage: obsidian://charted-roots-map?lat=51.5074&lng=-0.1278&zoom=12
// Also register legacy canvas-roots-map for backward compatibility
const mapProtocolHandler = async (params: ObsidianProtocolData) => {
const lat = parseFloat(params.lat);
const lng = parseFloat(params.lng);
const zoom = params.zoom ? parseInt(params.zoom, 10) : 12;
if (!isNaN(lat) && !isNaN(lng)) {
await this.activateMapView(undefined, false, undefined, { lat, lng, zoom });
}
};
this.registerObsidianProtocolHandler('charted-roots-map', mapProtocolHandler);
this.registerObsidianProtocolHandler('canvas-roots-map', mapProtocolHandler); // Legacy compatibility
}
// =========================================================================
// Code block processors
// =========================================================================
private registerCodeBlockProcessors(): void {
// Register dynamic content code block processors
// Register both new (charted-roots-*) and legacy (canvas-roots-*) for backward compatibility
const timelineProcessor = new TimelineProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-timeline',
(source, el, ctx) => timelineProcessor.process(source, el, ctx)
);
this.registerMarkdownCodeBlockProcessor(
'canvas-roots-timeline', // Legacy compatibility
(source, el, ctx) => timelineProcessor.process(source, el, ctx)
);
const relationshipsProcessor = new RelationshipsProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-relationships',
(source, el, ctx) => relationshipsProcessor.process(source, el, ctx)
);
this.registerMarkdownCodeBlockProcessor(
'canvas-roots-relationships', // Legacy compatibility
(source, el, ctx) => relationshipsProcessor.process(source, el, ctx)
);
const mediaProcessor = new MediaProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-media',
(source, el, ctx) => mediaProcessor.process(source, el, ctx)
);
this.registerMarkdownCodeBlockProcessor(
'canvas-roots-media', // Legacy compatibility
(source, el, ctx) => mediaProcessor.process(source, el, ctx)
);
// Source roles processor (#219)
const sourceRolesProcessor = new SourceRolesProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-source-roles',
(source, el, ctx) => sourceRolesProcessor.process(source, el, ctx)
);
// Transfers processor (#123)
const transfersProcessor = new TransfersProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-transfers',
(source, el, ctx) => transfersProcessor.process(source, el, ctx)
);
// Members processor (#268)
const membersProcessor = new MembersProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-members',
(source, el, ctx) => membersProcessor.process(source, el, ctx)
);
// Sources processor (#278)
const sourcesProcessor = new SourcesProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-sources',
(source, el, ctx) => sourcesProcessor.process(source, el, ctx)
);
// Extractions processor (#284) — reverse lookup: source → citing entities
const extractionsProcessor = new ExtractionsProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-extractions',
(source, el, ctx) => extractionsProcessor.process(source, el, ctx)
);
// Negative findings processor (#287) — surfaces negative research results
const negativeFindingsProcessor = new NegativeFindingsProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-negative-findings',
(source, el, ctx) => negativeFindingsProcessor.process(source, el, ctx)
);
// Research timeline processor (#293) — research activity log with gap detection
const researchTimelineProcessor = new ResearchTimelineProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-research-timeline',
(source, el, ctx) => researchTimelineProcessor.process(source, el, ctx)
);
// Universe entity blocks (#359) — list entities belonging to a universe
const universePeopleProcessor = new UniverseEntitiesProcessor(this, 'people');
this.registerMarkdownCodeBlockProcessor(
'charted-roots-universe-people',
(source, el, ctx) => universePeopleProcessor.process(source, el, ctx)
);
const universePlacesProcessor = new UniverseEntitiesProcessor(this, 'places');
this.registerMarkdownCodeBlockProcessor(
'charted-roots-universe-places',
(source, el, ctx) => universePlacesProcessor.process(source, el, ctx)
);
const universeEventsProcessor = new UniverseEntitiesProcessor(this, 'events');
this.registerMarkdownCodeBlockProcessor(
'charted-roots-universe-events',
(source, el, ctx) => universeEventsProcessor.process(source, el, ctx)
);
const universeOrgsProcessor = new UniverseEntitiesProcessor(this, 'organizations');
this.registerMarkdownCodeBlockProcessor(
'charted-roots-universe-organizations',
(source, el, ctx) => universeOrgsProcessor.process(source, el, ctx)
);
// Universe maps block (#360) — clickable map thumbnails
const universeMapsProcessor = new UniverseMapsProcessor(this);
this.registerMarkdownCodeBlockProcessor(
'charted-roots-universe-maps',
(source, el, ctx) => universeMapsProcessor.process(source, el, ctx)
);
// Timeline-callout sibling marker — adds `.cr-has-timeline` class to
// any <div> containing a `[data-callout="cr-timeline"]` direct child so
// adjacent-sibling CSS rules can give timelines spacing without :has().
// Replaces two :has()-based rules in styles/timeline-callouts.css that
// the Community automated review's CSS-lint rule flagged for broad
// selector invalidation. The class is idempotent (addClass no-ops when
// already present), so the post-processor can run repeatedly across
// re-renders without accumulating state.
this.registerMarkdownPostProcessor((el) => {
const callouts = el.querySelectorAll('[data-callout="cr-timeline"]');
for (const callout of Array.from(callouts)) {
const parent = callout.parentElement;
if (parent instanceof HTMLDivElement) {
parent.classList.add('cr-has-timeline');
}
}
});
}
// =========================================================================
// Commands and workspace events
// =========================================================================
private registerCommandsAndEvents(): void {
_registerCommandsAndEvents(this);
}
// =========================================================================
// Context menus
// =========================================================================
private registerContextMenus(): void {
registerContextMenus(this);
}
/**
* Initialize bidirectional relationship snapshots for all person notes
* Runs asynchronously after a short delay to avoid blocking plugin startup
*/
private initializeBidirectionalSnapshots() {
const linker = this.getBidirectionalLinker();
// Run after a 1-second delay to not impact plugin load performance.
// Handle is tracked so onunload can cancel it — without the clear,
// the callback can fire against a disposed plugin if the user
// disables Charted Roots within the 1-second window.
this.bidirectionalSnapshotTimer = window.setTimeout(() => {
this.bidirectionalSnapshotTimer = null;
try {
linker.initializeSnapshots();
} catch (error: unknown) {
logger.error('snapshot-init', 'Failed to initialize relationship snapshots', {
error: getErrorMessage(error)
});
}
}, 1000);
}
/**
* Initialize the relationship history service
*/
private async initializeRelationshipHistory() {
if (!this.settings.enableRelationshipHistory) {
return;
}
// Load existing history data
const dataKey = RelationshipHistoryService.getDataKey();
const savedData = await this.loadData();
const historyData: RelationshipHistoryData | null = savedData?.[dataKey] || null;
// Create save callback
const saveCallback = async (data: RelationshipHistoryData) => {
const allData = await this.loadData() || {};
allData[dataKey] = data;
await this.saveData(allData);
};
this.relationshipHistory = new RelationshipHistoryService(
this.app,
historyData,
saveCallback
);
// Cleanup old entries on startup
if (this.settings.historyRetentionDays > 0) {
await this.relationshipHistory.cleanupOldEntries(this.settings.historyRetentionDays);
}
logger.info('history-init', 'Relationship history service initialized');
}
/**
* Show the relationship history modal
*/
private showRelationshipHistory(personFile?: TFile) {
if (!this.relationshipHistory) {
new Notice('Relationship history is disabled. Enable it in settings.');
return;
}
new RelationshipHistoryModal(this.app, this.relationshipHistory, personFile).open();
}
/**
* Undo the most recent relationship change
*/
private async undoLastRelationshipChange() {
if (!this.relationshipHistory) {
new Notice('Relationship history is disabled. Enable it in settings.');
return;
}
const change = await this.relationshipHistory.undoLastChange();
if (change) {
new Notice(`Undone: ${formatChangeDescription(change)}`);
}
}
/**
* Get the relationship history service (for external use)
*/
getRelationshipHistory(): RelationshipHistoryService | null {
return this.relationshipHistory;
}
/**
* Register event handler for file modifications to auto-sync relationships
* Public to allow settings tab to re-register when settings change
*/
registerFileModificationHandler() {
// Unregister existing handler if present
if (this.fileModifyEventRef) {
this.app.metadataCache.offref(this.fileModifyEventRef);
this.fileModifyEventRef = null;
}
// Register new handler if sync is enabled
if (this.settings.enableBidirectionalSync && this.settings.syncOnFileModify) {
logger.debug('file-watcher', 'Registering file modification handler for bidirectional sync');
this.fileModifyEventRef = this.app.metadataCache.on('changed', async (file: TFile) => {
// Skip if sync is temporarily disabled (e.g., during bulk import)
if (this._syncDisabled) {
return;
}
// Only process markdown files
if (file.extension !== 'md') {
return;
}
// Only process files with cr_id (person notes)
const cache = this.app.metadataCache.getFileCache(file);
if (!cache?.frontmatter?.cr_id) {
return;
}
logger.debug('file-watcher', 'Person note modified, syncing relationships', {
file: file.path
});
// Sync relationships for this file
try {
await this.getBidirectionalLinker().syncRelationships(file);
} catch (error: unknown) {
logger.error('file-watcher', 'Failed to sync relationships on file modify', {
file: file.path,
error: getErrorMessage(error)
});
}
});
this.registerEvent(this.fileModifyEventRef);
}
}
/**
* Register a metadataCache `deleted` handler that removes a deleted
* person's cr_id from all `*_id` relationship fields on other person
* notes (#442). Obsidian rewrites wikilinks on delete; the cr_id
* arrays were left orphaned, leaving downstream consumers (timeline,
* family chart, exports) trying to resolve dead references.
*/
registerFileDeleteHandler() {
if (this.fileDeleteEventRef) {
this.app.metadataCache.offref(this.fileDeleteEventRef);
this.fileDeleteEventRef = null;
}
this.fileDeleteEventRef = this.app.metadataCache.on('deleted', (file, prevCache) => {
if (this._syncDisabled) return;
if (file.extension !== 'md') return;
const deletedCrId = getDeletedPersonCrId(prevCache);
if (!deletedCrId) return;
const aliases = this.settings.propertyAliases || {};
void cleanupPersonReferencesAfterDelete(this.app, deletedCrId, aliases, file.basename)
.then(result => {
if (result.filesUpdated > 0) {
logger.info('person-delete-cleanup',
`Removed ${deletedCrId} from ${result.filesUpdated} note(s) after delete`,
{ deletedCrId, filesUpdated: result.filesUpdated, deletedFile: file.path });
}
})
.catch(error => {
logger.error('person-delete-cleanup',
'Failed to clean up cr_id references after person delete',
{ deletedCrId, error: getErrorMessage(error) });
});
});
this.registerEvent(this.fileDeleteEventRef);
}
/**
* Register a vault `rename` handler that cascades Universe-note rename
* across `universe:` references on people / places / events / organizations
* (#488 Part 2). Obsidian's native wikilink rewrite handles `[[Name]]`
* references automatically; this handler covers the plain-string case
* that the wikilink rewrite doesn't touch.
*/
registerUniverseRenameHandler() {
if (this.universeRenameEventRef) {
this.app.vault.offref(this.universeRenameEventRef);
this.universeRenameEventRef = null;
}
this.universeRenameEventRef = this.app.vault.on('rename', async (file, oldPath) => {
if (this._syncDisabled) return;
if (!(file instanceof TFile) || file.extension !== 'md') return;
const oldBasename = oldPath.split('/').pop()?.replace(/\.md$/, '') ?? '';
const newBasename = file.basename;
if (!oldBasename || oldBasename === newBasename) return;
// The metadata cache is mid-update during the rename event so
// `getFileCache` returns null, and `metadataCache.on('changed')`
// doesn't fire for content-unchanged renames either. Read the
// file directly to detect `cr_type` — `cachedRead` serves the
// in-memory copy without round-tripping the cache (#488 Part 2).
let crType: string | undefined;
try {
const content = await this.app.vault.cachedRead(file);
const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
if (fmMatch) {
const typeMatch = fmMatch[1].match(/^cr_type:\s*["']?([^"'\s]+)/m);
crType = typeMatch?.[1];
}
} catch (error) {
logger.warn('universe-rename-cascade',
'Failed to read renamed file', { path: file.path, error: getErrorMessage(error) });
return;
}
if (crType !== 'universe') return;
const universeService = createUniverseService(this);
void universeService.cascadeUniverseRename(oldBasename, newBasename)
.then(updateCount => {
if (updateCount > 0) {
new Notice(`Updated universe references on ${updateCount} note${updateCount === 1 ? '' : 's'}`);
}
})
.catch(error => {
logger.error('universe-rename-cascade',
'Failed to cascade Universe rename across referencing notes',
{ oldBasename, newBasename, error: getErrorMessage(error) });
});
});
this.registerEvent(this.universeRenameEventRef);
}