KeyEvent#
A custom KeyboardEvent that attempts to eliminate cross-browser inconsistencies, and also provide both keyCode and charCode information for all key events (when such information can be determined).
KeyEvent tries to provide a higher level, more polished keyboard event information on top of the "raw" KeyboardEvent.
The mechanics of using KeyEvents is a little different from the underlying KeyboardEvent. To use KeyEvents, you need to create a stream and then add KeyEvents to the stream, rather than using the EventTarget.dispatchEvent. Here's an example usage:
// Initialize a stream for the KeyEvents:
var stream = KeyEvent.keyPressEvent.forTarget(document.body);
// Start listening to the stream of KeyEvents.
stream.listen((keyEvent) =>
window.console.log('KeyPress event detected ${keyEvent.charCode}'));
...
// Add a new KeyEvent of someone pressing the 'A' key to the stream so
// listeners can know a KeyEvent happened.
stream.add(new KeyEvent('keypress', keyCode: 65, charCode: 97));
This class is very much a work in progress, and we'd love to get information on how we can make this class work with as many international keyboards as possible. Bugs welcome!
Implemented types
Constructors#
KeyEvent() factory#
Programmatically create a new KeyEvent (and KeyboardEvent).
Implementation
factory KeyEvent(
String type, {
Window? view,
bool canBubble = true,
bool cancelable = true,
int keyCode = 0,
int charCode = 0,
int location = 1,
bool ctrlKey = false,
bool altKey = false,
bool shiftKey = false,
bool metaKey = false,
EventTarget? currentTarget,
}) {
if (view == null) {
view = window;
}
KeyboardEvent eventObj;
// Currently this works on everything but Safari. Safari throws an
// "Attempting to change access mechanism for an unconfigurable property"
// TypeError when trying to do the Object.defineProperty hack, so we avoid
// this branch if possible.
// Also, if we want this branch to work in FF, we also need to modify
// _initKeyboardEvent to also take charCode and keyCode values to
// initialize initKeyEvent.
eventObj =
new Event.eventType(
'KeyboardEvent',
type,
canBubble: canBubble,
cancelable: cancelable,
)
as KeyboardEvent;
// Chromium Hack
JS(
'void',
"Object.defineProperty(#, 'keyCode', {"
" get : function() { return this.keyCodeVal; } })",
eventObj,
);
JS(
'void',
"Object.defineProperty(#, 'which', {"
" get : function() { return this.keyCodeVal; } })",
eventObj,
);
JS(
'void',
"Object.defineProperty(#, 'charCode', {"
" get : function() { return this.charCodeVal; } })",
eventObj,
);
var keyIdentifier = _convertToHexString(charCode, keyCode);
eventObj._initKeyboardEvent(
type,
canBubble,
cancelable,
view,
keyIdentifier,
location,
ctrlKey,
altKey,
shiftKey,
metaKey,
);
JS('void', '#.keyCodeVal = #', eventObj, keyCode);
JS('void', '#.charCodeVal = #', eventObj, charCode);
// Tell dart2js that it smells like a KeyboardEvent!
setDispatchProperty(eventObj, _keyboardEventDispatchRecord);
var keyEvent = new KeyEvent.wrap(eventObj);
if (keyEvent._currentTarget == null) {
keyEvent._currentTarget = currentTarget == null ? window : currentTarget;
}
return keyEvent;
}
KeyEvent.wrap()#
Construct a KeyEvent with parent as the event we're emulating.
Implementation
KeyEvent.wrap(KeyboardEvent parent)
: _parent = parent,
_shadowAltKey = false,
_shadowCharCode = 0,
_shadowKeyCode = 0,
super(parent) {
_parent = parent;
_shadowAltKey = _realAltKey;
_shadowCharCode = _realCharCode;
_shadowKeyCode = _realKeyCode;
_currentTarget = _parent.currentTarget;
}
Properties#
altKey no setter override#
Calculated value of whether the alt key is pressed is for this event.
Implementation
bool get altKey => _shadowAltKey;
bubbles no setter inherited#
Inherited from _WrappedEvent.
Implementation
bool get bubbles => wrapped.bubbles!;
cancelable no setter inherited#
Inherited from _WrappedEvent.
Implementation
bool get cancelable => wrapped.cancelable!;
charCode no setter override#
Calculated value of what the estimated charCode is for this event.
Implementation
int get charCode => this.type == 'keypress' ? _shadowCharCode : 0;
code no setter override#
Implementation
String get code => _parent.code!;
composed no setter inherited#
Inherited from _WrappedEvent.
Implementation
bool get composed => wrapped.composed!;
ctrlKey no setter override#
True if the ctrl key is pressed during this event.
Implementation
bool get ctrlKey => _parent.ctrlKey;
currentTarget no setter#
The currently registered target for this event.
Implementation
EventTarget? get currentTarget => _currentTarget;
defaultPrevented no setter inherited#
Inherited from _WrappedEvent.
Implementation
bool get defaultPrevented => wrapped.defaultPrevented;
detail no setter override#
Implementation
int get detail => _parent.detail!;
eventPhase no setter inherited#
Inherited from _WrappedEvent.
Implementation
int get eventPhase => wrapped.eventPhase;
hashCode no setter inherited#
The hash code for this object.
A hash code is a single integer which represents the state of the object that affects operator == comparisons.
All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.
Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.
Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.
If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.
Inherited from Object.
Implementation
external int get hashCode;
isComposed no setter#
Implementation
bool get isComposed => throw new UnimplementedError();
isComposing no setter override#
Implementation
bool get isComposing => _parent.isComposing!;
isTrusted no setter inherited#
Inherited from _WrappedEvent.
Implementation
bool get isTrusted => wrapped.isTrusted!;
key no setter override#
Implementation
String get key => _parent.key!;
keyCode no setter override#
Calculated value of what the estimated keyCode is for this event.
Implementation
int get keyCode => _shadowKeyCode;
location no setter override#
Accessor to the part of the keyboard that the key was pressed from (one of KeyLocation.STANDARD, KeyLocation.RIGHT, KeyLocation.LEFT, KeyLocation.NUMPAD, KeyLocation.MOBILE, KeyLocation.JOYSTICK).
Implementation
int get location => _parent.location;
matchingTarget no setter inherited#
Inherited from _WrappedEvent.
Implementation
Element get matchingTarget {
if (_selector == null) {
throw new UnsupportedError(
'Cannot call matchingTarget if this Event did'
' not arise as a result of event delegation.',
);
}
Element? currentTarget = this.currentTarget as Element?;
Element? target = this.target as Element?;
do {
if (target!.matches(_selector!)) return target;
target = target.parent;
} while (target != null && target != currentTarget!.parent);
throw new StateError('No selector matched for populating matchedTarget.');
}
metaKey no setter override#
True if the Meta (or Mac command) key is pressed during this event.
Implementation
bool get metaKey => _parent.metaKey;
path no setter inherited#
Inherited from _WrappedEvent.
Implementation
// https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#extensions-to-event
List<Node> get path => wrapped.path as List<Node>;
repeat no setter override#
Implementation
bool get repeat => throw new UnimplementedError();
runtimeType no setter inherited#
A representation of the runtime type of the object.
Inherited from Object.
Implementation
external Type get runtimeType;
shiftKey no setter override#
True if the shift key was pressed during this event.
Implementation
bool get shiftKey => _parent.shiftKey;
sourceCapabilities no setter override#
Implementation
InputDeviceCapabilities? get sourceCapabilities =>
JS('InputDeviceCapabilities', '#.sourceCapabilities', this);
target no setter inherited#
Inherited from _WrappedEvent.
Implementation
EventTarget? get target => wrapped.target;
timeStamp no setter inherited#
Inherited from _WrappedEvent.
Implementation
double get timeStamp => wrapped.timeStamp as double;
type no setter inherited#
Inherited from _WrappedEvent.
Implementation
String get type => wrapped.type;
view no setter override#
Implementation
WindowBase? get view => _parent.view;
which no setter override#
Calculated value of what the estimated keyCode is for this event.
Implementation
int get which => keyCode;
wrapped final inherited#
Inherited from _WrappedEvent.
Implementation
final Event wrapped;
Methods#
composedPath() inherited#
Inherited from _WrappedEvent.
Implementation
List<EventTarget> composedPath() => wrapped.composedPath();
getModifierState() override#
Implementation
bool getModifierState(String keyArgument) => throw new UnimplementedError();
noSuchMethod() inherited#
Invoked when a nonexistent method or property is accessed.
A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:
dynamic object = 1;
object.add(42); // Statically allowed, run-time error
This invalid code will invoke the noSuchMethod method
of the integer 1 with an Invocation
representing the
.add(42) call and arguments (which then throws).
Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.
A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:
class MockList<T> implements List<T> {
noSuchMethod(Invocation invocation) {
log(invocation);
super.noSuchMethod(invocation); // Will throw.
}
}
void main() {
MockList().add(42);
}
This code has no compile-time warnings or errors even though
the MockList class has no concrete implementation of
any of the List interface methods.
Calls to List methods are forwarded to noSuchMethod,
so this code will log an invocation similar to
Invocation.method(#add, [42])
and then throw.
If a value is returned from noSuchMethod,
it becomes the result of the original invocation.
If the value is not of a type that can be returned by the original
invocation, a type error occurs at the invocation.
The default behavior is to throw a NoSuchMethodError.
Inherited from Object.
Implementation
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);
preventDefault() inherited#
Inherited from _WrappedEvent.
Implementation
void preventDefault() {
wrapped.preventDefault();
}
stopImmediatePropagation() inherited#
Inherited from _WrappedEvent.
Implementation
void stopImmediatePropagation() {
wrapped.stopImmediatePropagation();
}
stopPropagation() inherited#
Inherited from _WrappedEvent.
Implementation
void stopPropagation() {
wrapped.stopPropagation();
}
toString() inherited#
A string representation of this object.
Some classes have a default textual representation,
often paired with a static parse function (like int.parse).
These classes will provide the textual representation as
their string representation.
Other classes have no meaningful textual representation
that a program will care about.
Such classes will typically override toString to provide
useful information when inspecting the object,
mainly for debugging or logging.
Inherited from Object.
Implementation
external String toString();
Operators#
operator ==() inherited#
The equality operator.
The default behavior for all Objects is to return true if and
only if this object and other are the same object.
Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects
o,o == omust be true.-
Symmetric: For all objects
o1ando2,o1 == o2ando2 == o1must either both be true, or both be false. -
Transitive: For all objects
o1,o2, ando3, ifo1 == o2ando2 == o3are true, theno1 == o3must be true.
The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.
If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.
Inherited from Object.
Implementation
external bool operator ==(Object other);
Static Properties#
canUseDispatchEvent no setter#
Implementation
static bool get canUseDispatchEvent => JS(
'bool',
'(typeof document.body.dispatchEvent == "function")'
'&& document.body.dispatchEvent.length > 0',
);
keyDownEvent read / write#
getter:
Accessor to provide a stream of KeyEvents on the desired target.
setter:
Accessor to provide a stream of KeyEvents on the desired target.
Implementation
static EventStreamProvider<KeyEvent> keyDownEvent = new _KeyboardEventHandler(
'keydown',
);
keyPressEvent read / write#
getter:
Accessor to provide a stream of KeyEvents on the desired target.
setter:
Accessor to provide a stream of KeyEvents on the desired target.
Implementation
static EventStreamProvider<KeyEvent> keyPressEvent =
new _KeyboardEventHandler('keypress');
keyUpEvent read / write#
getter:
Accessor to provide a stream of KeyEvents on the desired target.
setter:
Accessor to provide a stream of KeyEvents on the desired target.
Implementation
static EventStreamProvider<KeyEvent> keyUpEvent = new _KeyboardEventHandler(
'keyup',
);