-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathresults.js
More file actions
923 lines (791 loc) · 34.9 KB
/
Copy pathresults.js
File metadata and controls
923 lines (791 loc) · 34.9 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
import angular from 'angular';
import Rx from 'rx';
import moment from 'moment';
import '../services/scroll-position';
import '../services/panel';
import '../util/async';
import '../util/rx';
import '../util/seq';
import '../util/storage';
import '../util/constants/sendToCapture-config';
import '../components/gu-lazy-table/gu-lazy-table';
import '../components/gu-lazy-table-shortcuts/gu-lazy-table-shortcuts';
import '../components/gr-archiver/gr-archiver';
import '../components/gr-delete-image/gr-delete-image';
import '../components/gr-undelete-image/gr-un-delete-image';
import '../components/gr-downloader/gr-downloader';
import '../components/gr-more-like-this/gr-more-like-this';
import '../components/gr-batch-export-original-images/gr-batch-export-original-images';
import '../components/gr-panel-button/gr-panel-button';
import '../components/gr-toggle-button/gr-toggle-button';
import '../components/gr-confirmation-modal/gr-confirmation-modal';
import '../components/gr-sort-control/gr-sort-control';
import '../components/gr-sort-control/gr-extended-sort-control';
import {
manageSortSelection,
DefaultSortOption,
TAKEN_SORT,
HAS_DATE_TAKEN,
HASNT_DATE_TAKEN
} from "../components/gr-sort-control/gr-sort-control-config";
import {
TAB_WITH
} from "../components/gr-tab-swap/gr-tab-swap";
import {
INVALIDIMAGES,
sendToCaptureAllValid, sendToCaptureCancelBtnTxt, sendToCaptureConfirmBtnTxt, sendToCaptureInvalid,
sendToCaptureSuccess, sendToCaptureFailure, announcementId,
sendToCaptureMixed,
sendToCaptureTitle,
VALIDIMAGES
} from "../util/constants/sendToCapture-config";
export var results = angular.module('kahuna.search.results', [
'kahuna.services.scroll-position',
'kahuna.services.panel',
'util.async',
'util.rx',
'util.seq',
'gu.lazyTable',
'gu.lazyTableShortcuts',
'gr.archiver',
'gr.downloader',
'gr.moreLikeThis',
'gr.batchExportOriginalImages',
'gr.deleteImage',
'gr.undeleteImage',
'gr.panelButton',
'gr.toggleButton',
'gr.confirmationModal',
'gr.sortControl',
'gr.extendedSortControl'
]);
function compact(array) {
return array.filter(angular.isDefined);
}
// Global session-level state to remember the uploadTime of the first
// result in the last search. This allows to always paginate the same
// set of results, as well as recovering the same set of results if
// navigating back to the same search.
// Note: I tried to do this using non-URL $stateParams and it was a
// rabbit-hole that doesn't seem to have any end. Hence this slightly
// horrid global state.
let lastSearchFirstResultTime;
results.controller('SearchResultsCtrl', [
'$rootScope',
'$scope',
'$state',
'$stateParams',
'$window',
'$timeout',
'$log',
'$q',
'inject$',
'delay',
'onNextEvent',
'scrollPosition',
'mediaApi',
'selection',
'selectedImages$',
'results',
'panels',
'isReloadingPreviousSearch',
'globalErrors',
'storage',
function($rootScope,
$scope,
$state,
$stateParams,
$window,
$timeout,
$log,
$q,
inject$,
delay,
onNextEvent,
scrollPosition,
mediaApi,
selection,
selectedImages$,
results,
panels,
isReloadingPreviousSearch,
globalErrors,
storage) {
const ctrl = this;
ctrl.$onInit = () => {
ctrl.showSendToPhotoSales = () => $window._clientConfig.showSendToPhotoSales;
ctrl.usePermissionsFilter = () => $window._clientConfig.usePermissionsFilter;
};
// Panel control
ctrl.metadataPanel = panels.metadataPanel;
ctrl.collectionsPanel = panels.collectionsPanel;
//-taken and sort controls-
const hasTakenDateClause = HAS_DATE_TAKEN;
const noTakenDateClause = HASNT_DATE_TAKEN;
const takenSort = TAKEN_SORT;
ctrl.setTakenVisible = (isVisible) => storage.setJs("takenTabVisible", isVisible ? "visible" : "hidden", true);
ctrl.getTakenVisible = () => {
const vis = storage.getJs("takenTabVisible", true) ? storage.getJs("takenTabVisible", true) : "hidden";
return (vis == "visible");
};
ctrl.getCollectionsPanelVisible = () => storage.getJs("collectionsPanelState", false) ? !(storage.getJs("collectionsPanelState", false).hidden) : false;
ctrl.getInfoPanelVisible = () => storage.getJs("metadataPanelState", false) ? !(storage.getJs("metadataPanelState", false).hidden) : false;
ctrl.getLastTakenSort = () => storage.getJs("lastTakenSort", false) ? storage.getJs("lastTakenSort", false) : "";
ctrl.setLastTakenSort = (orderBy) => storage.setJs("lastTakenSort", orderBy, false);
//-sort control select-
function updateSortChange (sortSel, tabSelected, userSelectedTaken) {
var orderBy = manageSortSelection(sortSel.value);
var curQuery = $stateParams.query ? $stateParams.query : '';
ctrl.setTakenVisible(userSelectedTaken);
curQuery = curQuery.replace(noTakenDateClause, "").replace(hasTakenDateClause, "").trim();
if (sortSel.isTaken) {
ctrl.setLastTakenSort(orderBy);
}
if (userSelectedTaken) {
if (tabSelected === TAB_WITH) {
curQuery = `${curQuery} ${hasTakenDateClause}`.trim();
orderBy = ctrl.getLastTakenSort();
} else { // without
curQuery = `${curQuery} ${noTakenDateClause}`.trim();
orderBy = DefaultSortOption.value;
}
}
storage.setJs("orderBy", orderBy);
const toParams = {
...$stateParams,
orderBy: orderBy,
query: curQuery
};
$state.go('search.results', toParams);
}
async function checkForNoTakenDate() {
let tempQuery = $stateParams.query ? $stateParams.query : '';
let isTaken = ($stateParams.orderBy && $stateParams.orderBy.includes(takenSort)) || tempQuery.includes(hasTakenDateClause);
if (!isTaken) { return 0; }
tempQuery = tempQuery.replace(noTakenDateClause, '').replace(hasTakenDateClause, '').trim();
storage.setJs("previousQuery", tempQuery, true);
let query = `${tempQuery} ${noTakenDateClause}`.trim();
var resp = await search({query: query, length: 0});
return resp.total;
};
ctrl.extendedSortProps = {
onSortSelect: updateSortChange,
query: $stateParams.query ? $stateParams.query : "",
orderBy: $stateParams.orderBy ? $stateParams.orderBy : "",
infoPanelVisible: ctrl.getInfoPanelVisible(),
collectionsPanelVisible: ctrl.getCollectionsPanelVisible(),
userTakenSelect: ctrl.getTakenVisible(),
noTakenDateCount: 0
};
checkForNoTakenDate().then(noTakenTotal => {
ctrl.extendedSortProps = { ...ctrl.extendedSortProps,
noTakenDateCount: noTakenTotal
};
});
//-end sort and taken tab controls-
ctrl.images = [];
if (ctrl.image && ctrl.image.data.softDeletedMetadata !== undefined) { ctrl.isDeleted = true; }
ctrl.newImagesCount = 0;
ctrl.newImagesLastCheckedMoment = moment();
ctrl.needsQuery = $stateParams.useAISearch && (!$stateParams.query || !$stateParams.query.trim());
// Map to track image->position and help remove duplicates
let imagesPositions;
// FIXME: This is being refreshed by the router.
// Make it watch a $stateParams collection instead
// See: https://github.com/guardian/media-service/pull/64#discussion-diff-17351746L116
ctrl.loading = true;
ctrl.revealNewImages = revealNewImages;
ctrl.applyFilter = applyFilter;
ctrl.getLastSeenVal = getLastSeenVal;
ctrl.imageHasBeenSeen = imageHasBeenSeen;
// large limit, but still a limit to ensure users don't reach unusable levels of performance
ctrl.maxResults = 100000;
// If not reloading a previous search, discard any previous
// state related to the last search
if (! isReloadingPreviousSearch) {
lastSearchFirstResultTime = undefined;
}
function initialiseSharedResults(images) {
ctrl.totalResults = images.total;
// FIXME: https://github.com/argo-rest/theseus has forced us to co-opt the actions field for this
ctrl.tickerCounts = images.$response?.$$state?.value?.actions?.tickerCounts;
ctrl.hasQuery = !!$stateParams.query;
ctrl.initialSearchUri = images.uri;
ctrl.embeddableUrl = window.location.href;
// images will be the array of loaded images, used for display
ctrl.images = [];
imagesPositions = new Map();
notificationMessages(ctrl.extendedSortProps, ctrl.totalResults);
}
function initialiseAiResults(images) {
const totalLength = images.data.length;
ctrl.imagesAll = new Array(totalLength);
// AI search returns a single fixed result set rather than a paged/lazy-loaded one,
// so we populate the full backing array up front to avoid placeholder rows.
results.clear();
results.resize(totalLength);
images.data.forEach((image, index) => {
ctrl.imagesAll[index] = image;
imagesPositions.set(image.data.id, index);
results.set(index, image);
});
ctrl.images = images.data.slice();
}
function initialisePagedResults(images) {
const totalLength = Math.min(images.total, ctrl.maxResults);
ctrl.imagesAll = [];
ctrl.imagesAll.length = totalLength;
// TODO: ultimately we want to manage the state in the
// results stream exclusively
results.clear();
results.resize(totalLength);
}
function updateLastSearchBoundary() {
const until = $stateParams.until || null;
const latestTime = until || moment().toISOString();
if (latestTime && ! isReloadingPreviousSearch) {
lastSearchFirstResultTime = latestTime;
}
}
function initialiseResults(images, { isAiSearch }) {
initialiseSharedResults(images);
if (isAiSearch) {
initialiseAiResults(images);
} else {
initialisePagedResults(images);
checkForNewImages();
}
updateLastSearchBoundary();
return images;
}
// Initial search to find upper `until` boundary of result set
// (i.e. the uploadTime of the newest result in the set)
// TODO: avoid this initial search (two API calls to init!)
const isAiSearch = !!$stateParams.useAISearch;
const initialSearchParams = isAiSearch
? {offset: 0, length: $window._clientConfig.aiSearchResultLimit}
: {length: 1, orderBy: 'newest'};
ctrl.searched = search(initialSearchParams).then(images =>
initialiseResults(images, { isAiSearch })
).catch(error => {
ctrl.loadingError = error;
return $q.reject(error);
}).finally(() => {
ctrl.loading = false;
});
ctrl.loadRange = function(start, end) {
if ($stateParams.useAISearch) {
return;
}
const length = end - start + 1;
search({offset: start, length: length, countAll: false}).then(images => {
// Update imagesAll with newly loaded images
images.data.forEach((image, index) => {
const position = index + start;
const imageId = image.data.id;
// If image already present in results at a
// different position (result set shifted due to
// items being spliced in or deleted?), get rid of
// item at its previous position to avoid
// duplicates
const existingPosition = imagesPositions.get(imageId);
if (angular.isDefined(existingPosition) &&
existingPosition !== position) {
$log.info(`Detected duplicate image ${imageId}, ` +
`old ${existingPosition}, new ${position}`);
delete ctrl.imagesAll[existingPosition];
results.set(existingPosition, undefined);
}
ctrl.imagesAll[position] = image;
imagesPositions.set(imageId, position);
results.set(position, image);
});
// images should not contain any 'holes'
ctrl.images = compact(ctrl.imagesAll);
});
};
// == Vertical position ==
// Logic to resume vertical position when navigating back to the same results
onNextEvent($scope, 'gu-lazy-table:height-changed').
// Attempt to resume the top position ASAP, so as to limit
// visible jump
then(() => scrollPosition.resume($state.href('search.results', $stateParams))).
// When navigating back, resuming the position immediately
// doesn't work, so we try again after a little while
then(() => delay(30)).
then(() => scrollPosition.resume($state.href('search.results', $stateParams))).
then(scrollPosition.clear);
const pollingPeriod = 15 * 1000; // ms
function notificationMessages(extendedProps, imagesTotal) {
if (!ctrl.usePermissionsFilter()) {
return;
}
if (extendedProps.orderBy.includes(takenSort) && extendedProps.query.includes(hasTakenDateClause)) {
if (imagesTotal === 0 && extendedProps.noTakenDateCount > 0) { // no images with taken date
updateSortChange(DefaultSortOption, 'with', false, extendedProps.noTakenDateCount);
const noMatchesStr = "There are no matching images with a taken date";
const notificationEvent = new CustomEvent("newNotification", {
detail: {
announceId: "noTakenDateImages",
description: noMatchesStr,
category: "information",
lifespan: "transient"
},
bubbles: true
});
window.dispatchEvent(notificationEvent);
} else if (0 < extendedProps.noTakenDateCount) {
const oldNoTakenCount = storage.getJs("lastNoTakenCount", false) ? storage.getJs("lastNoTakenCount", false) : 0;
let imageStr = "There are " + extendedProps.noTakenDateCount.toLocaleString() + " images with no taken date";
if (extendedProps.noTakenDateCount === 1) {
imageStr = "There is one image with no taken date";
}
if (oldNoTakenCount !== extendedProps.noTakenDateCount) {
const notificationEvent = new CustomEvent("newNotification", {
detail: {
announceId: "sortByTakenDate",
description: imageStr,
category: "information",
lifespan: "transient"
},
bubbles: true
});
window.dispatchEvent(notificationEvent);
storage.setJs("lastNoTakenCount", extendedProps.noTakenDateCount, false);
}
} else {
const notificationEvent = new CustomEvent("removeNotification", {
detail: {
announceId: "sortByTakenDate"
},
bubbles: true
});
window.dispatchEvent(notificationEvent);
storage.setJs("lastNoTakenCount", 0, false);
}
}
}
// FIXME: this will only add up to 50 images (search capped)
function checkForNewImages() {
// Polling for new images is meaningless for AI search — results are
// ranked by vector similarity, not upload time.
if ($stateParams.useAISearch) { return; }
$timeout(() => {
// Use explicit `until`, or blank it to find new images
const until = $stateParams.until || null;
const latestTime = lastSearchFirstResultTime;
search({since: latestTime, length: 0, until}).then(resp => {
// FIXME: minor assumption that only the latest
// displayed image is matching the uploadTime
ctrl.newImagesCount = resp.total;
// FIXME: https://github.com/argo-rest/theseus has forced us to co-opt the actions field for this
const newTickerCounts = resp.$response?.$$state?.value?.actions?.tickerCounts;
if (newTickerCounts) {
Object.entries(newTickerCounts).forEach(([key, {value, subCounts}]) => {
const existing = ctrl.tickerCounts[key];
existing.value += value;
if (existing.subCounts && subCounts){
Object.entries(subCounts).forEach(([subKey, subCount]) => {
if (existing.subCounts[subKey]){
existing.subCounts[subKey] += subCount;
} else {
existing.subCounts["other"] += subCount;
}
});
}
});
}
if (ctrl.newImagesCount > 0) {
$rootScope.$emit('events:new-images', { count: ctrl.newImagesCount});
}
ctrl.lastestTimeMoment = moment(latestTime);
ctrl.newImagesLastCheckedMoment = moment();
if (! scopeGone) {
checkForNewImages();
}
});
}, pollingPeriod);
}
function revealNewImages() {
// FIXME: should ideally be able to just call $state.reload(),
// but there seems to be a bug (alluded to in the docs) when
// notify is false, so forcing to true explicitly instead:
$window.scrollTo(0,0);
$state.transitionTo($state.current, $stateParams, {
reload: true, inherit: false, notify: true
});
}
ctrl.maybeOrgOwnedValue = window._clientConfig.maybeOrgOwnedValue;
function applyFilter(searchClause) {
$window.scrollTo(0,0);
const toParams = $stateParams.query?.includes(searchClause)
? $stateParams
: {
...$stateParams,
query: $stateParams.query
? `${$stateParams.query} ${searchClause}`
: searchClause
};
$state.transitionTo(
$state.current,
toParams,
{ reload: true, inherit: false, notify: true }
);
}
var seenSince;
const lastSeenKey = 'search.seenFrom';
function getLastSeenVal(image) {
const key = getQueryKey();
var val = {};
val[key] = image.data.uploadTime;
// Tracking to potentially kill this feature off
$rootScope.$emit('track:event', 'Mark as seen', 'Clicked', null, null, {image: image});
return val;
}
function imageHasBeenSeen(image) {
return image.data.uploadTime <= seenSince;
}
$scope.$watch(() => $window.localStorage.getItem(lastSeenKey), function() {
seenSince = getSeenSince();
});
// TODO: Move this into localstore service
function getSeenSince() {
return JSON.parse($window.localStorage.getItem(lastSeenKey) || '{}')[getQueryKey()];
}
function getQueryKey() {
return $stateParams.query || '*';
}
function search({query, until, since, offset, length, orderBy, countAll} = {}) {
// FIXME: Think of a way to not have to add a param in a million places to add it
/*
* @param `until` can have three values:
*
* - `null` => Don't send over a date, which will default to `now()` on the server.
* Used in `checkForNewImages` with no until in `stateParams` to search
* for the new image count
*
* - `string` => Override the use of `stateParams` or `lastSearchFirstResultTime`.
* Used in `checkForNewImages` when a `stateParams.until` is set.
*
* - `undefined` => Default. We then use the `lastSearchFirstResultTime` if available to
* make sure we aren't loading any new images into the result set and
* `checkForNewImages` deals with that. If it's the first search, we
* will use `stateParams.until` if available.
*/
if (angular.isUndefined(query)) {
query = $stateParams.query;
}
if (angular.isUndefined(until)) {
until = lastSearchFirstResultTime || $stateParams.until;
}
if (angular.isUndefined(since)) {
since = $stateParams.since;
}
if (angular.isUndefined(orderBy)) {
orderBy = $stateParams.orderBy;
}
if (angular.isUndefined(countAll)) {
countAll = true;
}
return mediaApi.search(query, angular.extend({
ids: $stateParams.ids,
archived: $stateParams.archived,
free: $stateParams.nonFree === 'true' ? undefined : true,
// Disabled while paytype filter unavailable
//payType: $stateParams.payType || 'free',
uploadedBy: $stateParams.uploadedBy,
takenSince: $stateParams.takenSince,
takenUntil: $stateParams.takenUntil,
modifiedSince: $stateParams.modifiedSince,
modifiedUntil: $stateParams.modifiedUntil,
until: until,
since: since,
offset: offset,
length: length,
orderBy: orderBy,
useAISearch: $stateParams.useAISearch,
vecWeight: $stateParams.vecWeight,
hasRightsAcquired: $stateParams.hasRightsAcquired,
hasCrops: $stateParams.hasCrops,
syndicationStatus: $stateParams.syndicationStatus,
persisted: $stateParams.persisted,
countAll
}));
}
ctrl.clearSelection = () => {
selection.clear();
};
ctrl.shareSelection = () => {
const sharedImagesIds = ctrl.selectedImages.map(image => image.data.id);
const sharedUrl = $window._clientConfig.rootUri + "/search?nonFree=true&ids=" + sharedImagesIds.join(',');
navigator.clipboard.writeText(sharedUrl);
globalErrors.trigger('clipboard', sharedUrl);
};
const imageHasSyndicationUsage = (image) => {
return image.data.usages.data.some(usage =>
usage.data.platform === 'syndication'
);
};
const validatePhotoSalesSelection = (images) => {
const validImages = [];
const invalidImages = [];
images.forEach(image => {
if (image.data.uploadedBy === 'Capture_AutoIngest' || imageHasSyndicationUsage(image)) {
invalidImages.push(image);
} else {
validImages.push(image);
}
});
return [validImages, invalidImages];
};
ctrl.showPaid = undefined;
mediaApi.getSession().then(session => {
ctrl.showPaid = session.user.permissions.showPaid ? session.user.permissions.showPaid : undefined;
});
ctrl.sendToPhotoSales = () => {
try {
const validImages = validatePhotoSalesSelection(ctrl.selectedImages)[0];
validImages.map(image => {
mediaApi.syndicateImage(image.data.id, "Capture", "true");
});
ctrl.clearSelection();
const notificationEvent = new CustomEvent("newNotification", {
detail: {
announceId: announcementId,
description: sendToCaptureSuccess,
category: "success",
lifespan: "transient"
},
bubbles: true
});
window.dispatchEvent(notificationEvent);
} catch (err) {
console.log(err);
const notificationEvent = new CustomEvent("newNotification", {
detail: {
announceId: announcementId,
description: sendToCaptureFailure,
category: "error",
lifespan: "transient"
},
bubbles: true
});
window.dispatchEvent(notificationEvent);
}
};
ctrl.displayConfirmationModal = () => {
const [validImages, invalidImages] = validatePhotoSalesSelection(ctrl.selectedImages);
const title = sendToCaptureTitle;
let eventType;
let detailObj;
if (validImages.length !== 0 && invalidImages.length === 0) {
// All images selected are valid
eventType = "displayModal";
detailObj = {
title: title,
message: sendToCaptureAllValid,
cancelBtnTxt: sendToCaptureCancelBtnTxt,
confirmBtnTxt: sendToCaptureConfirmBtnTxt,
okayFn: ctrl.sendToPhotoSales
};
} else if (validImages.length !== 0 && invalidImages.length !== 0) {
// Some valid images, some invalid images selected
eventType = "displayModal";
detailObj = {
title: title,
message: sendToCaptureMixed.replace(VALIDIMAGES, validImages.length.toString()).replace(INVALIDIMAGES, invalidImages.length.toString()),
cancelBtnTxt: sendToCaptureCancelBtnTxt,
confirmBtnTxt: sendToCaptureConfirmBtnTxt,
okayFn: ctrl.sendToPhotoSales
};
} else if (validImages.length === 0 && invalidImages.length !== 0) {
// No valid images selected
eventType = "newNotification";
detailObj = {
announceId: announcementId,
description: sendToCaptureInvalid,
category: "warning",
lifespan: "transient"
};
}
const customEvent = new CustomEvent(eventType, {
detail: detailObj,
bubbles: true
});
window.dispatchEvent(customEvent);
};
const inSelectionMode$ = selection.isEmpty$.map(isEmpty => ! isEmpty);
inject$($scope, inSelectionMode$, ctrl, 'inSelectionMode');
inject$($scope, selection.count$, ctrl, 'selectionCount');
inject$($scope, selection.items$, ctrl, 'selectedItems');
function canBeDeleted(image) {
if (image && image.data.softDeletedMetadata !== undefined) { ctrl.isDeleted = true; }
return image.getAction('delete').then(angular.isDefined);
}
// TODO: move to helper?
const selectionIsDeletable$ = selectedImages$.flatMap(selectedImages => {
const allDeletablePromise = $q.
all(selectedImages.map(canBeDeleted).toArray()).
then(allDeletable => allDeletable.every(v => v === true));
return Rx.Observable.fromPromise(allDeletablePromise);
});
inject$($scope, selectedImages$, ctrl, 'selectedImages');
inject$($scope, selectionIsDeletable$, ctrl, 'selectionIsDeletable');
// TODO: avoid expensive watch expressions and let stream push
// selected status to each image instead?
ctrl.imageHasBeenSelected = (image) => ctrl.selectedItems.has(image.uri);
const toggleSelection = (image) => selection.toggle(image.uri);
ctrl.select = (image) => {
selection.add(image.uri);
$window.getSelection().removeAllRanges();
};
ctrl.deselect = (image) => {
selection.remove(image.uri);
$window.getSelection().removeAllRanges();
};
ctrl.onImageClick = function (image, $event) {
if (ctrl.inSelectionMode) {
// TODO: prevent text selection?
if ($event.shiftKey) {
var lastSelectedUri = ctrl.selectedItems.last();
var lastSelectedIndex = ctrl.images.findIndex(image => {
return image.uri === lastSelectedUri;
});
var imageIndex = ctrl.images.indexOf(image);
if (imageIndex === lastSelectedIndex) {
toggleSelection(image);
return;
}
var start = Math.min(imageIndex, lastSelectedIndex);
var end = Math.max(imageIndex, lastSelectedIndex) + 1;
const imageURIs = ctrl.images
.slice(start, end)
.map(image => image.uri);
selection.union(imageURIs);
$window.getSelection().removeAllRanges();
}
else {
$window.getSelection().removeAllRanges();
toggleSelection(image);
}
}
};
const freeUpdatesListener = $rootScope.$on('images-updated', (e, updatedImages) => {
updatedImages.map(updatedImage => {
var index = ctrl.images.findIndex(i => i.data.id === updatedImage.data.id);
if (index !== -1) {
ctrl.images[index] = updatedImage;
}
var indexAll = ctrl.imagesAll.findIndex(i => i && i.data.id === updatedImage.data.id);
if (indexAll !== -1) {
ctrl.imagesAll[indexAll] = updatedImage;
}
});
// TODO: should not be needed here, the results list
// should listen to these events and update itself
// outside of any controller.
results.map(image => {
if (image == undefined){
return image;
}
const maybeUpdated = updatedImages.find(i => i.data.id === image.data.id);
if (maybeUpdated !== undefined) {
return maybeUpdated;
}
return image;
});
});
const updateImageArray = (images, image) => {
const index = images.findIndex(i => image.data.id === i.data.id);
if (index > -1){
images.splice(index, 1);
}
};
const updatePositions = (image) => {
// an image has been deleted, so update the imagePositions map, by
// decrementing the value of all images after the one deleted.
var positionIndex = imagesPositions.get(image.data.id);
imagesPositions.delete(image.data.id);
imagesPositions.forEach((value, key) => {
if (value > positionIndex) {
imagesPositions.set(key, value - 1);
}
});
};
const imageDeleteHandler = (_, images) => {
images.forEach(image => {
// TODO: should not be needed here, the selection and
// results should listen to these events and update
// itself outside of any controller
ctrl.deselect(image);
const indexAll = ctrl.imagesAll.findIndex(i => image.data.id === i.data.id);
results.removeAt(indexAll);
updateImageArray(ctrl.images, image);
updateImageArray(ctrl.imagesAll, image);
updatePositions(image);
ctrl.totalResults--;
});
};
const freeImageDeleteListener = $rootScope.$on('images-deleted', imageDeleteHandler);
const freeImageUndeleteListener = $rootScope.$on('images-undeleted', imageDeleteHandler);
// Safer than clearing the timeout in case of race conditions
// FIXME: nicer (reactive?) way to do this?
var scopeGone = false;
ctrl.batchOperations = [];
ctrl.buildBatchProgressGradient = () => {
const completed = ctrl.batchOperations
.map(({ completed }) => completed)
.reduce((acc, x) => acc + x, 0);
const total = ctrl.batchOperations
.map(({ total }) => total)
.reduce((acc, x) => acc + x, 0);
const percentage = Math.round(((completed * 1.0) / total) * 100);
return {
background:
`linear-gradient(90deg, #00adee ${percentage}%, transparent ${percentage}%)`
};
};
$scope.$on("events:batch-operations:start", (e, entry) => {
ctrl.batchOperations = [entry, ...ctrl.batchOperations];
if (entry.key === "peopleInImage" && ctrl.batchOperations.length > 1){
const total = ctrl.batchOperations.reduce((acc, operations) => acc + parseInt(operations.total), 0);
ctrl.batchOperations = [Object.assign({}, entry, { total })];
}
window.onbeforeunload = function() {
return 'Batch update in progress, are you sure you want to leave?';
};
});
$scope.$on("events:batch-operations:progress", (e, { key, completed }) => {
ctrl.batchOperations = ctrl.batchOperations.map(entry => {
if (entry.key === key) {
if (entry.key === "peopleInImage") {
completed = ctrl.batchOperations[0].completed + 1;
}
return Object.assign({}, entry, { completed });
}
return entry;
});
});
$scope.$on("events:batch-operations:complete", (e, { key }) => {
if (ctrl.batchOperations[0].key === 'peopleInImage' && ctrl.batchOperations[0].total !== ctrl.batchOperations[0].completed) {
return;
}
else {
ctrl.batchOperations = ctrl.batchOperations.filter(entry => entry.key !== key);
if (ctrl.batchOperations.length === 0) {
window.onbeforeunload = null;
}
}
});
$scope.$on('$destroy', () => {
// only save scroll position if we're destroying grid scope (avoids issue regarding ng-if triggering scope refresh)
if (0 < $scope.ctrl.images.length) {
scrollPosition.save($state.href('search.results', $stateParams));
}
freeUpdatesListener();
freeImageDeleteListener();
freeImageUndeleteListener();
scopeGone = true;
});
}
]);