-
-
Notifications
You must be signed in to change notification settings - Fork 391
/
ItemManager.ts
1421 lines (1198 loc) · 47.8 KB
/
ItemManager.ts
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 { ContentType } from '@standardnotes/common'
import { assert, naturalSort, removeFromArray, UuidGenerator, Uuids } from '@standardnotes/utils'
import { ItemsKeyMutator, SNItemsKey } from '@standardnotes/encryption'
import { PayloadManager } from '../Payloads/PayloadManager'
import { TagsToFoldersMigrationApplicator } from '../../Migrations/Applicators/TagsToFolders'
import { UuidString } from '../../Types/UuidString'
import * as Models from '@standardnotes/models'
import * as Services from '@standardnotes/services'
import { PayloadManagerChangeData } from '../Payloads'
import { DiagnosticInfo, ItemsClientInterface, ItemRelationshipDirection } from '@standardnotes/services'
import { CollectionSort, DecryptedItemInterface, ItemContent, SmartViewDefaultIconName } from '@standardnotes/models'
type ItemsChangeObserver<I extends Models.DecryptedItemInterface = Models.DecryptedItemInterface> = {
contentType: ContentType[]
callback: Services.ItemManagerChangeObserverCallback<I>
}
/**
* The item manager is backed by the payload manager. It listens for change events from the
* global payload manager, and converts any payloads to items, then propagates those items to
* listeners on the item manager. When the item manager makes a change to an item, it will modify
* items using a mutator, then emit those payloads to the payload manager. The payload manager
* will then notify its observers (which is us), we'll convert the payloads to items,
* and then we'll propagate them to our listeners.
*/
export class ItemManager
extends Services.AbstractService
implements Services.ItemManagerInterface, ItemsClientInterface
{
private unsubChangeObserver: () => void
private observers: ItemsChangeObserver[] = []
private collection!: Models.ItemCollection
private systemSmartViews: Models.SmartView[]
private tagItemsIndex!: Models.TagItemsIndex
private navigationDisplayController!: Models.ItemDisplayController<Models.SNNote | Models.FileItem>
private tagDisplayController!: Models.ItemDisplayController<Models.SNTag>
private itemsKeyDisplayController!: Models.ItemDisplayController<SNItemsKey>
private componentDisplayController!: Models.ItemDisplayController<Models.SNComponent>
private themeDisplayController!: Models.ItemDisplayController<Models.SNTheme>
private fileDisplayController!: Models.ItemDisplayController<Models.FileItem>
private smartViewDisplayController!: Models.ItemDisplayController<Models.SmartView>
constructor(
private payloadManager: PayloadManager,
protected override internalEventBus: Services.InternalEventBusInterface,
) {
super(internalEventBus)
this.payloadManager = payloadManager
this.systemSmartViews = this.rebuildSystemSmartViews({})
this.createCollection()
this.unsubChangeObserver = this.payloadManager.addObserver(ContentType.Any, this.setPayloads.bind(this))
}
private rebuildSystemSmartViews(criteria: Models.FilterDisplayOptions): Models.SmartView[] {
this.systemSmartViews = Models.BuildSmartViews(criteria)
return this.systemSmartViews
}
private createCollection() {
this.collection = new Models.ItemCollection()
this.navigationDisplayController = new Models.ItemDisplayController(
this.collection,
[ContentType.Note, ContentType.File],
{
sortBy: 'created_at',
sortDirection: 'dsc',
hiddenContentTypes: [],
},
)
this.tagDisplayController = new Models.ItemDisplayController(this.collection, [ContentType.Tag], {
sortBy: 'title',
sortDirection: 'asc',
})
this.itemsKeyDisplayController = new Models.ItemDisplayController(this.collection, [ContentType.ItemsKey], {
sortBy: 'created_at',
sortDirection: 'asc',
})
this.componentDisplayController = new Models.ItemDisplayController(this.collection, [ContentType.Component], {
sortBy: 'created_at',
sortDirection: 'asc',
})
this.themeDisplayController = new Models.ItemDisplayController(this.collection, [ContentType.Theme], {
sortBy: 'title',
sortDirection: 'asc',
})
this.smartViewDisplayController = new Models.ItemDisplayController(this.collection, [ContentType.SmartView], {
sortBy: 'title',
sortDirection: 'asc',
})
this.fileDisplayController = new Models.ItemDisplayController(this.collection, [ContentType.File], {
sortBy: 'title',
sortDirection: 'asc',
})
this.tagItemsIndex = new Models.TagItemsIndex(this.collection, this.tagItemsIndex?.observers)
}
private get allDisplayControllers(): Models.ItemDisplayController<Models.DisplayItem>[] {
return [
this.navigationDisplayController,
this.tagDisplayController,
this.itemsKeyDisplayController,
this.componentDisplayController,
this.themeDisplayController,
this.smartViewDisplayController,
this.fileDisplayController,
]
}
get invalidItems(): Models.EncryptedItemInterface[] {
return this.collection.invalidElements()
}
public createItemFromPayload(payload: Models.DecryptedPayloadInterface): Models.DecryptedItemInterface {
return Models.CreateDecryptedItemFromPayload(payload)
}
public createPayloadFromObject(object: Models.DecryptedTransferPayload): Models.DecryptedPayloadInterface {
return new Models.DecryptedPayload(object)
}
public setPrimaryItemDisplayOptions(options: Models.DisplayOptions): void {
const override: Models.FilterDisplayOptions = {}
const additionalFilters: Models.ItemFilter[] = []
if (options.views && options.views.find((view) => view.uuid === Models.SystemViewId.AllNotes)) {
if (options.includeArchived === undefined) {
override.includeArchived = false
}
if (options.includeTrashed === undefined) {
override.includeTrashed = false
}
}
if (options.views && options.views.find((view) => view.uuid === Models.SystemViewId.ArchivedNotes)) {
if (options.includeTrashed === undefined) {
override.includeTrashed = false
}
}
if (options.views && options.views.find((view) => view.uuid === Models.SystemViewId.TrashedNotes)) {
if (!options.includeArchived) {
override.includeArchived = true
}
}
if (options.views && options.views.find((view) => view.uuid === Models.SystemViewId.Conflicts)) {
additionalFilters.push((item) => this.collection.conflictsOf(item.uuid).length > 0)
}
this.rebuildSystemSmartViews({ ...options, ...override })
const mostRecentVersionOfTags = options.tags
?.map((tag) => {
return this.collection.find(tag.uuid) as Models.SNTag
})
.filter((tag) => tag != undefined)
const mostRecentVersionOfViews = options.views
?.map((view) => {
if (Models.isSystemView(view)) {
return this.systemSmartViews.find((systemView) => systemView.uuid === view.uuid) as Models.SmartView
}
return this.collection.find(view.uuid) as Models.SmartView
})
.filter((view) => view != undefined)
const updatedOptions: Models.DisplayOptions = {
...options,
...override,
...{
tags: mostRecentVersionOfTags,
views: mostRecentVersionOfViews,
},
}
if (updatedOptions.sortBy === CollectionSort.Title) {
updatedOptions.sortDirection = updatedOptions.sortDirection === 'asc' ? 'dsc' : 'asc'
}
this.navigationDisplayController.setDisplayOptions({
customFilter: Models.computeUnifiedFilterForDisplayOptions(updatedOptions, this.collection, additionalFilters),
...updatedOptions,
})
}
public getDisplayableNotes(): Models.SNNote[] {
assert(this.navigationDisplayController.contentTypes.length === 2)
return this.navigationDisplayController.items().filter(Models.isNote)
}
public getDisplayableFiles(): Models.FileItem[] {
return this.fileDisplayController.items()
}
public getDisplayableNotesAndFiles(): (Models.SNNote | Models.FileItem)[] {
return this.navigationDisplayController.items()
}
public getDisplayableTags(): Models.SNTag[] {
return this.tagDisplayController.items()
}
public getDisplayableItemsKeys(): SNItemsKey[] {
return this.itemsKeyDisplayController.items()
}
public getDisplayableComponents(): (Models.SNComponent | Models.SNTheme)[] {
return [...this.componentDisplayController.items(), ...this.themeDisplayController.items()]
}
public override deinit(): void {
this.unsubChangeObserver()
;(this.unsubChangeObserver as unknown) = undefined
;(this.payloadManager as unknown) = undefined
;(this.collection as unknown) = undefined
;(this.tagItemsIndex as unknown) = undefined
;(this.tagDisplayController as unknown) = undefined
;(this.navigationDisplayController as unknown) = undefined
;(this.itemsKeyDisplayController as unknown) = undefined
;(this.componentDisplayController as unknown) = undefined
;(this.themeDisplayController as unknown) = undefined
;(this.fileDisplayController as unknown) = undefined
;(this.smartViewDisplayController as unknown) = undefined
}
resetState(): void {
this.createCollection()
}
findItem<T extends Models.DecryptedItemInterface = Models.DecryptedItemInterface>(uuid: UuidString): T | undefined {
const itemFromCollection = this.collection.findDecrypted<T>(uuid)
return itemFromCollection || (this.findSystemSmartView(uuid) as T | undefined)
}
findAnyItem(uuid: UuidString): Models.ItemInterface | undefined {
const itemFromCollection = this.collection.find(uuid)
return itemFromCollection || this.findSystemSmartView(uuid)
}
findAnyItems(uuids: UuidString[]): Models.ItemInterface[] {
return this.collection.findAll(uuids)
}
private findSystemSmartView(uuid: string): Models.SmartView | undefined {
return this.systemSmartViews.find((view) => view.uuid === uuid)
}
findSureItem<T extends Models.DecryptedItemInterface = Models.DecryptedItemInterface>(uuid: UuidString): T {
return this.findItem(uuid) as T
}
/**
* Returns all items matching given ids
*/
findItems<T extends Models.DecryptedItemInterface>(uuids: UuidString[]): T[] {
return this.collection.findAllDecrypted(uuids) as T[]
}
/**
* If item is not found, an `undefined` element
* will be inserted into the array.
*/
findItemsIncludingBlanks<T extends Models.DecryptedItemInterface>(uuids: UuidString[]): (T | undefined)[] {
return this.collection.findAllDecryptedWithBlanks(uuids) as (T | undefined)[]
}
public get items(): Models.DecryptedItemInterface[] {
return this.collection.nondeletedElements().filter(Models.isDecryptedItem)
}
allTrackedItems(): Models.ItemInterface[] {
return this.collection.all()
}
public hasTagsNeedingFoldersMigration(): boolean {
return TagsToFoldersMigrationApplicator.isApplicableToCurrentData(this)
}
public addNoteCountChangeObserver(observer: Models.TagItemCountChangeObserver): () => void {
return this.tagItemsIndex.addCountChangeObserver(observer)
}
public allCountableNotesCount(): number {
return this.tagItemsIndex.allCountableNotesCount()
}
public allCountableFilesCount(): number {
return this.tagItemsIndex.allCountableFilesCount()
}
public countableNotesForTag(tag: Models.SNTag | Models.SmartView): number {
if (tag instanceof Models.SmartView) {
if (tag.uuid === Models.SystemViewId.AllNotes) {
return this.tagItemsIndex.allCountableNotesCount()
}
throw Error('countableItemsForTag is not meant to be used for smart views.')
}
return this.tagItemsIndex.countableItemsForTag(tag)
}
public getNoteCount(): number {
return this.noteCount
}
public addObserver<I extends Models.DecryptedItemInterface = Models.DecryptedItemInterface>(
contentType: ContentType | ContentType[],
callback: Services.ItemManagerChangeObserverCallback<I>,
): () => void {
if (!Array.isArray(contentType)) {
contentType = [contentType]
}
const observer: ItemsChangeObserver<I> = {
contentType,
callback,
}
this.observers.push(observer as ItemsChangeObserver)
const thislessObservers = this.observers
return () => {
removeFromArray(thislessObservers, observer)
}
}
/**
* Returns the items that reference the given item, or an empty array if no results.
*/
public itemsReferencingItem(
itemToLookupUuidFor: Models.DecryptedItemInterface,
contentType?: ContentType,
): Models.DecryptedItemInterface[] {
const uuids = this.collection.uuidsThatReferenceUuid(itemToLookupUuidFor.uuid)
let referencing = this.findItems(uuids)
if (contentType) {
referencing = referencing.filter((ref) => {
return ref?.content_type === contentType
})
}
return referencing
}
/**
* Returns all items that an item directly references
*/
public referencesForItem<I extends Models.DecryptedItemInterface = Models.DecryptedItemInterface>(
itemToLookupUuidFor: Models.DecryptedItemInterface,
contentType?: ContentType,
): I[] {
const item = this.findSureItem<I>(itemToLookupUuidFor.uuid)
const uuids = item.references.map((ref) => ref.uuid)
let references = this.findItems<I>(uuids)
if (contentType) {
references = references.filter((ref) => {
return ref?.content_type === contentType
})
}
return references
}
private setPayloads(data: PayloadManagerChangeData) {
const { changed, inserted, discarded, ignored, unerrored, source, sourceKey } = data
const createItem = (payload: Models.FullyFormedPayloadInterface) => {
return Models.CreateItemFromPayload(payload)
}
const affectedContentTypes = new Set<ContentType>()
const changedItems = changed.map((p) => {
affectedContentTypes.add(p.content_type)
return createItem(p)
})
const insertedItems = inserted.map((p) => {
affectedContentTypes.add(p.content_type)
return createItem(p)
})
const discardedItems: Models.DeletedItemInterface[] = discarded.map((p) => {
affectedContentTypes.add(p.content_type)
return new Models.DeletedItem(p)
})
const ignoredItems: Models.EncryptedItemInterface[] = ignored.map((p) => {
affectedContentTypes.add(p.content_type)
return new Models.EncryptedItem(p)
})
const unerroredItems = unerrored.map((p) => {
affectedContentTypes.add(p.content_type)
return Models.CreateDecryptedItemFromPayload(p)
})
const delta: Models.ItemDelta = {
changed: changedItems,
inserted: insertedItems,
discarded: discardedItems,
ignored: ignoredItems,
unerrored: unerroredItems,
}
this.collection.onChange(delta)
this.tagItemsIndex.onChange(delta)
const affectedContentTypesArray = Array.from(affectedContentTypes.values())
for (const controller of this.allDisplayControllers) {
if (controller.contentTypes.some((ct) => affectedContentTypesArray.includes(ct))) {
controller.onCollectionChange(delta)
}
}
this.notifyObserversByUiAdjustingDelta(delta, source, sourceKey)
}
private notifyObserversByUiAdjustingDelta(
delta: Models.ItemDelta,
source: Models.PayloadEmitSource,
sourceKey?: string,
) {
const changedItems: Models.DecryptedItemInterface[] = []
const insertedItems: Models.DecryptedItemInterface[] = []
const changedDeleted: Models.DeletedItemInterface[] = []
const insertedDeleted: Models.DeletedItemInterface[] = []
const changedToEncrypted: Models.EncryptedItemInterface[] = []
for (const item of delta.changed) {
if (Models.isDeletedItem(item)) {
changedDeleted.push(item)
} else if (Models.isDecryptedItem(item)) {
changedItems.push(item)
} else {
changedToEncrypted.push(item)
}
}
for (const item of delta.inserted) {
if (Models.isDeletedItem(item)) {
insertedDeleted.push(item)
} else if (Models.isDecryptedItem(item)) {
insertedItems.push(item)
}
}
const itemsToRemoveFromUI: (Models.DeletedItemInterface | Models.EncryptedItemInterface)[] = [
...delta.discarded,
...changedDeleted,
...insertedDeleted,
...changedToEncrypted,
]
this.notifyObservers(
changedItems,
insertedItems,
itemsToRemoveFromUI,
delta.ignored,
delta.unerrored,
source,
sourceKey,
)
}
private notifyObservers(
changed: Models.DecryptedItemInterface[],
inserted: Models.DecryptedItemInterface[],
removed: (Models.DeletedItemInterface | Models.EncryptedItemInterface)[],
ignored: Models.EncryptedItemInterface[],
unerrored: Models.DecryptedItemInterface[],
source: Models.PayloadEmitSource,
sourceKey?: string,
) {
const filter = <I extends Models.ItemInterface>(items: I[], types: ContentType[]) => {
return items.filter((item) => {
return types.includes(ContentType.Any) || types.includes(item.content_type)
})
}
const frozenObservers = this.observers.slice()
for (const observer of frozenObservers) {
const filteredChanged = filter(changed, observer.contentType)
const filteredInserted = filter(inserted, observer.contentType)
const filteredDiscarded = filter(removed, observer.contentType)
const filteredIgnored = filter(ignored, observer.contentType)
const filteredUnerrored = filter(unerrored, observer.contentType)
if (
filteredChanged.length === 0 &&
filteredInserted.length === 0 &&
filteredDiscarded.length === 0 &&
filteredIgnored.length === 0 &&
filteredUnerrored.length === 0
) {
continue
}
observer.callback({
changed: filteredChanged,
inserted: filteredInserted,
removed: filteredDiscarded,
ignored: filteredIgnored,
unerrored: filteredUnerrored,
source,
sourceKey,
})
}
}
/**
* Consumers wanting to modify an item should run it through this block,
* so that data is properly mapped through our function, and latest state
* is properly reconciled.
*/
public async changeItem<
M extends Models.DecryptedItemMutator = Models.DecryptedItemMutator,
I extends Models.DecryptedItemInterface = Models.DecryptedItemInterface,
>(
itemToLookupUuidFor: I,
mutate?: (mutator: M) => void,
mutationType: Models.MutationType = Models.MutationType.UpdateUserTimestamps,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<I> {
const results = await this.changeItems<M, I>(
[itemToLookupUuidFor],
mutate,
mutationType,
emitSource,
payloadSourceKey,
)
return results[0]
}
/**
* @param mutate If not supplied, the intention would simply be to mark the item as dirty.
*/
public async changeItems<
M extends Models.DecryptedItemMutator = Models.DecryptedItemMutator,
I extends Models.DecryptedItemInterface = Models.DecryptedItemInterface,
>(
itemsToLookupUuidsFor: I[],
mutate?: (mutator: M) => void,
mutationType: Models.MutationType = Models.MutationType.UpdateUserTimestamps,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<I[]> {
const items = this.findItemsIncludingBlanks(Uuids(itemsToLookupUuidsFor))
const payloads: Models.DecryptedPayloadInterface[] = []
for (const item of items) {
if (!item) {
throw Error('Attempting to change non-existant item')
}
const mutator = Models.CreateDecryptedMutatorForItem(item, mutationType)
if (mutate) {
mutate(mutator as M)
}
const payload = mutator.getResult()
payloads.push(payload)
}
await this.payloadManager.emitPayloads(payloads, emitSource, payloadSourceKey)
const results = this.findItems(payloads.map((p) => p.uuid)) as I[]
return results
}
/**
* Run unique mutations per each item in the array, then only propagate all changes
* once all mutations have been run. This differs from `changeItems` in that changeItems
* runs the same mutation on all items.
*/
public async runTransactionalMutations(
transactions: Models.TransactionalMutation[],
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<(Models.DecryptedItemInterface | undefined)[]> {
const payloads: Models.DecryptedPayloadInterface[] = []
for (const transaction of transactions) {
const item = this.findItem(transaction.itemUuid)
if (!item) {
continue
}
const mutator = Models.CreateDecryptedMutatorForItem(
item,
transaction.mutationType || Models.MutationType.UpdateUserTimestamps,
)
transaction.mutate(mutator)
const payload = mutator.getResult()
payloads.push(payload)
}
await this.payloadManager.emitPayloads(payloads, emitSource, payloadSourceKey)
const results = this.findItems(payloads.map((p) => p.uuid))
return results
}
public async runTransactionalMutation(
transaction: Models.TransactionalMutation,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<Models.DecryptedItemInterface | undefined> {
const item = this.findSureItem(transaction.itemUuid)
const mutator = Models.CreateDecryptedMutatorForItem(
item,
transaction.mutationType || Models.MutationType.UpdateUserTimestamps,
)
transaction.mutate(mutator)
const payload = mutator.getResult()
await this.payloadManager.emitPayloads([payload], emitSource, payloadSourceKey)
const result = this.findItem(payload.uuid)
return result
}
async changeNote(
itemToLookupUuidFor: Models.SNNote,
mutate: (mutator: Models.NoteMutator) => void,
mutationType: Models.MutationType = Models.MutationType.UpdateUserTimestamps,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<Models.DecryptedPayloadInterface[]> {
const note = this.findItem<Models.SNNote>(itemToLookupUuidFor.uuid)
if (!note) {
throw Error('Attempting to change non-existant note')
}
const mutator = new Models.NoteMutator(note, mutationType)
return this.applyTransform(mutator, mutate, emitSource, payloadSourceKey)
}
async changeTag(
itemToLookupUuidFor: Models.SNTag,
mutate: (mutator: Models.TagMutator) => void,
mutationType: Models.MutationType = Models.MutationType.UpdateUserTimestamps,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<Models.SNTag> {
const tag = this.findItem<Models.SNTag>(itemToLookupUuidFor.uuid)
if (!tag) {
throw Error('Attempting to change non-existant tag')
}
const mutator = new Models.TagMutator(tag, mutationType)
await this.applyTransform(mutator, mutate, emitSource, payloadSourceKey)
return this.findSureItem<Models.SNTag>(itemToLookupUuidFor.uuid)
}
async changeComponent(
itemToLookupUuidFor: Models.SNComponent,
mutate: (mutator: Models.ComponentMutator) => void,
mutationType: Models.MutationType = Models.MutationType.UpdateUserTimestamps,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<Models.SNComponent> {
const component = this.findItem<Models.SNComponent>(itemToLookupUuidFor.uuid)
if (!component) {
throw Error('Attempting to change non-existant component')
}
const mutator = new Models.ComponentMutator(component, mutationType)
await this.applyTransform(mutator, mutate, emitSource, payloadSourceKey)
return this.findSureItem<Models.SNComponent>(itemToLookupUuidFor.uuid)
}
async changeFeatureRepo(
itemToLookupUuidFor: Models.SNFeatureRepo,
mutate: (mutator: Models.FeatureRepoMutator) => void,
mutationType: Models.MutationType = Models.MutationType.UpdateUserTimestamps,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<Models.SNFeatureRepo> {
const repo = this.findItem(itemToLookupUuidFor.uuid)
if (!repo) {
throw Error('Attempting to change non-existant repo')
}
const mutator = new Models.FeatureRepoMutator(repo, mutationType)
await this.applyTransform(mutator, mutate, emitSource, payloadSourceKey)
return this.findSureItem<Models.SNFeatureRepo>(itemToLookupUuidFor.uuid)
}
async changeActionsExtension(
itemToLookupUuidFor: Models.SNActionsExtension,
mutate: (mutator: Models.ActionsExtensionMutator) => void,
mutationType: Models.MutationType = Models.MutationType.UpdateUserTimestamps,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<Models.SNActionsExtension> {
const extension = this.findItem<Models.SNActionsExtension>(itemToLookupUuidFor.uuid)
if (!extension) {
throw Error('Attempting to change non-existant extension')
}
const mutator = new Models.ActionsExtensionMutator(extension, mutationType)
await this.applyTransform(mutator, mutate, emitSource, payloadSourceKey)
return this.findSureItem<Models.SNActionsExtension>(itemToLookupUuidFor.uuid)
}
async changeItemsKey(
itemToLookupUuidFor: Models.ItemsKeyInterface,
mutate: (mutator: Models.ItemsKeyMutatorInterface) => void,
mutationType: Models.MutationType = Models.MutationType.UpdateUserTimestamps,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<Models.ItemsKeyInterface> {
const itemsKey = this.findItem<SNItemsKey>(itemToLookupUuidFor.uuid)
if (!itemsKey) {
throw Error('Attempting to change non-existant itemsKey')
}
const mutator = new ItemsKeyMutator(itemsKey, mutationType)
await this.applyTransform(mutator, mutate, emitSource, payloadSourceKey)
return this.findSureItem<Models.ItemsKeyInterface>(itemToLookupUuidFor.uuid)
}
private async applyTransform<T extends Models.DecryptedItemMutator>(
mutator: T,
mutate: (mutator: T) => void,
emitSource = Models.PayloadEmitSource.LocalChanged,
payloadSourceKey?: string,
): Promise<Models.DecryptedPayloadInterface[]> {
mutate(mutator)
const payload = mutator.getResult()
return this.payloadManager.emitPayload(payload, emitSource, payloadSourceKey)
}
/**
* Sets the item as needing sync. The item is then run through the mapping function,
* and propagated to mapping observers.
* @param isUserModified - Whether to update the item's "user modified date"
*/
public async setItemDirty(itemToLookupUuidFor: Models.DecryptedItemInterface, isUserModified = false) {
const result = await this.setItemsDirty([itemToLookupUuidFor], isUserModified)
return result[0]
}
public async setItemsDirty(
itemsToLookupUuidsFor: Models.DecryptedItemInterface[],
isUserModified = false,
): Promise<Models.DecryptedItemInterface[]> {
return this.changeItems(
itemsToLookupUuidsFor,
undefined,
isUserModified ? Models.MutationType.UpdateUserTimestamps : Models.MutationType.NoUpdateUserTimestamps,
)
}
/**
* Returns an array of items that need to be synced.
*/
public getDirtyItems(): (Models.DecryptedItemInterface | Models.DeletedItemInterface)[] {
return this.collection.dirtyElements().filter(Models.isDecryptedOrDeletedItem)
}
/**
* Duplicates an item and maps it, thus propagating the item to observers.
* @param isConflict - Whether to mark the duplicate as a conflict of the original.
*/
public async duplicateItem<T extends Models.DecryptedItemInterface>(
itemToLookupUuidFor: T,
isConflict = false,
additionalContent?: Partial<Models.ItemContent>,
) {
const item = this.findSureItem(itemToLookupUuidFor.uuid)
const payload = item.payload.copy()
const resultingPayloads = Models.PayloadsByDuplicating({
payload,
baseCollection: this.payloadManager.getMasterCollection(),
isConflict,
additionalContent,
})
await this.payloadManager.emitPayloads(resultingPayloads, Models.PayloadEmitSource.LocalChanged)
const duplicate = this.findSureItem<T>(resultingPayloads[0].uuid)
return duplicate
}
public async createItem<T extends Models.DecryptedItemInterface, C extends Models.ItemContent = Models.ItemContent>(
contentType: ContentType,
content: C,
needsSync = false,
): Promise<T> {
const payload = new Models.DecryptedPayload<C>({
uuid: UuidGenerator.GenerateUuid(),
content_type: contentType,
content: Models.FillItemContent<C>(content),
dirty: needsSync,
...Models.PayloadTimestampDefaults(),
})
await this.payloadManager.emitPayload(payload, Models.PayloadEmitSource.LocalInserted)
return this.findSureItem<T>(payload.uuid)
}
public createTemplateItem<
C extends Models.ItemContent = Models.ItemContent,
I extends Models.DecryptedItemInterface<C> = Models.DecryptedItemInterface<C>,
>(contentType: ContentType, content?: C, override?: Partial<Models.DecryptedPayload<C>>): I {
const payload = new Models.DecryptedPayload<C>({
uuid: UuidGenerator.GenerateUuid(),
content_type: contentType,
content: Models.FillItemContent<C>(content || {}),
...Models.PayloadTimestampDefaults(),
...override,
})
const item = Models.CreateDecryptedItemFromPayload<C, I>(payload)
return item
}
/**
* @param item item to be checked
* @returns Whether the item is a template (unmanaged)
*/
public isTemplateItem(item: Models.DecryptedItemInterface): boolean {
return !this.findItem(item.uuid)
}
public async insertItem(item: Models.DecryptedItemInterface): Promise<Models.DecryptedItemInterface> {
return this.emitItemFromPayload(item.payload, Models.PayloadEmitSource.LocalChanged)
}
public async insertItems(
items: Models.DecryptedItemInterface[],
emitSource: Models.PayloadEmitSource = Models.PayloadEmitSource.LocalInserted,
): Promise<Models.DecryptedItemInterface[]> {
return this.emitItemsFromPayloads(
items.map((item) => item.payload),
emitSource,
)
}
public async emitItemFromPayload(
payload: Models.DecryptedPayloadInterface,
emitSource: Models.PayloadEmitSource,
): Promise<Models.DecryptedItemInterface> {
await this.payloadManager.emitPayload(payload, emitSource)
return this.findSureItem(payload.uuid)
}
public async emitItemsFromPayloads(
payloads: Models.DecryptedPayloadInterface[],
emitSource: Models.PayloadEmitSource,
): Promise<Models.DecryptedItemInterface[]> {
await this.payloadManager.emitPayloads(payloads, emitSource)
const uuids = Uuids(payloads)
return this.findItems(uuids)
}
public async setItemToBeDeleted(
itemToLookupUuidFor: Models.DecryptedItemInterface | Models.EncryptedItemInterface,
source: Models.PayloadEmitSource = Models.PayloadEmitSource.LocalChanged,
): Promise<void> {
const referencingIdsCapturedBeforeChanges = this.collection.uuidsThatReferenceUuid(itemToLookupUuidFor.uuid)
const item = this.findAnyItem(itemToLookupUuidFor.uuid)
if (!item) {
return
}
const mutator = new Models.DeleteItemMutator(item, Models.MutationType.UpdateUserTimestamps)
const deletedPayload = mutator.getDeletedResult()
await this.payloadManager.emitPayload(deletedPayload, source)
for (const referencingId of referencingIdsCapturedBeforeChanges) {
const referencingItem = this.findItem(referencingId)
if (referencingItem) {
await this.changeItem(referencingItem, (mutator) => {
mutator.removeItemAsRelationship(item)
})
}
}
}
public async setItemsToBeDeleted(
itemsToLookupUuidsFor: (Models.DecryptedItemInterface | Models.EncryptedItemInterface)[],
): Promise<void> {
await Promise.all(itemsToLookupUuidsFor.map((item) => this.setItemToBeDeleted(item)))
}
public getItems<T extends Models.DecryptedItemInterface>(contentType: ContentType | ContentType[]): T[] {
return this.collection.allDecrypted<T>(contentType)
}
getAnyItems(contentType: ContentType | ContentType[]): Models.ItemInterface[] {
return this.collection.all(contentType)
}
public itemsMatchingPredicate<T extends Models.DecryptedItemInterface>(
contentType: ContentType,
predicate: Models.PredicateInterface<T>,
): T[] {
return this.itemsMatchingPredicates(contentType, [predicate])
}
public itemsMatchingPredicates<T extends Models.DecryptedItemInterface>(
contentType: ContentType,
predicates: Models.PredicateInterface<T>[],
): T[] {
const subItems = this.getItems<T>(contentType)
return this.subItemsMatchingPredicates(subItems, predicates)
}
public subItemsMatchingPredicates<T extends Models.DecryptedItemInterface>(
items: T[],
predicates: Models.PredicateInterface<T>[],
): T[] {
const results = items.filter((item) => {
for (const predicate of predicates) {
if (!item.satisfiesPredicate(predicate)) {
return false
}
}
return true
})
return results
}
public getRootTags(): Models.SNTag[] {
return this.getDisplayableTags().filter((tag) => tag.parentId === undefined)
}
public findTagByTitle(title: string): Models.SNTag | undefined {
const lowerCaseTitle = title.toLowerCase()
return this.getDisplayableTags().find((tag) => tag.title?.toLowerCase() === lowerCaseTitle)
}
public findTagByTitleAndParent(title: string, parentItemToLookupUuidFor?: Models.SNTag): Models.SNTag | undefined {
const lowerCaseTitle = title.toLowerCase()
const tags = parentItemToLookupUuidFor ? this.getTagChildren(parentItemToLookupUuidFor) : this.getRootTags()
return tags.find((tag) => tag.title?.toLowerCase() === lowerCaseTitle)
}
/**
* Finds tags with title or component starting with a search query and (optionally) not associated with a note
* @param searchQuery - The query string to match
* @param note - The note whose tags should be omitted from results
* @returns Array containing tags matching search query and not associated with note
*/
public searchTags(searchQuery: string, note?: Models.SNNote): Models.SNTag[] {
return naturalSort(
this.getDisplayableTags().filter((tag) => {
const expandedTitle = this.getTagLongTitle(tag)
const matchesQuery = expandedTitle.toLowerCase().includes(searchQuery.toLowerCase())
const tagInNote = note ? this.itemsReferencingItem(note).some((item) => item?.uuid === tag.uuid) : false
return matchesQuery && !tagInNote
}),
'title',
)
}
getTagParent(itemToLookupUuidFor: Models.SNTag): Models.SNTag | undefined {
const tag = this.findItem<Models.SNTag>(itemToLookupUuidFor.uuid)
if (!tag) {
return undefined
}
const parentId = tag.parentId
if (parentId) {
return this.findItem(parentId) as Models.SNTag
}
return undefined
}
public getTagPrefixTitle(tag: Models.SNTag): string | undefined {
const hierarchy = this.getTagParentChain(tag)
if (hierarchy.length === 0) {
return undefined
}
const prefixTitle = hierarchy.map((tag) => tag.title).join('/')
return `${prefixTitle}/`
}
public getTagLongTitle(tag: Models.SNTag): string {
const hierarchy = this.getTagParentChain(tag)
const tags = [...hierarchy, tag]
const longTitle = tags.map((tag) => tag.title).join('/')
return longTitle
}
getTagParentChain(itemToLookupUuidFor: Models.SNTag): Models.SNTag[] {