FileSelect.hx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package hide.comp;
  2. class FileSelect extends Component {
  3. var extensions : Array<String>;
  4. public var path(default, set) : String;
  5. public function new(extensions,?parent,?root) {
  6. if( root == null )
  7. root = new Element("<input>");
  8. super(parent,root);
  9. root.addClass("file");
  10. this.extensions = extensions;
  11. path = null;
  12. root.mousedown(function(e) {
  13. e.preventDefault();
  14. if( e.button == 0 ) {
  15. ide.chooseFile(extensions, function(path) {
  16. if( path == null ) return; // cancel
  17. this.path = path;
  18. onChange();
  19. });
  20. }
  21. });
  22. root.contextmenu(function(e) {
  23. e.preventDefault();
  24. var fpath = getFullPath();
  25. new ContextMenu([
  26. { label : "View", enabled : fpath != null, click : function() ide.openFile(fpath) },
  27. { label : "Clear", enabled : path != null, click : function() { path = null; onChange(); } },
  28. ]);
  29. return false;
  30. });
  31. // allow drag files
  32. root.on("dragover", function(e) {
  33. root.addClass("dragover");
  34. e.preventDefault();
  35. });
  36. root.on("dragleave", function(e) {
  37. root.removeClass("dragover");
  38. });
  39. root.on("drop", function(e:js.jquery.Event) {
  40. root.removeClass("dragover");
  41. var file = getTransferFile(e);
  42. if( file != null ) {
  43. path = file;
  44. onChange();
  45. }
  46. e.preventDefault();
  47. });
  48. }
  49. function getTransferFile( e : js.jquery.Event ) {
  50. var data : js.html.DataTransfer = untyped e.originalEvent.dataTransfer;
  51. var text = data.getData("text/html");
  52. var path : String = null;
  53. if( data.files.length > 0 )
  54. path = untyped data.files[0].path;
  55. else if( StringTools.startsWith(text, "<a") && text.indexOf("jstree-anchor") > 0 ) {
  56. var rpath = ~/id="([^"]+)_anchor"/;
  57. if( rpath.match(text) )
  58. path = rpath.matched(1);
  59. }
  60. if( path != null && sys.FileSystem.exists(ide.getPath(path)) && extensions.indexOf(path.split(".").pop().toLowerCase()) >= 0 )
  61. return ide.makeRelative(path);
  62. return null;
  63. }
  64. public function getFullPath() {
  65. if( path == null )
  66. return null;
  67. var fpath = ide.getPath(path);
  68. if( sys.FileSystem.exists(fpath) )
  69. return fpath;
  70. return null;
  71. }
  72. function set_path(p:String) {
  73. var text = p == null ? "-- select --" : (sys.FileSystem.exists(ide.getPath(p)) ? "" : "[NOT FOUND] ") + p;
  74. element.val(text);
  75. element.attr("title", p == null ? "" : p);
  76. return this.path = p;
  77. }
  78. public dynamic function onChange() {
  79. }
  80. }