Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add capability for KeyboardEvent.code + capture #291

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions examples/example-keyboard-capture/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!--
~ Copyright (c) Jupyter Development Team.
~ Distributed under the terms of the Modified BSD License.
-->

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="build/bundle.example.js"></script>
</head>
<body>
</body>
</html>
21 changes: 21 additions & 0 deletions examples/example-keyboard-capture/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "@lumino/example-keyboard-capture",
"version": "2.0.0",
"private": true,
"scripts": {
"build": "tsc && rollup -c",
"clean": "rimraf build"
},
"dependencies": {
"@lumino/signaling": "^2.1.3",
"@lumino/widgets": "^2.6.0"
},
"devDependencies": {
"@lumino/messaging": "^2.0.2",
"@rollup/plugin-node-resolve": "^15.0.1",
"rimraf": "^5.0.1",
"rollup": "^3.25.1",
"rollup-plugin-styles": "^4.0.0",
"typescript": "~5.1.3"
}
}
8 changes: 8 additions & 0 deletions examples/example-keyboard-capture/rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* Copyright (c) Jupyter Development Team.
* Distributed under the terms of the Modified BSD License.
*/

import { createRollupExampleConfig } from '@lumino/buildutils';
const rollupConfig = createRollupExampleConfig();
export default rollupConfig;
154 changes: 154 additions & 0 deletions examples/example-keyboard-capture/src/capture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { KeycodeLayout } from '@lumino/keyboard';
import { Message } from '@lumino/messaging';
import { ISignal, Signal } from '@lumino/signaling';
import { Widget } from '@lumino/widgets';

/**
* A widget for capturing a keyboard layout.
*/
export class CaptureWidget extends Widget {
/**
*
*/
constructor(options?: Widget.IOptions) {
super(options);
this.addClass('lm-keyboardCaptureArea');
if (!options || !options.node) {
this.node.tabIndex = 0;
}
}

extractLayout(name: string): KeycodeLayout {
return new KeycodeLayout(
name,
this._keyCodeMap,
Array.from(this._modifierKeys),
this._codeMap
);
}

formatMap(): string {
return `codes: ${Private.formatCodeMap(
this._codeMap
)}\n\nmodifiers: [${Array.from(this._modifierKeys)
.map(k => `"${k}"`)
.sort()
.join(', ')}]${
Private.isCodeMapEmpty(this._keyCodeMap)
? ''
: `\n\nkeyCodes${Private.formatCodeMap(this._keyCodeMap)}`
}`;
}

clear(): void {
this._codeMap = {};
this._keyCodeMap = {};
this._modifierKeys.clear();
}

node: HTMLInputElement;

get dataAdded(): ISignal<this, CaptureWidget.Entry> {
return this._dataAdded;
}

/**
* Handle the DOM events for the widget.
*
* @param event - The DOM event sent to the element.
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'keydown':
this._onKeyDown(event as KeyboardEvent);
break;
case 'keyup':
this._onKeyUp(event as KeyboardEvent);
break;
}
}

/**
* A message handler invoked on a `'before-attach'` message.
*/
protected onBeforeAttach(msg: Message): void {
this.node.addEventListener('keydown', this);
this.node.addEventListener('keyup', this);
super.onBeforeAttach(msg);
}

/**
* A message handler invoked on an `'after-detach'` message.
*/
protected onAfterDetach(msg: Message): void {
super.onAfterDetach(msg);
this.node.removeEventListener('keydown', this);
this.node.removeEventListener('keyup', this);
}

private _onKeyDown(event: KeyboardEvent): void {
event.stopPropagation();
event.preventDefault();
if (event.getModifierState(event.key)) {
this._modifierKeys.add(event.key);
this._dataAdded.emit({ key: event.key, type: 'modifier' });
}
}

private _onKeyUp(event: KeyboardEvent): void {
event.stopPropagation();
event.preventDefault();
if (event.getModifierState(event.key)) {
this._modifierKeys.add(event.key);
this._dataAdded.emit({ key: event.key, type: 'modifier' });
return;
}
let { key, code } = event;
if (key === 'Dead') {
console.log('Dead key', event);
return;
}
if ((!code || code === 'Unidentified') && event.keyCode) {
console.log('Unidentified code', event);
this._keyCodeMap[event.keyCode] = key;
this._dataAdded.emit({ key, code: event.keyCode, type: 'keyCode' });
} else {
this._codeMap[code] = key;
this._dataAdded.emit({ key, code, type: 'code' });
}
}

private _codeMap: { [key: string]: string } = {};
private _keyCodeMap: { [key: number]: string } = {};
private _modifierKeys: Set<string> = new Set();
private _dataAdded = new Signal<this, CaptureWidget.Entry>(this);
}

namespace CaptureWidget {
export type Entry = { type: string; code?: string | number; key: string };
}

