-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathFileTreeView.js
More file actions
1378 lines (1227 loc) · 50.5 KB
/
FileTreeView.js
File metadata and controls
1378 lines (1227 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2014 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
// @INCLUDE_IN_API_DOCS
/*unittests: FileTreeView*/
/**
* This is the view layer (template) for the file tree in the sidebar. It takes a FileTreeViewModel
* and renders it to the given element using Preact. User actions are signaled via an ActionCreator
* (in the Flux sense).
*/
define(function (require, exports, module) {
var Preact = require("thirdparty/preact"),
Classnames = require("thirdparty/classnames"),
Immutable = require("thirdparty/immutable"),
_ = require("thirdparty/lodash"),
FileUtils = require("file/FileUtils"),
LanguageManager = require("language/LanguageManager"),
FileTreeViewModel = require("project/FileTreeViewModel"),
ViewUtils = require("utils/ViewUtils"),
KeyEvent = require("utils/KeyEvent");
var DOM = Preact.DOM;
/**
* @private
* @type {Immutable.Map}
*
* Stores the file tree extensions for adding classes and icons. The keys of the map
* are the "categories" of the extensions and values are vectors of the callback functions.
*/
var _extensions = Immutable.Map();
/**
* @private
* @type {string}
*
* Stores the path of the currently dragged item in the filetree.
*/
var _draggedItemPath;
// Constants
// Time range from first click to second click to invoke renaming.
const RIGHT_MOUSE_BUTTON = 2,
LEFT_MOUSE_BUTTON = 0;
const INDENTATION_WIDTH = 10;
/**
* @private
*
* Returns the name of a file without its extension.
*
* @param {string} fullname The complete name of the file (not including the rest of the path)
* @param {string} extension The file extension
* @return {string} The fullname without the extension
*/
function _getName(fullname, extension) {
return extension !== "" ? fullname.substring(0, fullname.length - extension.length - 1) : fullname;
}
/**
* Mixin that allows a component to compute the full path to its directory entry.
* @private
*/
var pathComputer = {
/**
* Computes the full path of the file represented by this input.
* @private
*/
myPath: function () {
var result = this.props.parentPath + this.props.name;
// Add trailing slash for directories
if (!FileTreeViewModel.isFile(this.props.entry) && _.last(result) !== "/") {
result += "/";
}
return result;
}
};
/**
* @private
*
* Gets an appropriate width given the text provided.
*
* @param {string} text Text to measure
* @return {int} Width to use
*/
function _measureText(text) {
var measuringElement = $("<span />", { css: { "position": "absolute", "top": "-200px", "left": "-1000px", "visibility": "hidden", "white-space": "pre" } }).appendTo("body");
measuringElement.text("pW" + text);
var width = measuringElement.width();
measuringElement.remove();
return width;
}
/**
* @private
*
* Create an appropriate div based "thickness" to indent the tree correctly.
*
* @param {int} depth The depth of the current node.
* @return {PreactComponent} The resulting div.
*/
function _createThickness(depth) {
return DOM.div({
style: {
display: "inline-block",
width: INDENTATION_WIDTH * depth
}
});
}
/**
* @private
*
* Create, and indent correctly, the arrow icons used for the folders.
*
* @param {int} depth The depth of the current node.
* @return {PreactComponent} The resulting ins.
*/
function _createAlignedIns(depth) {
return DOM.ins({
className: "jstree-icon",
style: {
marginLeft: INDENTATION_WIDTH * depth
}
});
}
/**
* This is a mixin that provides rename input behavior. It is responsible for taking keyboard input
* and invoking the correct action based on that input.
* @private
*/
var renameBehavior = {
/**
* Stop clicks from propagating so that clicking on the rename input doesn't
* cause directories to collapse.
* @private
*/
handleClick: function (e) {
e.stopPropagation();
if (e.button !== LEFT_MOUSE_BUTTON) {
e.preventDefault();
}
},
/**
* If the user presses enter or escape, we either successfully complete or cancel, respectively,
* the rename or create operation that is underway.
* @private
*/
handleKeyDown: function (e) {
this.props.actions.setRenameValue(this.props.parentPath + this.refs.name.value.trim());
if (e.keyCode === KeyEvent.DOM_VK_ESCAPE) {
this.props.actions.cancelRename();
} else if (e.keyCode === KeyEvent.DOM_VK_RETURN) {
this.props.actions.performRename();
}
},
/**
* The rename or create operation can be completed or canceled by actions outside of
* this component, so we keep the model up to date by sending every update via an action.
* @private
*/
handleInput: function (e) {
this.props.actions.setRenameValue(this.props.parentPath + this.refs.name.value.trim());
if (e.keyCode !== KeyEvent.DOM_VK_LEFT &&
e.keyCode !== KeyEvent.DOM_VK_RIGHT) {
// update the width of the input field
var node = this.refs.name,
newWidth = _measureText(node.value);
$(node).width(newWidth);
}
},
/**
* If we leave the field for any reason, complete the rename.
* @private
*/
handleBlur: function () {
this.props.actions.performRename();
}
};
/**
* This is a mixin that provides drag and drop move function.
* @private
*/
var dragAndDrop = {
handleDrag: function(e) {
// Disable drag when renaming
if (this.props.entry.get("rename")) {
e.preventDefault();
e.stopPropagation();
return false;
}
// In newer CEF versions, the drag and drop data from the event
// (i.e. e.dataTransfer.getData) cannot be used to read data in dragOver event,
// so store the drag and drop data in a global variable to read it in the dragOver
// event.
_draggedItemPath = this.myPath();
// Pass the dragged item path.
e.dataTransfer.setData("text", JSON.stringify({
path: _draggedItemPath
}));
this.props.actions.dragItem(this.myPath());
this.setDragImage(e);
e.stopPropagation();
},
handleDrop: function(e) {
var data = JSON.parse(e.dataTransfer.getData("text"));
this.props.actions.moveItem(data.path, this.myPath());
this.setDraggedOver(false);
this.clearDragTimeout();
e.stopPropagation();
},
handleDragEnd: function(e) {
this.clearDragTimeout();
},
handleDragOver: function(e) {
var data = e.dataTransfer.getData("text"),
path;
if (data) {
path = JSON.parse(data).path;
} else {
path = _draggedItemPath;
}
if (path === this.myPath() || FileUtils.getParentPath(path) === this.myPath()) {
e.preventDefault();
e.stopPropagation();
return;
}
var self = this;
this.setDraggedOver(true);
// Open the directory tree when item is dragged over a directory
if (!this.dragOverTimeout) {
this.dragOverTimeout = window.setTimeout(function() {
self.props.actions.setDirectoryOpen(self.myPath(), true);
self.dragOverTimeout = null;
}, 800);
}
e.preventDefault(); // Allow the drop
e.stopPropagation();
},
handleDragLeave: function(e) {
this.setDraggedOver(false);
this.clearDragTimeout();
},
clearDragTimeout: function() {
if (this.dragOverTimeout) {
clearTimeout(this.dragOverTimeout);
this.dragOverTimeout = null;
}
},
setDraggedOver: function(draggedOver) {
if (this.state.draggedOver !== draggedOver) {
this.setState({
draggedOver: draggedOver
});
}
},
setDragImage: function(e) {
var div = window.document.createElement('div');
div.textContent = this.props.name;
div.classList.add('jstree-dragImage');
window.document.body.appendChild(div);
e.dataTransfer.setDragImage(div, -10, -10);
setTimeout(function() {
window.document.body.removeChild(div);
}, 0);
}
};
/**
* @private
*
* This component presents an input field to the user for renaming a file.
*
* Props:
* * parentPath: the full path of the directory containing this file
* * name: the name of the file, including the extension
* * actions: the action creator responsible for communicating actions the user has taken
*/
var fileRenameInput = Preact.createFactory(Preact.createClass({
mixins: [renameBehavior],
/**
* When this component is displayed, we scroll it into view and select the portion
* of the filename that excludes the extension.
*/
componentDidMount: function () {
var fullname = this.props.name,
extension = LanguageManager.getCompoundFileExtension(fullname);
var node = this.refs.name;
node.setSelectionRange(0, _getName(fullname, extension).length);
node.focus(); // set focus on the rename input
ViewUtils.scrollElementIntoView($("#project-files-container"), $(node), true);
},
render: function () {
var width = _measureText(this.props.name);
return DOM.input({
className: "jstree-rename-input",
type: "text",
defaultValue: this.props.name,
autoFocus: true,
// 🔒 Disable OS / browser assistance
autoComplete: "off",
autoCorrect: "off", // Safari / iOS
autoCapitalize: "off", // Safari / iOS
spellCheck: false, // Chrome / Firefox / Safari
inputMode: "text", // Prevent smart keyboards
enterKeyHint: "done", // Optional, avoids suggestions UI
// Event handlers
onKeyDown: this.handleKeyDown,
onInput: this.handleInput,
onClick: this.handleClick,
onBlur: this.handleBlur,
style: {
width: width
},
ref: "name"
});
}
}));
/**
* @private
*
* This mixin handles right click (or control click on Mac) action to make a file
* the "context" object for performing operations like rename.
*/
var contextSettable = {
/**
* Send matching mouseDown events to the action creator as a setContext action.
*/
handleMouseDown: function (e) {
e.stopPropagation();
if (e.button === RIGHT_MOUSE_BUTTON ||
(this.props.platform === "mac" && e.button === LEFT_MOUSE_BUTTON && e.ctrlKey)) {
this.props.actions.setContext(this.myPath());
e.preventDefault();
return;
}
// Return true only for mouse down in rename mode.
if (this.props.entry.get("rename")) {
return;
}
this.selectNode(e);
}
};
/**
* @private
*
* Returns true if the value is defined (used in `.filter`)
*
* @param {Object} value value to test
* @return {boolean} true if value is defined
*/
function isDefined(value) {
return value !== undefined;
}
/**
* Mixin for components that support the "icons" and "addClass" extension points.
* `fileNode` and `directoryNode` support this.
* @private
*/
var extendable = {
/**
* Calls the icon providers to get the collection of icons (most likely just one) for
* the current file or directory.
* @private
* @return {Array.<PreactComponent>} icon components to render
*/
getIcons: function () {
let result= [],
extensions = this.props.extensions;
if (extensions && extensions.get("icons")) {
let data = this.getDataForExtension();
let iconProviders = extensions.get("icons").toArray();
// the iconProviders list is sorted by priority at insertion
for(let iconProviderCB of iconProviders){
try {
let iconResult = iconProviderCB(data);
if (iconResult && !Preact.isValidElement(iconResult)) {
iconResult = Preact.DOM.span({
dangerouslySetInnerHTML: {
__html: $(iconResult)[0].outerHTML
}
});
}
// by this point, returns either undefined or a Preact object
if(iconResult){
result.push(iconResult);
break;
}
} catch (e) {
console.error("Exception thrown in FileTreeView icon provider: " + e, e.stack);
}
}
}
if (!result || result.length === 0) {
result = [DOM.ins({
className: "jstree-icon"
}, " ")];
}
return result;
},
/**
* Calls the addClass providers to get the classes (in string form) to add for the current
* file or directory.
* @private
* @param {string} classes Initial classes for this node
* @return {string} classes for the current node
*/
getClasses: function (classes) {
let extensions = this.props.extensions;
if (extensions && extensions.get("addClass")) {
let data = this.getDataForExtension();
let classProviders = extensions.get("addClass").toArray();
let succeededPriority = null;
// the classProviders list is sorted by priority at insertion
for(let classProviderCB of classProviders){
if(succeededPriority !== null && (succeededPriority !== classProviderCB.priority)){
// we need to append all class of the same priority and break once we shift to lower priority.
break;
}
try{
let classResult = classProviderCB(data);
if(classResult){
classes = classes + " " + classResult;
succeededPriority = classProviderCB.priority;
}
} catch (e) {
console.error("Exception thrown in FileTreeView addClass provider: " + e, e.stack);
}
}
}
return classes;
}
};
/**
* @private
*
* Component to display a file in the tree.
*
* Props:
* * parentPath: the full path of the directory containing this file
* * name: the name of the file, including the extension
* * entry: the object with the relevant metadata for the file (whether it's selected or is the context file)
* * actions: the action creator responsible for communicating actions the user has taken
* * extensions: registered extensions for the file tree
* * forceRender: causes the component to run render
*/
var fileNode = Preact.createFactory(Preact.createClass({
mixins: [contextSettable, pathComputer, extendable, dragAndDrop],
/**
* Ensures that we always have a state object.
*/
getInitialState: function () {
return {};
},
/**
* Thanks to immutable objects, we can just do a start object identity check to know
* whether or not we need to re-render.
* @private
*/
shouldComponentUpdate: function (nextProps, nextState) {
return nextProps.forceRender ||
this.props.entry !== nextProps.entry ||
this.props.extensions !== nextProps.extensions;
},
/**
* If this node is newly selected, scroll it into view. Also, move the selection or
* context boxes as appropriate.
* @private
*/
componentDidUpdate: function (prevProps, prevState) {
var wasSelected = prevProps.entry.get("selected"),
isSelected = this.props.entry.get("selected");
if (isSelected && !wasSelected) {
// TODO: This shouldn't really know about project-files-container
// directly. It is probably the case that our Preact tree should actually
// start with project-files-container instead of just the interior of
// project-files-container and then the file tree will be one self-contained
// functional unit.
ViewUtils.scrollElementIntoView($("#project-files-container"), $(Preact.findDOMNode(this)), true);
}
},
startRename: function () {
if (!this.props.entry.get("rename")) {
this.props.actions.startRename(this.myPath());
}
},
/**
* When the user clicks on the node, we'll either select it or, if they've clicked twice
* with a bit of delay in between, we'll invoke the `startRename` action.
* @private
*/
handleClick: function (e) {
// If we're renaming, allow the click to go through to the rename input.
if (this.props.entry.get("rename")) {
e.stopPropagation();
return;
}
if (e.button !== LEFT_MOUSE_BUTTON) {
return;
}
if (!(this.props.entry.get("selected") && !e.ctrlKey)) {
var language = LanguageManager.getLanguageForPath(this.myPath()),
doNotOpen = false;
if (language && language.isBinary() && "image" !== language.getId() &&
FileUtils.shouldOpenInExternalApplication(
FileUtils.getFileExtension(this.myPath()).toLowerCase()
)
) {
doNotOpen = true;
}
this.props.actions.setSelected(this.myPath(), doNotOpen);
}
e.stopPropagation();
e.preventDefault();
},
/**
* select the current node in the file tree on mouse down event on files.
* This is to increase click responsiveness of file tree.
* @private
*/
selectNode: function (e) {
if (e.button !== LEFT_MOUSE_BUTTON) {
return;
}
var language = LanguageManager.getLanguageForPath(this.myPath()),
doNotOpen = false;
if (language && language.isBinary() && "image" !== language.getId() &&
FileUtils.shouldOpenInExternalApplication(
FileUtils.getFileExtension(this.myPath()).toLowerCase()
)
) {
doNotOpen = true;
}
this.props.actions.setSelected(this.myPath(), doNotOpen);
this.render();
},
/**
* When the user double clicks, we will select this file and add it to the working
* set (via the `selectInWorkingSet` action.)
* @private
*/
handleDoubleClick: function () {
if (!this.props.entry.get("rename")) {
if (FileUtils.shouldOpenInExternalApplication(
FileUtils.getFileExtension(this.myPath()).toLowerCase()
)) {
this.props.actions.openWithExternalApplication(this.myPath());
return;
}
this.props.actions.selectInWorkingSet(this.myPath());
}
},
/**
* Create the data object to pass to extensions.
* @private
* @return {!{name:string, isFile:boolean, fullPath:string}} Data for extensions
*/
getDataForExtension: function () {
return {
name: this.props.name,
isFile: true,
fullPath: this.myPath()
};
},
render: function () {
var fullname = this.props.name,
extension = LanguageManager.getCompoundFileExtension(fullname),
name = _getName(fullname, extension);
// React automatically wraps content in a span element whereas preact doesn't, so do it manually
if (name) {
name = DOM.span({}, name);
}
if (extension) {
extension = DOM.span({
className: "extension"
}, "." + extension);
}
var nameDisplay,
cx = Classnames;
var fileClasses = cx({
'jstree-clicked selected-node': this.props.entry.get("selected"),
'context-node': this.props.entry.get("context")
});
var liArgs = [
{
className: this.getClasses("jstree-leaf"),
onClick: this.handleClick,
onMouseDown: this.handleMouseDown,
onDoubleClick: this.handleDoubleClick,
draggable: true,
onDragStart: this.handleDrag
},
DOM.ins({
className: "jstree-icon"
})
];
var thickness = _createThickness(this.props.depth);
if (this.props.entry.get("rename")) {
liArgs.push(thickness);
nameDisplay = fileRenameInput({
actions: this.props.actions,
entry: this.props.entry,
name: this.props.name,
parentPath: this.props.parentPath
});
} else {
// Need to flatten the argument list because getIcons returns an array
var aArgs = _.flatten([{
href: "#",
className: fileClasses
}, thickness, this.getIcons(), name, extension]);
nameDisplay = DOM.a.apply(DOM.a, aArgs);
}
liArgs.push(nameDisplay);
return DOM.li.apply(DOM.li, liArgs);
}
}));
/**
* @private
*
* Creates a comparison function for sorting a directory's contents with directories
* appearing before files.
*
* We're sorting the keys of the directory (the names) based partly on the values,
* so we use a closure to capture the map itself so that we can look up the
* values as needed.
*
* @param {Immutable.Map} contents The directory's contents
* @return {function(string,string)} Comparator that sorts directories first.
*/
function _buildDirsFirstComparator(contents) {
function _dirsFirstCompare(a, b) {
var aIsFile = FileTreeViewModel.isFile(contents.get(a)),
bIsFile = FileTreeViewModel.isFile(contents.get(b));
if (!aIsFile && bIsFile) {
return -1;
} else if (aIsFile && !bIsFile) {
return 1;
}
return FileUtils.compareFilenames(a, b);
}
return _dirsFirstCompare;
}
/**
* @private
*
* Sort a directory either alphabetically or with subdirectories listed first.
*
* @param {Immutable.Map} contents the directory's contents
* @param {boolean} dirsFirst true to sort subdirectories first
* @return {Immutable.Map} sorted mapping
*/
function _sortDirectoryContents(contents, dirsFirst) {
if (dirsFirst) {
return contents.keySeq().sort(_buildDirsFirstComparator(contents));
}
return contents.keySeq().sort(FileUtils.compareFilenames);
}
// Forward references to keep JSLint happy.
var directoryNode, directoryContents;
/**
* @private
*
* Component that provides the input for renaming a directory.
*
* Props:
* * parentPath: the full path of the directory containing this file
* * name: the name of the file, including the extension
* * actions: the action creator responsible for communicating actions the user has taken
*/
var directoryRenameInput = Preact.createFactory(Preact.createClass({
mixins: [renameBehavior],
/**
* When this component is displayed, we scroll it into view and select the folder name.
*/
componentDidMount: function () {
var fullname = this.props.name;
var node = this.refs.name;
node.setSelectionRange(0, fullname.length);
node.focus(); // set focus on the rename input
ViewUtils.scrollElementIntoView($("#project-files-container"), $(node), true);
},
render: function () {
var width = _measureText(this.props.name);
return DOM.input({
className: "jstree-rename-input",
type: "text",
defaultValue: this.props.name,
autoFocus: true,
// 🔒 Disable OS / browser assistance
autoComplete: "off",
autoCorrect: "off", // Safari / iOS
autoCapitalize: "off", // Safari / iOS
spellCheck: false, // Chrome / Firefox / Safari
inputMode: "text", // Prevent smart keyboards
enterKeyHint: "done", // Optional, avoids suggestions UI
// events
onKeyDown: this.handleKeyDown,
onInput: this.handleInput,
onBlur: this.handleBlur,
style: {
width: width
},
onClick: this.handleClick,
ref: "name"
});
}
}));
/**
* @private
*
* Displays a directory (but not its contents) in the tree.
*
* Props:
* * parentPath: the full path of the directory containing this file
* * name: the name of the directory
* * entry: the object with the relevant metadata for the file (whether it's selected or is the context file)
* * actions: the action creator responsible for communicating actions the user has taken
* * sortDirectoriesFirst: whether the directories should be displayed first when listing the contents of a directory
* * extensions: registered extensions for the file tree
* * forceRender: causes the component to run render
*/
directoryNode = Preact.createFactory(Preact.createClass({
mixins: [contextSettable, pathComputer, extendable, dragAndDrop],
getInitialState: function() {
return {
draggedOver: false
};
},
/**
* We need to update this component if the sort order changes or our entry object
* changes. Thanks to immutability, if any of the directory contents change, our
* entry object will change.
* @private
*/
shouldComponentUpdate: function (nextProps, nextState) {
return nextProps.forceRender ||
this.props.entry !== nextProps.entry ||
this.props.sortDirectoriesFirst !== nextProps.sortDirectoriesFirst ||
this.props.extensions !== nextProps.extensions ||
(nextState !== undefined && this.state.draggedOver !== nextState.draggedOver);
},
/**
* If you click on a directory, it will toggle between open and closed.
* @private
*/
handleClick: function (event) {
if (this.props.entry.get("rename")) {
event.stopPropagation();
return;
}
if (event.button !== LEFT_MOUSE_BUTTON
|| (brackets.platform === "mac" && event.ctrlKey)) { // in mac ctrl-click is context menu
return;
}
var isOpen = this.props.entry.get("open"),
setOpen = isOpen ? false : true;
if (event.metaKey || event.ctrlKey) {
// ctrl-alt-click toggles this directory and its children
if (event.altKey) {
if (setOpen) {
// when opening, we only open the immediate children because
// opening a whole subtree could be really slow (consider
// a `node_modules` directory, for example).
this.props.actions.toggleSubdirectories(this.myPath(), setOpen);
this.props.actions.setDirectoryOpen(this.myPath(), setOpen);
} else {
// When closing, we recursively close the whole subtree.
this.props.actions.closeSubtree(this.myPath());
}
} else {
// ctrl-click toggles the sibling directories
this.props.actions.toggleSubdirectories(this.props.parentPath, setOpen);
}
} else {
// directory toggle with no modifier
this.props.actions.setDirectoryOpen(this.myPath(), setOpen);
}
event.stopPropagation();
event.preventDefault();
},
/**
* select the current node in the file tree
* @private
*/
selectNode: function (e) {
// Do nothing for folders on keydown event. Only expand the file tree on click event
// to prevent jarring directory accordion expansion in ui.
},
/**
* Create the data object to pass to extensions.
*
* @return {{name: {string}, isFile: {boolean}, fullPath: {string}}} Data for extensions
* @private
*/
getDataForExtension: function () {
return {
name: this.props.name,
isFile: false,
fullPath: this.myPath()
};
},
render: function () {
var entry = this.props.entry,
nodeClass,
childNodes,
children = entry.get("children"),
isOpen = entry.get("open");
if (isOpen && children) {
nodeClass = "open";
childNodes = directoryContents({
depth: this.props.depth + 1,
parentPath: this.myPath(),
contents: children,
extensions: this.props.extensions,
actions: this.props.actions,
forceRender: this.props.forceRender,
platform: this.props.platform,
sortDirectoriesFirst: this.props.sortDirectoriesFirst
});
} else {
nodeClass = "closed";
}
var nameDisplay,
cx = Classnames;
var directoryClasses = cx({
'jstree-clicked sidebar-selection': entry.get("selected"),
'context-node': entry.get("context")
});
var nodeClasses = "jstree-" + nodeClass;
if (this.state.draggedOver) {
nodeClasses += " jstree-draggedOver";
}
var liArgs = [
{
className: this.getClasses(nodeClasses),
onClick: this.handleClick,
onMouseDown: this.handleMouseDown,
draggable: true,
onDragStart: this.handleDrag,
onDrop: this.handleDrop,
onDragEnd: this.handleDragEnd,
onDragOver: this.handleDragOver,
onDragLeave: this.handleDragLeave
},
_createAlignedIns(this.props.depth)
];
var thickness = _createThickness(this.props.depth);
if (entry.get("rename")) {
liArgs.push(thickness);
nameDisplay = directoryRenameInput({
actions: this.props.actions,
entry: entry,
name: this.props.name,
parentPath: this.props.parentPath
});
} else {
// React automatically wraps content in a span element whereas preact doesn't, so do it manually
if (this.props.name) {
var name = DOM.span({}, this.props.name);
}
// Need to flatten the arguments because getIcons returns an array
var aArgs = _.flatten([{
href: "#",
className: directoryClasses
}, thickness, this.getIcons(), name]);
nameDisplay = DOM.a.apply(DOM.a, aArgs);
}
liArgs.push(nameDisplay);
liArgs.push(childNodes);
return DOM.li.apply(DOM.li, liArgs);
}
}));
/**
* @private
*
* Displays the contents of a directory.
*