Type guarding React.KeyboardEvent to reuse event handlers - user-input

I created a search-bar-React-Component that resembles the one by Google.
It should fire off a search based on the input if I either click on the 'search' icon or if I hit the enter key.
I want to reuse the same function for both the click and the keydown handler:
...
var [searchParam, setSearchParam] = useState('');
function initSearch(
e:
| React.MouseEvent<HTMLButtonElement>
| React.KeyboardEvent<HTMLInputElement>
): void {
if (e.type == 'click' || (e.type == 'keydown' && e.key == 'Enter')) {
console.log(searchParam); /* ⬆️ this throws the error */
}
}
...
TypeScript keeps giving me the following error:
'Property 'key' does not exist on type 'MouseEvent<HTMLButtonElement, MouseEvent>'
I tried both of the following:
(e instance of KeyboardEvent && e.key == 'Enter') // This is always false, since e is a React.KeyboardEvent
(e instance of React.KeyboardEvent) // KeyboardEvent is not a property of React.
What is a good way to typeguard? Is there a better way to write the function?
Thank you.

Turns out using an intersection type solved the problem:
function initSearch(
e:
| (React.MouseEvent<HTMLButtonElement> & { type: 'click' }) /*⬅️*/
| (React.KeyboardEvent<HTMLInputElement> & { type: 'keydown' }) /*⬅️*/
): void {
if (e.type == 'click' || (e.type == 'keydown' && e.key == 'Enter')) {
console.log(searchParam);
}
}
I checked the type definitions, turns out the 'type' property is only defined as 'string', not as a definite primitive value.
In case I'm missing something here (i.e. that a keydown event can somehow not include the e.type == 'keydown' property), please let me know.
It feels unnecessarily hacky!

Related

NullReferenceException when gamepad is disconnected

I'm using New Input system on my game and I'm having this error
NullReferenceException: Object reference not set to an instance of an object
PauseMenu.Update ()
pointing to this line:
if (gamepad.startButton.wasPressedThisFrame || keyboard.pKey.wasPressedThisFrame)
whenever the gamepad is not connected.
void Update()
{
var gamepad = Gamepad.current;
var keyboard = Keyboard.current;
if (gamepad == null && keyboard == null)
return; // No gamepad connected.
if (gamepad.startButton.wasPressedThisFrame || keyboard.pKey.wasPressedThisFrame)
{
if (GameIsPaused)
{
Resume();
}
else
{
Pause();
}
}
}
How can I fix this?
The issue is that the exit condition requires that both keyboard and gamepad are null. In the case that gamepad is null and keyboard is not (or the other way around), an attempt is made to access a member of the null object.
You can resolve the issue by comparing each object against null before accessing its properties.
if ((gamepad != null && gamepad.startButton.wasPressedThisFrame) ||
(keyboard != null && keyboard.pKey.wasPressedThisFrame)
)
{
// Pause / Resume
}
You could also use the null conditional operator ? in each condition. When the preceding object is null, the resulting value is null. Then using the null coalescing operator ?? we convert this null value to a bool (false in this case because a null button cannot be "pressed").
if (gamepad?.startButton.wasPressedThisFrame ?? false ||
keyboard?.pKey.wasPressedThisFrame ?? false)

Set custom filters for boost log sink with custom attribute & severity level

