Workaround for input TextField

I’m currently working on a workaround for the TextField, and naturally looked up some AS3 topics for an issue regarding Neko crashing anytime you attempted to use any key that was not a letter or number.

I came across this code:

import flash.utils.describeType;

function getKeyboardDict():Dictionary {
    var keyDescription:XML = describeType(Keyboard);
    var keyNames:XMLList = keyDescription..constant.@name;

    var keyboardDict:Dictionary = new Dictionary();

    var len:int = keyNames.length();
    for(var i:int = 0; i < len; i++) {
        keyboardDict[Keyboard[keyNames[i]]] = keyNames[i];
    }

    return keyboardDict;
}

var keyDict:Dictionary = getKeyboardDict();

trace(keyDict[Keyboard.UP]); //UP
trace(keyDict[Keyboard.SHIFT]); //SHIFT

I got as far as this for converting the code the best I can, but I’m not 100% sure how the OpenFL Dictionary works in Haxe compared to the one in AS3.

EDIT: My latest attempt consists of this code:

public static function getKeyboardDict():Dictionary {
        var keyNames = Type.getClassFields(Keyboard);

        var keyboardDict:Dictionary = new Dictionary();

        var len = keyNames.length;
        for(i in 0...len) {
            keyboardDict[Reflect.field(Keyboard, keyNames[i])] = keyNames[i];
        }

        return keyboardDict;
    }

But now neko crashes instantly, so Reflect API is probably not a good idea…

Try using a Haxe Map instead of Dictionary, I think it will work better :slight_smile:

public static function getKeyboardDict():Map<Int, String> {
        var keyNames = Type.getClassFields(Keyboard);

        var keyboardDict:Map<Int, String> = new Map<Int, String>();

        var len = keyNames.length;
        for(i in 0...len) {
            keyboardDict.set(Reflect.field(Keyboard, keyNames[i]), keyNames[i]);
        }

        return keyboardDict;
    }

That, followed by this:

class ExtTextField extends TextField
{
    private var _dict:Map<Int, String>;
    
    public function new() 
    {
        super();
        
        _dict = Keys.getKeyboardDict();
        
        addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
    }
    
    private function onKeyUp(e:KeyboardEvent):Void
    {
        if (e.keyCode == Keyboard.BACKSPACE)
            text = text.substring(0, text.length - 1);
        else if (e.keyCode == Keyboard.ENTER && multiline)
            text += "\n";
        else if (e.keyCode == Keyboard.CAPS_LOCK || e.keyCode == Keyboard.TAB)
        {
            
        }
        else if (e.keyCode == Keyboard.COMMA)
            text += ",";
        else if (e.keyCode == Keyboard.SPACE)
            text += " ";
        else
            text += _dict.get(e.keyCode);
    }
    
}

Is mostly suboptimal, but it works, which is nice to know ;p Just need to tweak some things because every time you hit SHIFT it actually prints SHIFT into the TextField