-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
file_table.js
1238 lines (1100 loc) · 39.7 KB
/
file_table.js
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert, assertInstanceof} from 'chrome://resources/js/assert.m.js';
import {dispatchSimpleEvent} from 'chrome://resources/js/cr.m.js';
import {AsyncUtil} from '../../../common/js/async_util.js';
import {FileType} from '../../../common/js/file_type.js';
import {importer} from '../../../common/js/importer_common.js';
import {str, strf, util} from '../../../common/js/util.js';
import {importerHistoryInterfaces} from '../../../externs/background/import_history.js';
import {FilesAppEntry} from '../../../externs/files_app_entry_interfaces.js';
import {VolumeManager} from '../../../externs/volume_manager.js';
import {FilesTooltip} from '../../elements/files_tooltip.js';
import {FileListModel} from '../file_list_model.js';
import {ListThumbnailLoader} from '../list_thumbnail_loader.js';
import {MetadataModel} from '../metadata/metadata_model.js';
import {A11yAnnounce} from './a11y_announce.js';
import {DragSelector} from './drag_selector.js';
import {FileMetadataFormatter} from './file_metadata_formatter.js';
import {filelist, FileTableList} from './file_table_list.js';
import {Table} from './table/table.js';
import {TableColumn} from './table/table_column.js';
import {TableColumnModel} from './table/table_column_model.js';
/**
* Custom column model for advanced auto-resizing.
*/
export class FileTableColumnModel extends TableColumnModel {
/**
* @param {!Array<TableColumn>} tableColumns Table columns.
*/
constructor(tableColumns) {
super(tableColumns);
/** @private {?FileTableColumnModel.ColumnSnapshot} */
this.snapshot_ = null;
}
/**
* Sets column width so that the column dividers move to the specified
* position. This function also check the width of each column and keep the
* width larger than MIN_WIDTH_.
*
* @private
* @param {Array<number>} newPos Positions of each column dividers.
*/
applyColumnPositions_(newPos) {
// Check the minimum width and adjust the positions.
for (let i = 0; i < newPos.length - 2; i++) {
if (!this.columns_[i].visible) {
newPos[i + 1] = newPos[i];
} else if (newPos[i + 1] - newPos[i] < FileTableColumnModel.MIN_WIDTH_) {
newPos[i + 1] = newPos[i] + FileTableColumnModel.MIN_WIDTH_;
}
}
for (let i = newPos.length - 1; i >= 2; i--) {
if (!this.columns_[i - 1].visible) {
newPos[i - 1] = newPos[i];
} else if (newPos[i] - newPos[i - 1] < FileTableColumnModel.MIN_WIDTH_) {
newPos[i - 1] = newPos[i] - FileTableColumnModel.MIN_WIDTH_;
}
}
// Set the new width of columns
for (let i = 0; i < this.columns_.length; i++) {
if (!this.columns_[i].visible) {
this.columns_[i].width = 0;
} else {
// Make sure each cell has the minimum width. This is necessary when the
// window size is too small to contain all the columns.
this.columns_[i].width = Math.max(
FileTableColumnModel.MIN_WIDTH_, newPos[i + 1] - newPos[i]);
}
}
}
/**
* Normalizes widths to make their sum 100% if possible. Uses the proportional
* approach with some additional constraints.
*
* @param {number} contentWidth Target width.
* @override
*/
normalizeWidths(contentWidth) {
let totalWidth = 0;
// Some columns have fixed width.
for (let i = 0; i < this.columns_.length; i++) {
totalWidth += this.columns_[i].width;
}
const positions = [0];
let sum = 0;
for (let i = 0; i < this.columns_.length; i++) {
const column = this.columns_[i];
sum += column.width;
// Faster alternative to Math.floor for non-negative numbers.
positions[i + 1] = ~~(contentWidth * sum / totalWidth);
}
this.applyColumnPositions_(positions);
}
/**
* Handles to the start of column resizing by splitters.
*/
handleSplitterDragStart() {
this.initializeColumnPos();
}
/**
* Handles to the end of column resizing by splitters.
*/
handleSplitterDragEnd() {
this.destroyColumnPos();
}
/**
* Initialize a column snapshot which is used in setWidthAndKeepTotal().
*/
initializeColumnPos() {
this.snapshot_ = new FileTableColumnModel.ColumnSnapshot(this.columns_);
}
/**
* Destroy the column snapshot which is used in setWidthAndKeepTotal().
*/
destroyColumnPos() {
this.snapshot_ = null;
}
/**
* Sets the width of column while keeping the total width of table.
* Before and after calling this method, you must initialize and destroy
* columnPos with initializeColumnPos() and destroyColumnPos().
* @param {number} columnIndex Index of column that is resized.
* @param {number} columnWidth New width of the column.
*/
setWidthAndKeepTotal(columnIndex, columnWidth) {
columnWidth = Math.max(columnWidth, FileTableColumnModel.MIN_WIDTH_);
this.snapshot_.setWidth(columnIndex, columnWidth);
this.applyColumnPositions_(this.snapshot_.newPos);
// Notify about resizing
dispatchSimpleEvent(this, 'resize');
}
/**
* Obtains a column by the specified horizontal position.
* @param {number} x Horizontal position.
* @return {Object} The object that contains column index, column width, and
* hitPosition where the horizontal position is hit in the column.
*/
getHitColumn(x) {
let i = 0;
for (; x >= this.columns_[i].width; i++) {
x -= this.columns_[i].width;
}
if (i >= this.columns_.length) {
return null;
}
return {index: i, hitPosition: x, width: this.columns_[i].width};
}
/** @override */
setVisible(index, visible) {
if (index < 0 || index > this.columns_.length - 1) {
return;
}
const column = this.columns_[index];
if (column.visible === visible) {
return;
}
// Re-layout the table. This overrides the default column layout code in
// the parent class.
const snapshot = new FileTableColumnModel.ColumnSnapshot(this.columns_);
column.visible = visible;
// Keep the current column width, but adjust the other columns to
// accommodate the new column.
snapshot.setWidth(index, column.width);
this.applyColumnPositions_(snapshot.newPos);
}
/**
* Export a set of column widths for use by #restoreColumnWidths. Use these
* two methods instead of manually saving and setting column widths, because
* doing the latter will not correctly save/restore column widths for hidden
* columns.
* @see #restoreColumnWidths
* @return {!Object} config
*/
exportColumnConfig() {
// Make a snapshot, and use that to compute a column layout where all the
// columns are visible.
const snapshot = new FileTableColumnModel.ColumnSnapshot(this.columns_);
for (let i = 0; i < this.columns_.length; i++) {
if (!this.columns_[i].visible) {
snapshot.setWidth(i, this.columns_[i].absoluteWidth);
}
}
// Export the column widths.
const config = {};
for (let i = 0; i < this.columns_.length; i++) {
config[this.columns_[i].id] = {
width: snapshot.newPos[i + 1] - snapshot.newPos[i],
};
}
return config;
}
/**
* Restores a set of column widths previously created by calling
* #exportColumnConfig.
* @see #exportColumnConfig
* @param {!Object} config
*/
restoreColumnConfig(config) {
// Convert old-style raw column widths into new-style config objects.
if (Array.isArray(config)) {
const tmpConfig = {};
tmpConfig[this.columns_[0].id] = config[0];
tmpConfig[this.columns_[1].id] = config[1];
tmpConfig[this.columns_[3].id] = config[2];
tmpConfig[this.columns_[4].id] = config[3];
config = tmpConfig;
}
// Columns must all be made visible before restoring their widths. Save the
// current visibility so it can be restored after.
const visibility = [];
for (let i = 0; i < this.columns_.length; i++) {
visibility[i] = this.columns_[i].visible;
this.columns_[i].visible = true;
}
// Do not use external setters (e.g. #setVisible, #setWidth) here because
// they trigger layout thrash, and also try to dynamically resize columns,
// which interferes with restoring the old column layout.
for (const columnId in config) {
const column = this.columns_[this.indexOf(columnId)];
if (column) {
// Set column width. Ignore invalid widths.
const width = ~~config[columnId].width;
if (width > 0) {
column.width = width;
}
}
}
// Restore column visibility. Use setVisible here, to trigger table
// relayout.
for (let i = 0; i < this.columns_.length; i++) {
this.setVisible(i, visibility[i]);
}
}
}
/**
* Customize the column header to decorate with a11y attributes that announces
* the sorting used when clicked.
*
* @this {TableColumn} Bound by TableHeader before
* calling.
* @param {Element} table Table being rendered.
* @return {Element}
*/
export function renderHeader_(table) {
const column = /** @type {TableColumn} */ (this);
const container = table.ownerDocument.createElement('div');
container.classList.add('table-label-container');
const textElement = table.ownerDocument.createElement('span');
textElement.textContent = column.name;
const dm = table.dataModel;
let sortOrder = column.defaultOrder;
let isSorted = false;
if (dm && dm.sortStatus.field === column.id) {
isSorted = true;
// Here we have to flip, because clicking will perform the opposite sorting.
sortOrder = dm.sortStatus.direction === 'desc' ? 'asc' : 'desc';
}
textElement.setAttribute('aria-describedby', 'sort-column-' + sortOrder);
textElement.setAttribute('role', 'button');
container.appendChild(textElement);
const icon = document.createElement('cr-icon-button');
const iconName = sortOrder === 'desc' ? 'up' : 'down';
icon.setAttribute('iron-icon', `files16:arrow_${iconName}_small`);
icon.setAttribute('tabindex', '-1');
icon.setAttribute('aria-hidden', 'true');
icon.classList.add('sort-icon', 'no-overlap');
container.classList.toggle('not-sorted', !isSorted);
container.classList.toggle('sorted', isSorted);
container.appendChild(icon);
return container;
}
/**
* Minimum width of column. Note that is not marked private as it is used in the
* unit tests.
* @const {number}
*/
FileTableColumnModel.MIN_WIDTH_ = 40;
/**
* A helper class for performing resizing of columns.
*/
FileTableColumnModel.ColumnSnapshot = class {
/**
* @param {!Array<!TableColumn>} columns
*/
constructor(columns) {
/** @private {!Array<number>} */
this.columnPos_ = [0];
for (let i = 0; i < columns.length; i++) {
this.columnPos_[i + 1] = columns[i].width + this.columnPos_[i];
}
/**
* Starts off as a copy of the current column positions, but gets modified.
* @private {!Array<number>}
*/
this.newPos = this.columnPos_.slice(0);
}
/**
* Set the width of the given column. The snapshot will keep the total width
* of the table constant.
* @param {number} index
* @param {number} width
*/
setWidth(index, width) {
// Skip to resize 'selection' column
if (index < 0 || index >= this.columnPos_.length - 1 || !this.columnPos_) {
return;
}
// Round up if the column is shrinking, and down if the column is expanding.
// This prevents off-by-one drift.
const currentWidth = this.columnPos_[index + 1] - this.columnPos_[index];
const round = width < currentWidth ? Math.ceil : Math.floor;
// Calculate new positions of column splitters.
const newPosStart = this.columnPos_[index] + width;
const posEnd = this.columnPos_[this.columnPos_.length - 1];
for (let i = 0; i < index + 1; i++) {
this.newPos[i] = this.columnPos_[i];
}
for (let i = index + 1; i < this.columnPos_.length - 1; i++) {
const posStart = this.columnPos_[index + 1];
this.newPos[i] = (posEnd - newPosStart) *
(this.columnPos_[i] - posStart) / (posEnd - posStart) +
newPosStart;
this.newPos[i] = round(this.newPos[i]);
}
this.newPos[index] = this.columnPos_[index];
this.newPos[this.columnPos_.length - 1] = posEnd;
}
};
/**
* File list Table View.
*/
export class FileTable extends Table {
constructor() {
super();
/** @private {number} */
this.beginIndex_ = 0;
/** @private {number} */
this.endIndex_ = 0;
/** @private {?ListThumbnailLoader} */
this.listThumbnailLoader_ = null;
/** @private {?AsyncUtil.RateLimiter} */
this.relayoutRateLimiter_ = null;
/** @private {?MetadataModel} */
this.metadataModel_ = null;
/** @private {?FileMetadataFormatter} */
this.formatter_ = null;
/** @private {boolean} */
this.useModificationByMeTime_ = false;
/** @private {?importerHistoryInterfaces.HistoryLoader} */
this.historyLoader_ = null;
/** @private {boolean} */
this.importStatusVisible_ = false;
/** @private {?VolumeManager} */
this.volumeManager_ = null;
/** @private {!Array} */
this.lastSelection_ = [];
/** @private {?function(!Event)} */
this.onThumbnailLoadedBound_ = null;
/** @public {?A11yAnnounce} */
this.a11y = null;
throw new Error('Designed to decorate elements');
}
/**
* Decorates the element.
* @param {!Element} self Table to decorate.
* @param {!MetadataModel} metadataModel To retrieve metadata.
* @param {!VolumeManager} volumeManager To retrieve volume info.
* @param {!importerHistoryInterfaces.HistoryLoader} historyLoader
* @param {!A11yAnnounce} a11y FileManagerUI to be able to announce a11y
* messages.
* @param {boolean} fullPage True if it's full page File Manager, False if a
* file open/save dialog.
* @suppress {checkPrototypalTypes} Closure was failing because the signature
* of this decorate() doesn't match the base class.
*/
static decorate(
self, metadataModel, volumeManager, historyLoader, a11y, fullPage) {
Table.decorate(self);
self.__proto__ = FileTable.prototype;
FileTableList.decorate(self.list);
self.list.setOnMergeItems(self.updateHighPriorityRange_.bind(self));
self.metadataModel_ = metadataModel;
self.volumeManager_ = volumeManager;
self.historyLoader_ = historyLoader;
self.a11y = a11y;
// Force the list's ending spacer to be tall enough to allow overscroll.
const endSpacer = self.querySelector('.spacer:last-child');
if (endSpacer) {
endSpacer.classList.add('signals-overscroll');
}
/** @private {ListThumbnailLoader} */
self.listThumbnailLoader_ = null;
/** @private {number} */
self.beginIndex_ = 0;
/** @private {number} */
self.endIndex_ = 0;
/** @private {function(!Event)} */
self.onThumbnailLoadedBound_ = self.onThumbnailLoaded_.bind(self);
/**
* Reflects the visibility of import status in the UI. Assumption: import
* status is only enabled in import-eligible locations. See
* ImportController#onDirectoryChanged. For this reason, the code in this
* class checks if import status is visible, and if so, assumes that all
* the files are in an import-eligible location.
* TODO(kenobi): Clean this up once import status is queryable from
* metadata.
*
* @private {boolean}
*/
self.importStatusVisible_ = true;
/** @private {boolean} */
self.useModificationByMeTime_ = false;
const nameColumn =
new TableColumn('name', str('NAME_COLUMN_LABEL'), fullPage ? 386 : 324);
nameColumn.renderFunction = self.renderName_.bind(self);
nameColumn.headerRenderFunction = renderHeader_;
const sizeColumn =
new TableColumn('size', str('SIZE_COLUMN_LABEL'), 110, true);
sizeColumn.renderFunction = self.renderSize_.bind(self);
sizeColumn.defaultOrder = 'desc';
sizeColumn.headerRenderFunction = renderHeader_;
const statusColumn =
new TableColumn('status', str('STATUS_COLUMN_LABEL'), 60, true);
statusColumn.renderFunction = self.renderStatus_.bind(self);
statusColumn.visible = self.importStatusVisible_;
statusColumn.headerRenderFunction = renderHeader_;
const typeColumn =
new TableColumn('type', str('TYPE_COLUMN_LABEL'), fullPage ? 110 : 110);
typeColumn.renderFunction = self.renderType_.bind(self);
typeColumn.headerRenderFunction = renderHeader_;
const modTimeColumn = new TableColumn(
'modificationTime', str('DATE_COLUMN_LABEL'), fullPage ? 150 : 210);
modTimeColumn.renderFunction = self.renderDate_.bind(self);
modTimeColumn.defaultOrder = 'desc';
modTimeColumn.headerRenderFunction = renderHeader_;
const columns =
[nameColumn, sizeColumn, statusColumn, typeColumn, modTimeColumn];
const columnModel = new FileTableColumnModel(columns);
self.columnModel = columnModel;
self.formatter_ = new FileMetadataFormatter();
const selfAsTable = /** @type {!Table} */ (self);
selfAsTable.setRenderFunction(
self.renderTableRow_.bind(self, selfAsTable.getRenderFunction()));
// Keep focus on the file list when clicking on the header.
selfAsTable.header.addEventListener('mousedown', e => {
self.list.focus();
e.preventDefault();
});
self.relayoutRateLimiter_ =
new AsyncUtil.RateLimiter(self.relayoutImmediately_.bind(self));
// Save the last selection. This is used by shouldStartDragSelection.
self.list.addEventListener('mousedown', function(e) {
this.lastSelection_ = this.selectionModel.selectedIndexes;
}.bind(self), true);
self.list.addEventListener('touchstart', function(e) {
this.lastSelection_ = this.selectionModel.selectedIndexes;
}.bind(self), true);
self.list.shouldStartDragSelection =
self.shouldStartDragSelection_.bind(self);
}
/**
* Sort data by the given column. Overridden to add the a11y message after
* sorting.
* @param {number} index The index of the column to sort by.
* @override
*/
sort(index) {
const cm = this.columnModel;
if (!this.dataModel) {
return;
}
const fieldName = cm.getId(index);
const sortStatus = this.dataModel.sortStatus;
let sortDirection = cm.getDefaultOrder(index);
if (sortStatus.field === fieldName) {
// If it's sorting the column that's already sorted, we need to flip the
// sorting order.
sortDirection = sortStatus.direction === 'desc' ? 'asc' : 'desc';
}
const msgId =
sortDirection === 'asc' ? 'COLUMN_SORTED_ASC' : 'COLUMN_SORTED_DESC';
const msg = strf(msgId, fieldName);
// Delegate to parent to sort.
super.sort(index);
this.a11y.speakA11yMessage(msg);
}
/**
* @override
*/
onDataModelSorted() {
const fileListModel = /** @type {FileListModel} */ (this.dataModel);
const hasGroupHeadingAfterSort = fileListModel.shouldShowGroupHeading();
// Sort doesn't trigger redraw sometimes, e.g. if we sort by Name for now,
// then we sort by time, if the list order doesn't change, no permuted event
// is triggered, thus no redraw is triggered. In this scenario, we need to
// manually trigger a redraw to remove/add the group heading.
if (hasGroupHeadingAfterSort !== fileListModel.hasGroupHeadingBeforeSort) {
this.list.redraw();
}
}
/**
* Updates high priority range of list thumbnail loader based on current
* viewport.
*
* @param {number} beginIndex Begin index.
* @param {number} endIndex End index.
* @private
*/
updateHighPriorityRange_(beginIndex, endIndex) {
// Keep these values to set range when a new list thumbnail loader is set.
this.beginIndex_ = beginIndex;
this.endIndex_ = endIndex;
if (this.listThumbnailLoader_ !== null) {
this.listThumbnailLoader_.setHighPriorityRange(beginIndex, endIndex);
}
}
/**
* Sets list thumbnail loader.
* @param {ListThumbnailLoader} listThumbnailLoader A list thumbnail loader.
*/
setListThumbnailLoader(listThumbnailLoader) {
if (this.listThumbnailLoader_) {
this.listThumbnailLoader_.removeEventListener(
'thumbnailLoaded', this.onThumbnailLoadedBound_);
}
this.listThumbnailLoader_ = listThumbnailLoader;
if (this.listThumbnailLoader_) {
this.listThumbnailLoader_.addEventListener(
'thumbnailLoaded', this.onThumbnailLoadedBound_);
this.listThumbnailLoader_.setHighPriorityRange(
this.beginIndex_, this.endIndex_);
}
}
/**
* Returns the element containing the thumbnail of a certain list item as
* background image.
* @param {number} index The index of the item containing the desired
* thumbnail.
* @return {?Element} The element containing the thumbnail, or null, if an
* error occurred.
*/
getThumbnail(index) {
const listItem = this.getListItemByIndex(index);
if (!listItem) {
return null;
}
const container = listItem.querySelector('.detail-thumbnail');
if (!container) {
return null;
}
return container.querySelector('.thumbnail');
}
/**
* Handles thumbnail loaded event.
* @param {!Event} event An event.
* @private
*/
onThumbnailLoaded_(event) {
const listItem = this.getListItemByIndex(event.index);
if (listItem) {
const box = listItem.querySelector('.detail-thumbnail');
if (box) {
if (event.dataUrl) {
this.setThumbnailImage_(
assertInstanceof(box, HTMLDivElement), event.dataUrl);
} else {
this.clearThumbnailImage_(assertInstanceof(box, HTMLDivElement));
}
const icon = listItem.querySelector('.detail-icon');
icon.classList.toggle('has-thumbnail', !!event.dataUrl);
}
}
}
/**
* Adjust column width to fit its content.
* @param {number} index Index of the column to adjust width.
* @override
*/
fitColumn(index) {
const render = this.columnModel.getRenderFunction(index);
const MAXIMUM_ROWS_TO_MEASURE = 1000;
// Create a temporaty list item, put all cells into it and measure its
// width. Then remove the item. It fits "list > *" CSS rules.
const container = this.ownerDocument.createElement('li');
container.style.display = 'inline-block';
container.style.textAlign = 'start';
// The container will have width of the longest cell.
container.style.webkitBoxOrient = 'vertical';
// Select at most MAXIMUM_ROWS_TO_MEASURE items around visible area.
const items = this.list.getItemsInViewPort(
this.list.scrollTop, this.list.clientHeight);
const firstIndex = Math.floor(
Math.max(0, (items.last + items.first - MAXIMUM_ROWS_TO_MEASURE) / 2));
const lastIndex =
Math.min(this.dataModel.length, firstIndex + MAXIMUM_ROWS_TO_MEASURE);
for (let i = firstIndex; i < lastIndex; i++) {
const item = this.dataModel.item(i);
const div = this.ownerDocument.createElement('div');
div.className = 'table-row-cell';
div.appendChild(render(item, this.columnModel.getId(index), this));
container.appendChild(div);
}
this.list.appendChild(container);
const width = parseFloat(window.getComputedStyle(container).width);
this.list.removeChild(container);
this.columnModel.initializeColumnPos();
this.columnModel.setWidthAndKeepTotal(index, Math.ceil(width));
this.columnModel.destroyColumnPos();
}
/**
* Sets the visibility of the cloud import status column.
* @param {boolean} visible
*/
setImportStatusVisible(visible) {
if (this.importStatusVisible_ != visible) {
this.importStatusVisible_ = visible;
this.columnModel.setVisible(this.columnModel.indexOf('status'), visible);
this.relayout();
}
}
/**
* Sets date and time format.
* @param {boolean} use12hourClock True if 12 hours clock, False if 24 hours.
*/
setDateTimeFormat(use12hourClock) {
this.formatter_.setDateTimeFormat(use12hourClock);
}
/**
* Sets whether to use modificationByMeTime as "Last Modified" time.
* @param {boolean} useModificationByMeTime
*/
setUseModificationByMeTime(useModificationByMeTime) {
this.useModificationByMeTime_ = useModificationByMeTime;
}
/**
* Obtains if the drag selection should be start or not by referring the mouse
* event.
* @param {MouseEvent} event Drag start event.
* @return {boolean} True if the mouse is hit to the background of the list,
* or certain areas of the inside of the list that would start a drag
* selection.
* @private
*/
shouldStartDragSelection_(event) {
// If the shift key is pressed, it should starts drag selection.
if (event.shiftKey) {
return true;
}
// If we're outside of the element list, start the drag selection.
if (!this.list.hasDragHitElement(event)) {
return true;
}
// If the position values are negative, it points the out of list.
const pos = DragSelector.getScrolledPosition(this.list, event);
if (!pos) {
return false;
}
if (pos.x < 0 || pos.y < 0) {
return true;
}
// If the item index is out of range, it should start the drag selection.
const itemHeight = this.list.measureItem().height;
// Faster alternative to Math.floor for non-negative numbers.
const itemIndex = ~~(pos.y / itemHeight);
if (itemIndex >= this.list.dataModel.length) {
return true;
}
// If the pointed item is already selected, it should not start the drag
// selection.
if (this.lastSelection_ && this.lastSelection_.indexOf(itemIndex) !== -1) {
return false;
}
// If the horizontal value is not hit to column, it should start the drag
// selection.
const hitColumn = this.columnModel.getHitColumn(pos.x);
if (!hitColumn) {
return true;
}
// Check if the point is on the column contents or not.
switch (this.columnModel.columns_[hitColumn.index].id) {
case 'name':
const item = this.list.getListItemByIndex(itemIndex);
if (!item) {
return false;
}
const spanElement = item.querySelector('.filename-label span');
const spanRect = spanElement.getBoundingClientRect();
// The this.list.cachedBounds_ object is set by
// DragSelector.getScrolledPosition.
if (!this.list.cachedBounds) {
return true;
}
const textRight =
spanRect.left - this.list.cachedBounds.left + spanRect.width;
return textRight <= hitColumn.hitPosition;
default:
return true;
}
}
/**
* Render the Name column of the detail table.
*
* Invoked by Table when a file needs to be rendered.
*
* @param {!Entry} entry The Entry object to render.
* @param {string} columnId The id of the column to be rendered.
* @param {Table} table The table doing the rendering.
* @return {!HTMLDivElement} Created element.
* @private
*/
renderName_(entry, columnId, table) {
const label = /** @type {!HTMLDivElement} */
(this.ownerDocument.createElement('div'));
const metadata = this.metadataModel_.getCache(
[entry], ['contentMimeType', 'isDlpRestricted'])[0];
const mimeType = metadata.contentMimeType;
const locationInfo = this.volumeManager_.getLocationInfo(entry);
const icon = filelist.renderFileTypeIcon(
this.ownerDocument, entry, locationInfo, mimeType);
if (FileType.isImage(entry, mimeType) ||
FileType.isVideo(entry, mimeType) ||
FileType.isAudio(entry, mimeType) || FileType.isRaw(entry, mimeType)) {
icon.appendChild(this.renderThumbnail_(entry, icon));
}
icon.appendChild(this.renderCheckmark_());
label.appendChild(icon);
label.entry = entry;
label.className = 'detail-name';
label.appendChild(
filelist.renderFileNameLabel(this.ownerDocument, entry, locationInfo));
if (locationInfo && locationInfo.isDriveBased) {
label.appendChild(filelist.renderPinned(this.ownerDocument));
}
const isDlpRestricted = !!metadata.isDlpRestricted;
if (isDlpRestricted) {
label.appendChild(this.renderDlpManagedIcon_());
}
return label;
}
/**
* @param {number} index Index of the list item.
* @return {string}
*/
getItemLabel(index) {
if (index === -1) {
return '';
}
/** @type {Entry|FilesAppEntry} */
const entry = this.dataModel.item(index);
if (!entry) {
return '';
}
const locationInfo = this.volumeManager_.getLocationInfo(entry);
return util.getEntryLabel(locationInfo, entry);
}
/**
* Render the Size column of the detail table.
*
* @param {Entry} entry The Entry object to render.
* @param {string} columnId The id of the column to be rendered.
* @param {Table} table The table doing the rendering.
* @return {!HTMLDivElement} Created element.
* @private
*/
renderSize_(entry, columnId, table) {
const div = /** @type {!HTMLDivElement} */
(this.ownerDocument.createElement('div'));
div.className = 'size';
this.updateSize_(div, entry);
return div;
}
/**
* Sets up or updates the size cell.
*
* @param {HTMLDivElement} div The table cell.
* @param {Entry} entry The corresponding entry.
* @private
*/
updateSize_(div, entry) {
const metadata =
this.metadataModel_.getCache([entry], ['size', 'hosted'])[0];
const size = metadata.size;
const hosted = metadata.hosted;
div.textContent = this.formatter_.formatSize(size, hosted);
}
/**
* Render the Status column of the detail table.
*
* @param {Entry} entry The Entry object to render.
* @param {string} columnId The id of the column to be rendered.
* @param {Table} table The table doing the rendering.
* @return {!HTMLDivElement} Created element.
* @private
*/
renderStatus_(entry, columnId, table) {
const div =
/** @type {!HTMLDivElement} */ (
this.ownerDocument.createElement('div'));
div.className = 'status status-icon';
if (entry) {
this.updateStatus_(div, entry);
}
return div;
}
/**
* Returns the status of the entry w.r.t. the given import destination.
* @param {Entry} entry
* @param {!importer.Destination} destination
* @return {!Promise<string>} The import status - will be 'imported',
* 'copied', or 'unknown'.
*/
getImportStatus_(entry, destination) {
// If import status is not visible, early out because there's no point
// retrieving it.
if (!this.importStatusVisible_ || !importer.isEligibleType(entry)) {
// Our import history doesn't deal with directories.
// TODO(kenobi): May need to revisit this if the above assumption changes.
return Promise.resolve('unknown');
}
// For the compiler.
const fileEntry = /** @type {!FileEntry} */ (entry);
return this.historyLoader_.getHistory()
.then(
/** @param {!importerHistoryInterfaces.ImportHistory} history */
history => {
return Promise.all([
history.wasImported(fileEntry, destination),
history.wasCopied(fileEntry, destination),
]);
})
.then(
/** @param {!Array<boolean>} status */
status => {
if (status[0]) {
return 'imported';
} else if (status[1]) {
return 'copied';
} else {
return 'unknown';
}
});
}
/**
* Render the status icon of the detail table.
*
* @param {HTMLDivElement} div
* @param {Entry} entry The Entry object to render.
* @private
*/
updateStatus_(div, entry) {
this.getImportStatus_(entry, importer.Destination.GOOGLE_DRIVE)
.then(
/** @param {string} status */
status => {
div.setAttribute('file-status-icon', status);
});
}
/**
* Render the Type column of the detail table.
*
* @param {Entry} entry The Entry object to render.
* @param {string} columnId The id of the column to be rendered.
* @param {Table} table The table doing the rendering.
* @return {!HTMLDivElement} Created element.
* @private
*/
renderType_(entry, columnId, table) {
const div = /** @type {!HTMLDivElement} */
(this.ownerDocument.createElement('div'));
div.className = 'type';
const mimeType =
this.metadataModel_.getCache([entry], ['contentMimeType'])[0]
.contentMimeType;
div.textContent =
FileListModel.getFileTypeString(FileType.getType(entry, mimeType));
return div;
}
/**
* Render the Date column of the detail table.
*
* @param {Entry} entry The Entry object to render.