P5.js - Translate keycode presses to actual keyboard letters (in system) - keyboard

function keyPressed() {
if (keyCode === "e") {
control *"system keyboard"* to output "e"
I want to type letters with poses via the [Teachable Machine.] (https://teachablemachine.withgoogle.com/train/pose)

The simplest solution would be to use the p5.js key property, which for normal printable keys will be the string for the letter inserted by the key being pressed (taking the state of the shift key into account). Just be sure you take the non-printable keys (Shift, Alt, Meta, Backspace, Tab, Enter, Escape, etc.) into account.
If you don't want to use the built in p5.js capabilities, then this question is a duplicate of Get Character value from KeyCode in JavaScript... then trim

I kinda wrote everything within comments...
// copied this line of of the mozilla docs also this is for window rather than canvas
window.addEventListener("keydown", function(event){//you should just create a html canvas
// console.log(event.code) // and just select('#id')||('.class')||('canvas').
// console.log(event.code.replace("Key","")) // ya can also get rid of these console.log()-s
if(typeof getCharString === "function"){ // this checks if function exists
getCharString(event.code) // this'll give you the text
}
}) // idk if you can do this with p5.js or not tbh...
function getCharString(P_EN_GUI_N_AGHHHH){
console.log(`${P_EN_GUI_N_AGHHHH} !!!`)
console.log( P_EN_GUI_N_AGHHHH+"!!!")
}
// |
// here's just for copy |
// V
window.addEventListener("keydown", function(event){
if(typeof getCharString === "function"){
getCharString(event.code)
}
})
function getCharString(str){
console.log(str)
} // str == string

Related

Selecting (and deleting) entire function with definition (INCLUDING whitespace) in Vim

I recently switched to using Vim (with VSCode) as my editor.
I'm trying to delete a function with it's definition in JavaScript. I looked on google and here on StackOverflow and found this question. Unfortunately the answers for this question only work for functions without white space.
Here is how my function looks:
const useBattery = () => {
const [battery, setBattery] = useState({ level: 0, charging: false });
const handleChange = ({ target: { level, charging } }) => setBattery({ level, charging });
useEffect(() => {
let battery;
navigator.getBattery().then(bat => {
battery = bat;
battery.addEventListener("levelchange", handleChange);
battery.addEventListener("chargingchange", handleChange);
handleChange({ target: battery });
});
return () => {
battery.removeEventListener("levelchange", handleChange);
battery.removeEventListener("chargingchange", handleChange);
};
}, []);
return battery;
};
I tried several approaches, the best one was da{ when my cursor is within the function. This motion will delete the function body, but not the definition.
Is there any way to delete the function and the definition in one motion using Vim, if there is white space in the function?
From inside the function, as you say da{ deletes only the braces and its content, without the preceding declaration or the following semicolon. However... if we switch to linewise...?
There is a semi-hidden section a bit under :help exclusive-linewise with bold heading but no tag to jump to: "FORCING A MOTION TO BE LINEWISE, CHARACTERWISE OR BLOCKWISE", saying that we can switch to a non-default selection by using v (characterwise), V (linewise) or Ctrl-V (blockwise) immediately after the operator. So...
dVa{
As mentioned in the post you linked to, d]] when the cursor is placed at the beginning of the function definition will delete the whole function.

Cocos2dx 3.4 - manipulating user input

I am working on a breakout-type game using Cocos2dx.
I need to make a highscore table. After the game is finished, I'd like to display a page, where player types his username into text field.
I don't know how to add the user input into variable, so I can manipulate it later (mainly saving along with score to display it on the selected scene).
What is the simplest way of doing so?
Approach One:
If you just need to handle keyboard as key-event, It's as easy as these below lines of code:
HelloWorld::init()
{
...
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_UP_ARROW: /*Jump maybe*/ break;
case EventKeyboard::KeyCode::KEY_DOWN_ARROW: /*Crouch maybe*/ break;
case EventKeyboard::KeyCode::KEY_RIGHT_ARROW: /*Move Right maybe*/ break;
case EventKeyboard::KeyCode::KEY_LEFT_ARROW: /*Move Left maybe*/ break;
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
...
return true;
}
I think it's clear enough not to need any extra description.
Approach Two: if you need an input box that user/player can enter string with keyboard and you get what is entered, I recommend to use TextField which is available in cocos2d v3 ( and with some difficulty in v2) and has a full functionality. You can create and initial one of them as:
auto textField = cocos2d::ui::TextField::create("hint: enter here","Arial" , 30);
textField->setTextHorizontalAlignment(cocos2d::TextHAlignment::CENTER);
textField->setTextVerticalAlignment(cocos2d::TextVAlignment::CENTER);
textField->setColor(Color3B(100,100,100));
textField->setMaxLength(10);
textField->setMaxLengthEnabled(true);
textField->setTouchAreaEnabled(true);
textField->setTouchSize(Size(200,400));
textField->setPosition(...);
textField->addEventListener(CC_CALLBACK_2(HelloWorld::textFieldEvent, this));
this->addChild(textField, 10);
You can get entered data any time with std::string enteredData= textField->getString();
You can also do something when user entering text with two event as :
void HelloWorld::textFieldEvent(Ref *pSender, cocos2d::ui::TextField::EventType type)
{
switch (type)
{
case cocos2d::ui::TextField::EventType::ATTACH_WITH_IME:
{
textField->setColor(Color3B::BLACK);
// or whatever elese
break;
}
case cocos2d::ui::TextField::EventType::DETACH_WITH_IME:
{
textField->setColor(Color3B(100,100,100));
// or whatever elese
break;
}
}
}
Enjoy !

Extjs messagebox prompt limit the text input entered by user

I am using http://dev.sencha.com/playpen/docs/output/Ext.MessageBox.html#prompt to display an extjs prompt where the user can enter some text and click Ok. Now if I want to restrict the user to enter text not more than 100 characters, what should I do?
I understand I need to write some kind of an eventhandler but what is the event? Is it possible to look at a code sample?
When you invoke MessageBox.prompt it will return instance of the singleton which can be used to get dom reference of textbox element, this element can be used to specify attribute maxlength which can be used to limit length of text that can be entered
var dlg = Ext.MessageBox.prompt('Name', 'Please enter your name:', function(btn, text){
if (btn == 'ok'){
// process text value and close...
}
});
var textboxEl = dlg.getDialog().body.child('input[class=ext-mb-input]', true);
textboxEl.setAttribute('maxlength', 1); // second parameter is character length allowed so change it according to your need
Reference:
Character Limit in HTML
Updated for Ext 4 (with many thanks to SilentSakky for the original answer):
var dlg = Ext.MessageBox.prompt('Name', 'Please enter your name:', function(btn, text){
if (btn == 'ok'){
// process text value and close...
}
});
var textboxEl = dlg.getEl().query('input')[0];
textboxEl.setAttribute('maxlength', 1);

Preventing tab to cycle through address bar

I realize this is probably an accessibility issue that may best be left alone, but I'd like to figure out if it possible to prevent the tab from visiting the address bar in the tabbing cycle.
My application has another method of cycling through input areas, but many new users instinctively try to use the tab, and it doesn't work as expected.
Here's a generic jquery implementation where you don't have to find the max tab index. Note that this code will also work if you add or remove elements in your DOM.
$('body').on('keydown', function (e) {
var jqTarget = $(e.target);
if (e.keyCode == 9) {
var jqVisibleInputs = $(':input:visible');
var jqFirst = jqVisibleInputs.first();
var jqLast = jqVisibleInputs.last();
if (!e.shiftKey && jqTarget.is(jqLast)) {
e.preventDefault();
jqFirst.focus();
} else if (e.shiftKey && jqTarget.is(jqFirst)) {
e.preventDefault();
jqLast.focus();
}
}
});
However, you should note that the code above will work only with visible inputs. Some elements may become the document's activeElement even if they're not input so if it's your case, you should consider adding them to the $(':input:visible') selector.
I didn't add code to scroll to the focus element as this may not be the wanted behavior for everyone... if you need it, just add it after the call to focus()
You can control the tabbing order (and which elements should be able to get focus at all) with the global tabindex attribute.
However, you can't prevent users to tab into another context not under control of the page (e.g. the browser's address bar) with this attribute. (It might be possible in combination with JavaScript, though.)
For such a (evil!) use case, you'd have to look into keyboard traps.
WCAG 2.0 has the guideline: 2.1.2 No Keyboard Trap. In Understanding SC 2.1.2 you can find "Techniques and Failures" for this guideline:
F10: Failure of Success Criterion 2.1.2 and Conformance Requirement 5 due to combining multiple content formats in a way that traps users inside one format type
FLASH17: Providing keyboard access to a Flash object and avoiding a keyboard trap
G21: Ensuring that users are not trapped in content
So maybe you get some ideas by that how such a trap would be possible.
I used to add two tiny, invisible elements on tabindex 1 and on the last tabindex. Add a onFocus for these two: The element with tabindex 1 should focus the last real element, the one with the max tabindex should focus the first real element. Make sure that you focus the first real element on Dom:loaded.
You could use Javascript and capture the "keydown" event on the element with the highest "tabindex". If the user presses the "TAB" key (event.keyCode==9) without the "Shift" key (event.shiftKey == false) then simply set the focus on the element with the lowest tabindex.
You would then also need to do the same thing in reverse for the element with the lowest tabindex. Capture the "keydown" event for this element. If the user presses the "TAB" key (event.keyCode==9) WITH the "Shift" key (event.shiftKey == true) then set the focus on the element with the highest tabindex.
This would effectively prevent the address bar from ever being focused using the TAB key. I am using this technique in my current project.
Dont forget to cancel the keydown event if the proper key-combination is pressed! With JQuery it's "event.preventDefault()". In standard Javascript, I believe you simply "return false".
Here's a JQuery-laden snippet I'm using...
$('#dos-area [tabindex=' + maxTabIndex + ']').on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == false) {
e.preventDefault();
$('#dos-area [tabindex=1]').focus();
}
});
$('#dos-area [tabindex=1]').on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == true) {
e.preventDefault();
$('#dos-area [tabindex=' + maxTabIndex + ']').focus();
}
});
Also keep in mind that setting tabindex=0 has undesirable results on the order in which things are focused. I always remember (for my purposes) that tabindex is a 1-based index.
Hi i have an easy solution. just place an empty span on the end of the page. Give it an id and tabindex = 0, give this span an onfocus event, when triggered let your focus jump to the first element on your page you want to cycle trough. This way you won't lose focus on the document, because if you do your events don't work anymore.
I used m-albert solution and it works. But in my case I do not control the tabindex properties. My intention is set the focus on a toolbar at the top of the page (first control) when user leaves the last control on the page.
$(':input:visible').last().on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == false) {
e.preventDefault();
$('html, body').animate({
scrollTop: 0
}, 500);
$(':input:visible', context).first().focus();
}
});
Where context can be any Jquery object, selector, or even document, or you can omit it.
The scrolling animation, of course, is optional.
Not sure if this is still a issue, but I implemented my own solution that does not use jQuery, can be used in the case when all the elements have tabindex="0", and when the DOM is subject to change. I added an extra argument for a context if you want to limit the tabcycling to a specific element containing the tabindex elements.
Some brief notes on the arguments:
min must be less than or equal to max, and contextSelector is an optional string that if used should be a valid selector. If contextSelector is an invalid selector or a selector that doesn't match with any elements, then the document object is used as the context.
function PreventAddressBarTabCyle(min, max, contextSelector) {
if( isNaN(min) ) throw new Error('Invalid argument: first argument needs to be a number type.')
if( isNaN(max) ) throw new Error('Invalid argument: second argument needs to be a number type.')
if( max < min ) throw new Error('Invalid arguments: first argument needs to be less than or equal to the second argument.')
min = min |0;
max = max |0;
var isDocumentContext = typeof(contextSelector) != 'string' || contextSelector == '';
if( min == max ) {
var tabCycleListener = function(e) {
if( e.keyCode != 9 ) return;
var context = isDocumentContext ? document : document.querySelector(contextSelector);
if( !context && !('querySelectorAll' in context) ) {
context = document;
}
var tabindexElements = context.querySelectorAll('[tabindex]');
if( tabindexElements.length <= 0 ) return;
var targetIndex = -1;
for(var i = 0; i < tabindexElements.length; i++) {
if( e.target == tabindexElements[i] ) {
targetIndex = i;
break;
}
}
// Check if tabbing backward and reached first element
if( e.shiftKey == true && targetIndex == 0 ) {
e.preventDefault();
tabindexElements[tabindexElements.length-1].focus();
}
// Check if tabbing forward and reached last element
if( e.shiftKey == false && targetIndex == tabindexElements.length-1 ) {
e.preventDefault();
tabindexElements[0].focus();
}
};
} else {
var tabCycleListener = function(e) {
if( e.keyCode != 9 ) return;
var context = isDocumentContext ? document : document.querySelector(contextSelector);
if( !context && !('querySelectorAll' in context) ) {
context = document;
}
var tabindex = parseInt(e.target.getAttribute('tabindex'));
if( isNaN(tabindex) ) return;
// Check if tabbing backward and reached first element
if (e.shiftKey == true && tabindex == min) {
e.preventDefault();
context.querySelector('[tabindex="' + max + '"]').focus();
}
// Check if tabbing forward and reached last element
else if (e.shiftKey == false && tabindex == max) {
e.preventDefault();
context.querySelector('[tabindex="' + min + '"]').focus();
}
};
}
document.body.addEventListener('keydown', tabCycleListener, true);
}
More notes:
If min is equal to max, then tab cycling will occur naturally until the last element in the context is reached. If min is strictly less than max, then tabbing will cycle naturally until either the min or the max is reached. If tabbing backwards and the min is reached, or tabbing forward and the max is reached, then the tabbing will cycle to the min element or max element respectively.
Example usage:
// For all tabindex elements inside the document
PreventAddressBarTabCyle(0,0);
// Same as above
PreventAddressBarTabCyle(1,1);
// NOTE: if min == max, the tabindex value doesn't matter
// it matches all elements with the tabindex attribute
// For all tabindex elements between 1 and 15
PreventAddressBarTabCyle(1,15);
// For tabindex elements between 1 and 15 inside
// the first element that matches the selector: .some-form
PreventAddressBarTabCyle(1,15, '.some-form');
// For all tabindex elements inside the element
// that matches the selector: .some-form2
PreventAddressBarTabCyle(1,1, '.some-form2');
Salinan solution worked for me
Put this in the start of your html page:
<span tabindex="0" id="prevent-outside-tab"></span>
and this at the end of your html page.:
<span tabindex="0" onfocus="foucsFirstElement()"></span>
foucsFirstElement() :
foucsFirstElement() {
document.getElementById("prevent-outside-tab").focus();
},