I have a log setup in which I have 2 types of log messages:
1 based solely on severity level
1 based solely on a custom tag attribute
These attributes are defined as follows:
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", trivial::severity_level)
BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string)
I want to create a filter function that allows a message to be added to my log based on either of the 2 criteria (note that the log messages based on the custom tag attribute are always printed with severity level info, based on the trivial logger's severity levels).
So I want to have a filter, which allows a message based on if a message has the custom tag, and if it does not have it, based on the severity of the message.
I have tried to have a relative simple filter which does the following:
sink_->set_filter(
trivial::severity >= severityLevel
|| (expr::has_attr(tag_attr) && tag_attr == "JSON" && logJson_)
);
But as it is possible that the severityLevel can be either Debug, Info, Warning, Error or Fatal, if the level is configured as either Debug or Info, the custom tag attribute is ignored by the filter.
I have tried using a c++11 lambda, as following:
sink_->set_filter([this, severityLevel](const auto& attr_set) {
if (<condition for custom tag first>) {
return true;
} else if (<condition for severity level second>) {
return true;
} else {
return false;
}
});
But then I don't have an idea on how to actually check for my conditions. I have tried the following:
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
return true;
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
return true;
} else {
return false;
}
But the compiler throws several errors about this:
Core/Source/Log/Logger.cpp: In lambda function:
Core/Source/Log/Logger.cpp:127:48: error: expected primary-expression before '>' token
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
^
Core/Source/Log/Logger.cpp:127:50: error: expected primary-expression before ')' token
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
^
Core/Source/Log/Logger.cpp:129:72: error: expected primary-expression before '>' token
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
^
Core/Source/Log/Logger.cpp:129:74: error: expected primary-expression before ')' token
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
^
Core/Source/Log/Logger.cpp: In lambda function:
Core/Source/Log/Logger.cpp:134:5: error: control reaches end of non-void function [-Werror=return-type]
});
^
cc1plus: all warnings being treated as errors
scons: *** [obj/release/Core/Source/Log/Logger.os] Error 1
====5 errors, 0 warnings====
I have been scouring the boost log documentation about extracting the attributes myself, but I cannot find the information I need.
EDIT:
For posterity, I'll add how I've solved my issue (with thanks to the given answer by Andrey):
sink_->set_filter([this, severityLevel](const auto& attr_set) {
if (attr_set[tag_attr] == "JSON") {
return logJson_;
} else if (attr_set[severity] >= severityLevel) {
return true;
} else {
return false;
}
});
The filter can be written in multiple ways, I will demonstrate a few alternatives.
First, using expression templates you can write it this way:
sink_->set_filter(
(expr::has_attr(tag_attr) && tag_attr == "JSON" && logJson_) ||
trivial::severity >= severityLevel
);
Following the normal short-circuiting rules of C++, the tag attribute will be tested first and if that condition succeeds, the severity will not be tested. If the tag is not present or not JSON or logJson_ is not true, then severity level is tested.
Note that the filter above will save copies of its arguments (including logJson_ and severityLevel) at the point of construction, so if you change logJson_ later on the filter will keep using the old value. This is an important difference from your later attempts with C++14 lambdas, which access logJson_ via the captured this pointer. If you actually want to save a reference to your member logJson_ in the filter, you can use phoenix::ref:
sink_->set_filter(
(expr::has_attr(tag_attr) && tag_attr == "JSON" && boost::phoenix::ref(logJson_)) ||
trivial::severity >= severityLevel
);
However, you should remember that the filter can be called concurrently in multiple threads, so the access to logJson_ is unprotected. You will have to implement your own thread synchronization if you want to update logJson_ in run time.
Barring multithreading issues, your second attempt with a lambda is almost correct. The compiler is complaining because the lambda function is a template, and the result of attr_set["Tag"] expression depends on one of the template parameters (namely, the type of attr_set). In this case, the programmer has to qualify that the following extract<std::string>() expression is a template instantiation and not a sequence of comparisons. This is done by adding a template keyword:
if (attr_set["Tag"].template extract<std::string>() == "JSON" && logJson_) {
return true;
} else if (attr_set["Severity"].template extract<trivial::severity_level>() >= severityLevel) {
return true;
} else {
return false;
}
Note that you could use a standalone function to the same effect, which wouldn't require the template qualification:
if (boost::log::extract<std::string>("Tag", attr_set) == "JSON" && logJson_) {
return true;
} else if (boost::log::extract<trivial::severity_level>("Severity", attr_set) >= severityLevel) {
return true;
} else {
return false;
}
Finally, the preferred way to extract attribute values is to leverage attribute keywords, which you declared previously. Not only this allows to avoid the template qualification quirk but it also removes a lot of code duplication.
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", trivial::severity_level)
BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string)
if (attr_set[tag_attr] == "JSON" && logJson_) {
return true;
} else if (attr_set[severity] >= severityLevel) {
return true;
} else {
return false;
}
The attribute value name and type are inferred from the keyword declaration in this case. This use of attribute keywords is documented at the end of this section.

Input type number "only numeric value" validation

