1
0
Fork 0
spacetac/src/ui/common/UITextInput.ts

50 lines
1.7 KiB
TypeScript
Raw Normal View History

2017-09-24 22:23:22 +00:00
module TK.SpaceTac.UI {
2017-05-03 18:12:13 +00:00
/**
* UI component to allow the user to enter a small text
*/
2018-04-12 16:30:08 +00:00
export class UITextInput {
2017-05-03 18:12:13 +00:00
private content: Phaser.Text
2018-04-12 16:30:08 +00:00
private placeholder: Phaser.Text
2017-05-03 18:12:13 +00:00
private maxlength: number
2018-04-12 16:30:08 +00:00
constructor(builder: UIBuilder, background: string, x = 0, y = 0, maxlength: number, placeholder = "") {
let input_bg = builder.image(background, x, y, true);
2017-05-03 18:12:13 +00:00
input_bg.inputEnabled = true;
input_bg.input.useHandCursor = true;
2018-04-12 16:30:08 +00:00
input_bg.events.onInputUp.add(() => {
builder.view.inputs.grabKeyboard(this, key => this.processKey(key));
});
this.content = builder.in(input_bg).text("");
this.placeholder = builder.in(input_bg).text(placeholder);
this.placeholder.alpha = 0.5;
this.maxlength = maxlength;
2017-05-03 18:12:13 +00:00
}
/**
* Process a key press
*/
processKey(key: string): void {
if (key.length == 1 && this.content.text.length < this.maxlength) {
2018-04-12 16:30:08 +00:00
this.setContent(this.content.text + key);
2017-05-03 18:12:13 +00:00
} else if (key == "Backspace" && this.content.text.length > 0) {
2018-04-12 16:30:08 +00:00
this.setContent(this.content.text.substr(0, this.content.text.length - 1));
2017-05-03 18:12:13 +00:00
}
}
/**
* Get current text content
*/
getContent(): string {
return this.content.text;
}
/**
* Set the current text content
*/
setContent(content: string): void {
this.content.text = content.slice(0, this.maxlength);
2018-04-12 16:30:08 +00:00
this.placeholder.visible = !this.content.text;
}
2017-05-03 18:12:13 +00:00
}
}