namespace Private {
export function isCodeMapEmpty(
codemap: { [key: string]: string } | { [key: number]: string }
): boolean {
return !Object.keys(codemap).length;
}
export function formatCodeMap(
codemap: { [key: string]: string } | { [key: number]: string }
): string {
return `{\n${Object.keys(codemap)
.sort()
.map(
k =>
` "${k}": "${
(codemap as any)[k] &&
(codemap as any)[k][0].toUpperCase() + (codemap as any)[k].slice(1)
}"`
)
.join(',\n')}\n}`;
}
}
49 changes: 49 additions & 0 deletions examples/example-keyboard-capture/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { Panel, Widget } from '@lumino/widgets';
import { CaptureWidget } from './capture';
import { OutputWidget } from './output';

import '../style/index.css';

/**
* Initialize the applicaiton.
*/
async function init(): Promise<void> {
// Add the text editors to a dock panel.
let capture = new CaptureWidget();
let output = new OutputWidget();

capture.node.textContent =
'Focus me and hit each key on your keyboard without any modifiers';

// Add the dock panel to the document.
let box = new Panel();
box.id = 'main';
box.addWidget(capture);
box.addWidget(output);

capture.dataAdded.connect((sender, entry) => {
output.value = `Added ${entry.type}: ${
entry.code ? `${entry.code} →` : ''
} <kbd>${entry.key}</kbd>`;
});
output.action.connect((sender, action) => {
if (action === 'clipboard') {
navigator.clipboard.writeText(capture.formatMap());
} else if (action === 'clear') {
capture.clear();
output.value = ' ';
} else {
output.value = `<pre>${capture.formatMap()}</pre>`;
}
});

window.onresize = () => {
box.update();
};
Widget.attach(box, document.body);
}

window.onload = init;
83 changes: 83 additions & 0 deletions examples/example-keyboard-capture/src/output.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { Message } from '@lumino/messaging';
import { ISignal, Signal } from '@lumino/signaling';
import { Widget } from '@lumino/widgets';

export class OutputWidget extends Widget {
/**
*
*/
constructor(options?: Widget.IOptions) {
super(options);
this._output = document.createElement('div');
this._exportButton = document.createElement('button');
this._exportButton.innerText = 'Show';
this._copyButton = document.createElement('button');
this._copyButton.innerText = 'Copy';
this._clearButton = document.createElement('button');
this._clearButton.innerText = 'Clear';
this.node.appendChild(this._exportButton);
this.node.appendChild(this._copyButton);
this.node.appendChild(this._clearButton);
this.node.appendChild(this._output);
this.addClass('lm-keyboardCaptureOutputArea');
}

set value(content: string) {
this._output.innerHTML = content;
}

get action(): ISignal<this, 'display' | 'clipboard' | 'clear'> {
return this._action;
}

/**
* Handle the DOM events for the widget.
*
* @param event - The DOM event sent to the element.
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'click':
if (event.target === this._exportButton) {
event.stopPropagation();
this._action.emit('display');
} else if (event.target === this._copyButton) {
event.stopPropagation();
this._action.emit('clipboard');
} else if (event.target === this._clearButton) {
event.stopPropagation();
this._action.emit('clear');
}
break;
}
}

/**
* A message handler invoked on a `'before-attach'` message.
*/
protected onBeforeAttach(msg: Message): void {
this._exportButton.addEventListener('click', this);
this._copyButton.addEventListener('click', this);
this._clearButton.addEventListener('click', this);
super.onBeforeAttach(msg);
}

/**
* A message handler invoked on an `'after-detach'` message.
*/
protected onAfterDetach(msg: Message): void {
super.onAfterDetach(msg);
this._exportButton.removeEventListener('click', this);
this._copyButton.removeEventListener('click', this);
this._clearButton.removeEventListener('click', this);
}

private _output: HTMLElement;
private _exportButton: HTMLButtonElement;
private _copyButton: HTMLButtonElement;
private _clearButton: HTMLButtonElement;
private _action = new Signal<this, 'display' | 'clipboard' | 'clear'>(this);
}
58 changes: 58 additions & 0 deletions examples/example-keyboard-capture/style/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright (c) Jupyter Development Team.
* Distributed under the terms of the Modified BSD License.
*/

/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
@import '~@lumino/widgets/style/index.css';

body {
display: flex;
flex-direction: column;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: 0;
padding: 0;
}

#main {
flex: 1 1 auto;
overflow: auto;
padding: 10px;
}

.lm-keyboardCaptureArea {
border-radius: 5px;
border: 3px dashed #88a;
padding: 6px;
margin: 6px;
}

.lm-keyboardCaptureOutputArea kbd {
background-color: #eee;
border-radius: 5px;
border: 3px solid #b4b4b4;
box-shadow:
0 1px 1px rgba(0, 0, 0, 0.2),
0 2px 0 0 rgba(255, 255, 255, 0.7) inset;
color: #333;
display: inline-block;
font-size: 0.85em;
font-weight: 700;
line-height: 1;
padding: 2px 4px;
white-space: nowrap;
}

.lm-keyboardCaptureOutputArea button {
margin: 4px;
}
Loading
Loading