Skip to content

Commit

Permalink
Backslash text input (kaplayjs#507)
Browse files Browse the repository at this point in the history
  • Loading branch information
dragoncoder047 authored Nov 13, 2024
1 parent 1b269a0 commit 9cb2451
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
2 changes: 1 addition & 1 deletion examples/textInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ add([
// Add the node that you write in
const food = add([
text(""),
textInput(true, 10), // make it have focus and only be 20 chars max
textInput(true, 20), // make it have focus and only be 20 chars max
pos(width() / 2, height() / 2),
anchor("center"),
]);
Expand Down
20 changes: 15 additions & 5 deletions src/components/misc/textInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ export interface TextInputComp extends Comp {
* Enable the text input array from being modified by user input.
*/
hasFocus: boolean;
/**
* The "real" text that the user typed, without any escaping.
*/
typedText: string;
}

export function textInput(
Expand All @@ -22,30 +26,36 @@ export function textInput(
): TextInputComp {
let charEv: KEventController;
let backEv: KEventController;

return {
id: "textInput",
hasFocus: hasFocus,
require: ["text"],
typedText: "",
add(this: GameObj<TextComp & TextInputComp>) {
const flip = () => {
this.text = this.typedText.replace(/([\[\\])/g, "\\$1");
};

charEv = _k.k.onCharInput((character) => {
if (
this.hasFocus
&& (!maxInputLength || this.text.length < maxInputLength)
&& (!maxInputLength || this.typedText.length < maxInputLength)
) {
if (_k.k.isKeyDown("shift")) {
this.text += character.toUpperCase();
this.typedText += character.toUpperCase();
}
else {
this.text += character;
this.typedText += character;
}
flip();
}
});

backEv = _k.k.onKeyPressRepeat("backspace", () => {
if (this.hasFocus) {
this.text = this.text.slice(0, -1);
this.typedText = this.typedText.slice(0, -1);
}
flip();
});
},
destroy() {
Expand Down

0 comments on commit 9cb2451

Please sign in to comment.