Procházet zdrojové kódy

allow to bind a file watch to an element

ncannasse před 6 roky
rodič
revize
911f8a8b4a
1 změnil soubory, kde provedl 33 přidání a 5 odebrání
  1. 33 5
      hide/tools/FileWatcher.hx

+ 33 - 5
hide/tools/FileWatcher.hx

@@ -1,24 +1,35 @@
 package hide.tools;
 
+private typedef FileEvent = {path:String,fun:Void->Void,checkDel:Bool,element:js.html.Element};
+
 class FileWatcher {
 
 	var ide : hide.Ide;
-	var watches : Map<String,{ events : Array<{path:String,fun:Void->Void,checkDel:Bool}>, w : js.node.fs.FSWatcher, changed : Bool, isDir : Bool }> = new Map();
+	var watches : Map<String,{ events : Array<FileEvent>, w : js.node.fs.FSWatcher, changed : Bool, isDir : Bool }> = new Map();
+	var timer : haxe.Timer;
 
 	public function new() {
 		ide = hide.Ide.inst;
 	}
 
 	public function dispose() {
+		if( timer != null ) {
+			timer.stop();
+			timer = null;
+		}
 		for( w in watches )
 			if( w.w != null )
 				w.w.close();
 		watches = new Map();
 	}
 
-	public function register( path : String, updateFun, ?checkDelete : Bool ) {
+	public function register( path : String, updateFun, ?checkDelete : Bool, ?element : Element ) {
 		var w = getWatches(path);
-		w.events.push({ path : path, fun : updateFun, checkDel : checkDelete });
+		w.events.push({ path : path, fun : updateFun, checkDel : checkDelete, element : element == null ? null : element[0] });
+		if( element != null && timer == null ) {
+			timer = new haxe.Timer(1000);
+			timer.run = cleanEvents;
+		}
 	}
 
 	public function unregister( path : String, updateFun : Void -> Void ) {
@@ -34,6 +45,23 @@ class FileWatcher {
 		}
 	}
 
+	function cleanEvents() {
+		for( w in watches )
+			for( e in w.events.copy() )
+				isLive(w.events, e);
+	}
+
+	function isLive( events : Array<FileEvent>, e : FileEvent ) {
+		if( e.element == null ) return true;
+		var elt = e.element;
+		while( elt != null ) {
+			if( elt.nodeName == "BODY" ) return true;
+			elt = elt.parentElement;
+		}
+		events.remove(e);
+		return false;
+	}
+
 	function getWatches( path : String ) {
 		var w = watches.get(path);
 		if( w == null ) {
@@ -51,14 +79,14 @@ class FileWatcher {
 					if( !w.changed ) return;
 					w.changed = false;
 					for( e in w.events.copy() )
-						if( k == "change" || e.checkDel )
+						if( isLive(w.events,e) && (k == "change" || e.checkDel) )
 							e.fun();
 				}, 100);
 			}) catch( e : Dynamic ) {
 				// file does not exists, trigger a delayed event
 				haxe.Timer.delay(function() {
 					for( e in w.events.copy() )
-						if( e.checkDel )
+						if( isLive(w.events,e) && e.checkDel )
 							e.fun();
 				}, 0);
 				return w;