浏览代码

added Slider, blur on textinput enter

Nicolas Cannasse 8 年之前
父节点
当前提交
5eb3d39855
共有 2 个文件被更改,包括 81 次插入1 次删除
  1. 75 0
      h2d/Slider.hx
  2. 6 1
      h2d/TextInput.hx

+ 75 - 0
h2d/Slider.hx

@@ -0,0 +1,75 @@
+package h2d;
+
+class Slider extends h2d.Interactive {
+
+	public var tile : h2d.Tile;
+	public var cursorTile : h2d.Tile;
+	public var minValue(default, set) : Float = 0;
+	public var maxValue(default, set) : Float = 1;
+	public var value(default, set) : Float = 0;
+
+	public function new(?width:Int, ?height:Int, ?parent) {
+		super(width, height, parent);
+
+		tile = h2d.Tile.fromColor(0x808080, width, 4);
+		tile.dy = (height - 4) >> 1;
+
+		cursorTile = h2d.Tile.fromColor(0xCCCCCC, 5, height);
+		cursorTile.dx = -2;
+	}
+
+	function set_minValue(v) {
+		if( value < v ) value = v;
+		return minValue = v;
+	}
+
+	function set_maxValue(v) {
+		if( value > v ) value = v;
+		return maxValue = v;
+	}
+
+	function set_value(v) {
+		if( v < minValue ) v = minValue;
+		if( v > maxValue ) v = maxValue;
+		return value = v;
+	}
+
+	override function getBoundsRec( relativeTo, out, forSize ) {
+		super.getBoundsRec(relativeTo, out, forSize);
+		if( forSize ) addBounds(relativeTo, out, 0, 0, width, height);
+		if( tile != null ) addBounds(relativeTo, out, tile.dx, tile.dy, tile.width, tile.height);
+	}
+
+	override function draw(ctx:RenderContext) {
+		super.draw(ctx);
+		emitTile(ctx, tile);
+		var px = Math.round( (value - minValue) * width / (maxValue - minValue) );
+		cursorTile.dx += px;
+		emitTile(ctx, cursorTile);
+		cursorTile.dx -= px;
+	}
+
+	override function handleEvent(e:hxd.Event) {
+		super.handleEvent(e);
+		if( e.cancel ) return;
+		switch( e.kind ) {
+		case EPush:
+			value = (e.relX / width) * (maxValue - minValue) + minValue;
+			onChange();
+			var scene = scene;
+			startDrag(function(e) {
+				if( this.scene != scene || e.kind == ERelease ) {
+					scene.stopDrag();
+					return;
+				}
+				value = (e.relX / width) * (maxValue - minValue) + minValue;
+				onChange();
+			});
+		default:
+		}
+	}
+
+	public dynamic function onChange() {
+	}
+
+}

+ 6 - 1
h2d/TextInput.hx

@@ -110,6 +110,10 @@ class TextInput extends Text {
 					cursorIndex--;
 					onChange();
 				}
+			case K.ENTER:
+				cursorIndex = -1;
+				interactive.blur();
+				return;
 			case K.Z if( K.isDown(K.CTRL) ):
 				if( undo.length > 0 && canEdit ) {
 					redo.push(curHistoryState());
@@ -233,7 +237,8 @@ class TextInput extends Text {
 			ctx.setRenderZone(absX, absY, h.x - absX, h.y - absY);
 		}
 
-		if( cursorIndex >=0 && (text != cursorText || cursorIndex != cursorXIndex) ) {
+		if( cursorIndex >= 0 && (text != cursorText || cursorIndex != cursorXIndex) ) {
+			if( cursorIndex > text.length ) cursorIndex = text.length;
 			cursorText = text;
 			cursorXIndex = cursorIndex;
 			cursorX = calcTextWidth(text.substr(0, cursorIndex));