How can I validate an input of type="number" to only be valid if the value is numeric or null using only Reactive Forms (no directives)?
Only numbers [0-9] and . are allowed, no "e" or any other characters.
What I've tried so far:
Template:
<form [formGroup]="form" novalidate>
<input type="number" formControlName="number" id="number">
</form>
Component:
export class App {
form: FormGroup = new FormGroup({});
constructor(
private fb: FormBuilder,
) {
this.form = fb.group({
number: ['', [CustomValidator.numeric]]
})
}
}
CustomValidator:
export class CustomValidator{
// Number only validation
static numeric(control: AbstractControl) {
let val = control.value;
if (val === null || val === '') return null;
if (!val.toString().match(/^[0-9]+(\.?[0-9]+)?$/)) return { 'invalidNumber': true };
return null;
}
}
Plunker
The problem is when a user enters something that is not a number ("123e" or "abc") the FormControl's value becomes null, keep in mind I don't want the field to be required so if the field really is empty null value should be valid.
Cross browser support is also important (Chrome's number input fields do not allow the user to input letters - except "e", but FireFox and Safari do).
In the HTML file, you can add ngIf for your pattern like this,
<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
<p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
</div>
In .ts file you can add the Validators pattern -"^[0-9]*$"
this.Mobile = new FormControl('', [
Validators.required,
Validators.pattern("^[0-9]*$"),
Validators.minLength(8),
]);
Using directive it becomes easy and can be used throughout the application
HTML
<input type="text" placeholder="Enter value" numbersOnly>
As .keyCode() and .which() are deprecated, codes are checked using .key()
Referred from
Directive:
#Directive({
selector: "[numbersOnly]"
})
export class NumbersOnlyDirective {
#Input() numbersOnly:boolean;
navigationKeys: Array<string> = ['Backspace']; //Add keys as per requirement
constructor(private _el: ElementRef) { }
#HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent) {
if (
// Allow: Delete, Backspace, Tab, Escape, Enter, etc
this.navigationKeys.indexOf(e.key) > -1 ||
(e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A
(e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C
(e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V
(e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X
(e.key === 'a' && e.metaKey === true) || // Cmd+A (Mac)
(e.key === 'c' && e.metaKey === true) || // Cmd+C (Mac)
(e.key === 'v' && e.metaKey === true) || // Cmd+V (Mac)
(e.key === 'x' && e.metaKey === true) // Cmd+X (Mac)
) {
return; // let it happen, don't do anything
}
// Ensure that it is a number and stop the keypress
if (e.key === ' ' || isNaN(Number(e.key))) {
e.preventDefault();
}
}
}
Simplest and most effective way to do number validation is (it will restrict space and special character also)
if you dont want length restriction you can remove maxlength property
HTML
<input type="text" maxlength="3" (keypress)="validateNo($event)"/>
TS
validateNo(e): boolean {
const charCode = e.which ? e.which : e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false
}
return true
}
I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.
Sample use:
<input type="number" formControlName="num" placeholder="0" ntvFormValidity>
Directive definition:
import { Directive, Host, Self, ElementRef, AfterViewInit } from '#angular/core';
import { FormControlName, FormControl, Validators } from '#angular/forms';
#Directive({
selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {
constructor(#Host() private cn: FormControlName, #Host() private el: ElementRef) { }
/*
- Angular doesn't fire "change" events for invalid <input type="number">
- We have to check the DOM object for browser native invalid state
- Add custom validator that checks native invalidity
*/
ngAfterViewInit() {
var control: FormControl = this.cn.control;
// Bridge native invalid to ng-invalid via Validators
const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
const v_fn = control.validator;
control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
setTimeout(()=>control.updateValueAndValidity(), 0);
}
}
The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's #ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.
On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".
I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.
Something like this:
<my-input-number formControlName="num" placeholder="0">
PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers on the declaration, please let me know so I can update my Directive (and this answer).
IMO the most robust and general way to do this is by checking if the value may be converted to number. For that add a validator:
numberValidator(control: FormControl) {
if (isNaN(control?.value)) {
return {
number: true
}
}
return null;
}
export class App {
form: FormGroup = new FormGroup({});
constructor(
private fb: FormBuilder,
) {
this.form = fb.group({
number: ['', [numberValidator]]
})
}
}
You can combine it with Validators.min and/or Validators.max to further limiting the accepted values.
The easiest way would be to use a library like this one and specifically you want noStrings to be true
export class CustomValidator{ // Number only validation
static numeric(control: AbstractControl) {
let val = control.value;
const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});
if (hasError) return null;
return val;
}
}
Try to put a minimum input and allow only numbers from 0 to 9. This worked for me in Angular Cli
<input type="number" oninput="this.value=this.value.replace(/[^\d]/,'')" min=0>
You need to use regular expressions in your custom validator. For example, here's the code that allows only 9 digits in the input fields:
function ssnValidator(control: FormControl): {[key: string]: any} {
const value: string = control.value || '';
const valid = value.match(/^\d{9}$/);
return valid ? null : {ssn: true};
}
Take a look at a sample app here:
https://github.com/Farata/angular2typescript/tree/master/Angular4/form-samples/src/app/reactive-validator
Sometimes it is just easier to try something simple like this.
validateNumber(control: FormControl): { [s: string]: boolean } {
//revised to reflect null as an acceptable value
if (control.value === null) return null;
// check to see if the control value is no a number
if (isNaN(control.value)) {
return { 'NaN': true };
}
return null;
}
Hope this helps.
updated as per comment,
You need to to call the validator like this
number: new FormControl('',[this.validateNumber.bind(this)])
The bind(this) is necessary if you are putting the validator in the component which is how I do it.

coffee script testing if not defined

according to the coffee script site
console.log(s) if s?
should generate
if (typeof s !== "undefined" && s !== null) {
console.log(s);
}
But what is showing up in my browser is
if (s != null) {
return console.log(s);
}
Using coffee-script-source (1.6.2), coffee-rails (3.2.2), rails-backbone (0.7.2), rails (3.2.13)
Here is my coffee script function. any thoughts on why I am not getting what coffee script site says I should??
window.p = (s) ->
console.log(s) if s?
If you say just a bare:
console.log(s) if s?
then you will indeed get the JavaScript you're expecting (demo):
if (typeof s !== "undefined" && s !== null) {
console.log(s);
}
However, if s is a known variable such as here:
f = (s) -> console.log(s) if s?
then you'll get (demo):
if (s != null) {
//...
}
for the s? test.
So why the difference? In the first case, CoffeeScript cannot guarantee that there is an s variable in existence anywhere so it must do a typeof s check in order to avoid a ReferenceError exception.
However, if s is known to exist because it is a function parameter or has been assigned to as a local variable (so that CoffeeScript will produce a var s), then you don't need the typeof s check since you cannot, in this case, get a ReferenceError.
That leaves us with s !== null versus s != null. Dropping down to non-strict inequality (s != null) allows you to check if s is undefined or null with a single comparison. When you check typeof s !== "undefined", you wrapping the undefined test in with the "is there an s variable" check and a strict s !== null test is all that you need to check for null.
You're right,
(s) -> console.log(s) if s?
console.log(x) if x?
compiles to
(function(s) {
if (s != null) {
return console.log(s);
}
});
if (typeof x !== "undefined" && x !== null) {
console.log(x);
}
It looks like the CoffeeScript compiler is optimizing the Javascript a little bit for you, because in the case of a function argument like this, typeof s will never be undefined as s is defined right there in the function signature, even if its value is null.

tinymce.dom.replace throws an exception concerning parentNode

I'm writing a tinyMce plugin which contains a section of code, replacing one element for another. I'm using the editor's dom instance to create the node I want to insert, and I'm using the same instance to do the replacement.
My code is as follows:
var nodeData =
{
"data-widgetId": data.widget.widgetKey(),
"data-instanceKey": "instance1",
src: "/content/images/icon48/cog.png",
class: "widgetPlaceholder",
title: data.widget.getInfo().name
};
var nodeToInsert = ed.dom.create("img", nodeData);
// Insert this content into the editor window
if (data.mode == 'add') {
tinymce.DOM.add(ed.getBody(), nodeToInsert);
}
else if (data.mode == 'edit' && data.selected != null) {
var instanceKey = $(data.selected).attr("data-instancekey");
var elementToReplace = tinymce.DOM.select("[data-instancekey=" + instanceKey + "]");
if (elementToReplace.length === 1) {
ed.dom.replace(elementToReplace[0], nodeToInsert);
}
else {
throw new "No element to replace with that instance key";
}
}
TinyMCE breaks during the replace, here:
replace : function(n, o, k) {
var t = this;
if (is(o, 'array'))
n = n.cloneNode(true);
return t.run(o, function(o) {
if (k) {
each(tinymce.grep(o.childNodes), function(c) {
n.appendChild(c);
});
}
return o.parentNode.replaceChild(n, o);
});
},
..with the error Cannot call method 'replaceChild' of null.
I've verified that the two argument's being passed into replace() are not null and that their parentNode fields are instantiated. I've also taken care to make sure that the elements are being created and replace using the same document instance (I understand I.E has an issue with this).
I've done all this development in Google Chrome, but I receive the same errors in Firefox 4 and IE8 also. Has anyone else come across this?
Thanks in advance
As it turns out, I was simply passing in the arguments in the wrong order. I should have been passing the node I wanted to insert first, and the node I wanted to replace second.