How do I prevent a keyup event from interrupting a keydown event in jQuery? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Cross-browser way to get automatically repeating keydown events when key is held down
I'm trying to create a simple game in JavaScript/CSS/HTML, and I am using jQuery (and a little bit of Underscore) to handle key presses. The player controls a block using arrow keys. I've run into a problem with handling multiple keypresses at the same time. I have a system in place where a closure keeps track of all arrow keys that are pressed. This works well if the player presses keys in the following sequence:
Player presses Down (block moves down)
Player presses Left (block moves diagonally down-left)
Player releases Down (block moves left)
Player releases Left (block stops
However, the block stops if steps 3 and 4 are reversed. Here is what actually happens in that case:
Player presses Down (block moves down)
Player presses Left (block moves diagonally down-left)
Player releases Left (block stops)
The expected behavior is that on step 3, the block would continue to move down, rather than stopping completely.
From traces I have put in the code, it appears that a keyup event actually stops the propagation of further keydown events, even when my finger is still holding down one of the arrow keys.
Here is a snippet of relevant code. Can anyone tell me where the problem might be?
// Creates an animation handler for a specific element.
// Animation reacts to any changes as they are submitted
var getMovementAnimator = function(element) {
var params = {},
$element = $(element);
return function(changes) {
_.each(changes, function(val, key) {
// Remove null or zeroish keys from animation params
if ( (val == 0 || !val) && _.has(params, key)) {
delete params[key];
} else {
params[key] = '+=' + val + 'px';
}
});
$element.animate(params, {duration: 0, queue: false});
console.log(params);
};
};
// Determines direction and speed of movement for an element
// after a keypress event
var getMovementChange = function(keyEvent, keydown) {
var isMoving = !!keydown,
params = {},
dir = '',
speed = keydown ? 5 : 0,
arrows = {left: 37, up: 38, right: 39, down: 40};
switch (keyEvent.which) {
case arrows.left:
dir = 'left';
speed = -speed;
break;
case arrows.up:
dir = 'top';
speed = -speed;
break;
case arrows.right:
dir = 'left';
break;
case arrows.down:
dir = 'top';
break;
}
// If key hit not one of above, do nothing
if (!dir) {
return false;
}
if (!speed) {
console.log('key up: ', dir);
}
params[dir] = speed;
return params;
}
// Sets up key handlers
$(document).ready(function() {
var board = $('#board'),
animatePlayer = getMovementAnimator('.player');
$(document).keydown(function(e) {
e.preventDefault();
var changes = getMovementChange(e, true);
animatePlayer(changes);
}).keyup(function(e) {
e.preventDefault();
var changes = getMovementChange(e, false);
animatePlayer(changes);
});
});
Further search on Stack Overflow (using the right keywords) showed me that the issue I am seeing is not actually a bug in my code. Rather, this is expected behavior for the operating system.
However, I found a workaround which I believe will resolve the issue.

Resources