Compare commits

..
33 Commits
Author SHA1 Message Date
Francisco Hodge 0c76aef3fb Fix typo 2018-04-12 12:34:43 -04:00
Francisco Hodge d1eabe0167 npm version update 2018-04-12 12:25:41 -04:00
Francisco Hodge 988b8a0f64 Setting newLineOnEnter false by default 2018-04-12 12:25:10 -04:00
Francisco Hodge a097b0f470 Removing service worker 2018-04-12 12:24:13 -04:00
Francisco Hodge 073a6d467e README and package.json changes 2018-03-16 10:30:05 -04:00
Francisco Hodge 0087765e48 Bump npm version 2018-03-16 09:55:34 -04:00
Francisco Hodge 21072757cd Adding README tweaks 2018-03-16 09:54:34 -04:00
Francisco Hodge 89b0987a34 Minor index tweak for demos 2018-03-16 09:54:13 -04:00
Francisco Hodge a7f25df1ac Updating favicon 2018-03-16 09:53:58 -04:00
Francisco Hodge e94669ac06 Improving README 2018-03-15 16:39:22 -04:00
Francisco Hodge 7e09513534 Update npm version 2018-03-15 16:29:16 -04:00
Francisco Hodge 960537d7a6 Improving README 2018-03-15 16:28:24 -04:00
Francisco Hodge d88be11a42 Improving readme 2018-03-15 13:28:15 -04:00
Francisco Hodge e2ee5a4158 Update npm version 2018-03-15 13:10:14 -04:00
Francisco Hodge 4b162eaec7 normalizeString update. Added support for tab, enter. Support for newLineOnEnter prop 2018-03-15 13:09:29 -04:00
Francisco Hodge 715a9c4a90 Adding clearInput, getInput, setInput, newLineOnEnter functionality 2018-03-15 13:08:18 -04:00
Francisco Hodge df32ed440e Update default keyboard style 2018-03-15 13:07:40 -04:00
Francisco Hodge 12fe2cca75 Adding demo images 2018-03-15 13:07:22 -04:00
Francisco Hodge dddd45a220 Adding more functionality examples to demo 2018-03-15 13:07:10 -04:00
Francisco Hodge 857942811c Readme changes with demo 2018-03-15 13:06:49 -04:00
Francisco Hodge 832ecbaa2c Adding prepublish to package.json 2018-03-08 10:55:04 -05:00
Francisco Hodge ad5284ceb3 Update npm version 2018-03-08 10:40:51 -05:00
Francisco Hodge 9a47421260 Improved README 2018-03-08 10:40:30 -05:00
Francisco Hodge d27b94c6d9 Fixing emptybutton issue, updating README 2018-03-02 15:45:40 -05:00
Francisco Hodge e1cfcdd673 Renaming base class 2018-03-02 15:20:48 -05:00
Francisco Hodge 3c3a049b3f npm version bump 2018-03-02 14:59:43 -05:00
Francisco Hodge a8c5ffd401 Fix layout class display, license adjustment 2018-03-02 14:48:57 -05:00
Francisco Hodge d06baf7222 README update 2018-03-02 13:54:49 -05:00
Francisco Hodge afbdddb008 Updating package.json links 2018-03-02 13:53:19 -05:00
Francisco Hodge 41b1ae2941 Updating README, fixing minor bugs 2018-03-02 13:33:06 -05:00
Francisco Hodge e7411c6845 Merge branch 'master' of https://github.com/hodgef/simple-keyboard 2018-03-02 11:32:53 -05:00
Francisco Hodge 4f1111b49e First commit 2018-03-02 11:31:12 -05:00
Francisco HodgeandGitHub a47a855912 Initial commit 2018-03-02 11:25:36 -05:00
34 changed files with 3122 additions and 7143 deletions
-17
View File
@@ -1,17 +0,0 @@
---
name: Bug report
about: Create a report to help improve simple-keyboard
---
** simple-keyboard version you are using **
As some bugs have been addressed in later versions, please ensure you are running the latest.
**Describe the bug**
A clear and concise description of what the bug is.
**Create a sandbox example**
Edit [this sandbox example](https://codesandbox.io/s/krzkx19rr) and provide the new link.
**Screenshots**
If applicable, add screenshots to help explain your problem.
-17
View File
@@ -1,17 +0,0 @@
---
name: Feature request
about: Suggest an idea you'd like to see in simple-keyboard
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
-4
View File
@@ -1,4 +0,0 @@
# About .github
This directory handles special features to be used on simple-keyboard's Github repository.
It is not needed for simple-keyboard to run and can be safely removed.
+1
View File
@@ -4,6 +4,7 @@
/node_modules
# production
/build
/demo
# testing
+1 -13
View File
@@ -1,17 +1,5 @@
language: node_js
node_js:
- "node"
install:
- npm install -g codecov
- npm install
script:
- npm run test -- --coverage
- codecov
after_success:
- wget https://raw.githubusercontent.com/DiscordHooks/travis-ci-discord-webhook/master/send.sh
- chmod +x send.sh
- ./send.sh success $WEBHOOK_URL
after_failure:
- wget https://raw.githubusercontent.com/DiscordHooks/travis-ci-discord-webhook/master/send.sh
- chmod +x send.sh
- ./send.sh failure $WEBHOOK_URL
- npm run test
+73 -488
View File
@@ -1,107 +1,58 @@
[![npm version](https://badge.fury.io/js/simple-keyboard.svg)](https://www.npmjs.com/package/simple-keyboard)
[![Build Status](https://travis-ci.org/hodgef/simple-keyboard.svg?branch=master)](https://travis-ci.org/hodgef/simple-keyboard)
[![codecov](https://codecov.io/gh/hodgef/simple-keyboard/branch/master/graph/badge.svg)](https://codecov.io/gh/hodgef/simple-keyboard)
[![](https://img.shields.io/badge/discord--chat-join-green.svg?longCache=true&style=flat-square&colorB=7289DA&logo=discord)](http://franciscohodge.com/simple-keyboard/chat/join)
# simple-keyboard
<a href="https://franciscohodge.com/simple-keyboard/demo" title="View Demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/simplekeyboard-banner_B.png" align="center" width="100%"></a>
<a href="https://franciscohodge.com/simple-keyboard/demo" title="View Demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/simple-keyboard-240-demo-2.gif" align="center" width="100%"></a>
[![npm](https://img.shields.io/npm/v/simple-keyboard.svg)](https://www.npmjs.com/package/simple-keyboard)
[![Dependencies](https://img.shields.io/david/hodgef/simple-keyboard.svg)](https://www.npmjs.com/package/simple-keyboard)
[![npm downloads](https://img.shields.io/npm/dm/simple-keyboard.svg)](https://www.npmjs.com/package/simple-keyboard)
> The easily customisable and responsive on-screen virtual keyboard for Javascript projects.
<a href="https://franciscohodge.com/projects/simple-keyboard/"><img src="src/demo/images/simple-keyboard.png" align="center"></a>
> An easily customisable and responsive on-screen virtual keyboard for React.js projects.
This package works with <a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard" title="View Vanilla JS Demo" target="_blank">**Vanilla JS**</a> projects, yet it is also compatible with <a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_angular-js" title="View Angular Demo" target="_blank">**Angular**</a>, <a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_vue-js" title="View Vue Demo" target="_blank">**Vue**</a>, and other libraries and frameworks.
<img src="src/demo/images/keyboard.PNG" align="center" width="100%">
<b>[Live Demo](https://franciscohodge.com/simple-keyboard/demo)</b>
Looking for **React** support? Check out [react-simple-keyboard](https://www.npmjs.com/package/react-simple-keyboard) !
## Installation
### npm
`npm install simple-keyboard --save`
### zip file (self-hosted)
[Click here to download the latest release (zip format).](https://github.com/hodgef/simple-keyboard/zipball/master)
> Want to use a CDN instead of self-host? Scroll down to the "Usage with CDN" instructions below.
## Usage with npm
### js
## Usage
````js
import React, {Component} from 'react';
import Keyboard from 'simple-keyboard';
import 'simple-keyboard/build/css/index.css';
let keyboard = new Keyboard({
onChange: input => onChange(input),
onKeyPress: button => onKeyPress(button)
});
class App extends Component {
function onChange(input){
document.querySelector(".input").value = input;
console.log("Input changed", input);
onChange = (input) => {
console.log("Input changed", input);
}
onKeyPress = (button) => {
console.log("Button pressed", button);
}
render(){
return (
<Keyboard
onChange={input =>
this.onChange(input)}
onKeyPress={button =>
this.onKeyPress(button)}
/>
);
}
}
function onKeyPress(button){
console.log("Button pressed", button);
}
export default App;
````
### html
````html
<input class="input" />
<div class="simple-keyboard"></div>
````
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
## Usage with CDN
### html
````html
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/simple-keyboard@latest/build/css/index.css">
</head>
<body>
<input class="input" placeholder="Tap on the virtual keyboard to start" />
<div class="simple-keyboard"></div>
<script src="https://cdn.jsdelivr.net/npm/simple-keyboard@latest/build/index.min.js"></script>
<script src="src/index.js"></script>
</body>
</html>
````
### js (index.js)
````js
let Keyboard = window.SimpleKeyboard.default;
let myKeyboard = new Keyboard({
onChange: input => onChange(input),
onKeyPress: button => onKeyPress(button)
});
function onChange(input) {
document.querySelector(".input").value = input;
console.log("Input changed", input);
}
function onKeyPress(button) {
console.log("Button pressed", button);
}
````
<a href="https://codesandbox.io/s/github/hodgef/demo_cdn_simple-keyboard" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
> Need a more extensive example? [Click here](https://github.com/hodgef/simple-keyboard/blob/master/src/demo/App.js).
## Options
You can customize the Keyboard by passing options to it.
You can customize the Keyboard by passing options (props) to it.
Here are the available options (the code examples are the defaults):
### layout
@@ -109,7 +60,7 @@ Here are the available options (the code examples are the defaults):
> Modify the keyboard layout
```js
layout: {
layout={{
'default': [
'` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
'{tab} q w e r t y u i o p [ ] \\',
@@ -124,90 +75,49 @@ layout: {
'{shift} Z X C V B N M < > ? {shift}',
'.com @ {space}'
]
}
}}
```
> Looking for keyboard layouts in other languages? **Check out [simple-keyboard-layouts](https://github.com/hodgef/simple-keyboard-layouts) !**
### layoutName
> Specifies which layout should be used.
```js
layoutName: "default"
layoutName={"default"}
```
### display
> Replaces variable buttons (such as `{bksp}`) with a human-friendly name (e.g.: "backspace").
> Replaces variable buttons (such as `{bksp}`) with a human-friendly name (e.g.: "delete").
```js
display: {
'{bksp}': 'backspace',
display={{
'{bksp}': 'delete',
'{enter}': '< enter',
'{shift}': 'shift',
...
}
```
### mergeDisplay
By default, when you set the `display` property, you replace the default one. This setting merges them instead.
```js
mergeDisplay: true,
display: {
'{bksp}': 'delete',
'{enter}': 'submit',
}
// Result:
{
'{bksp}': 'delete'
'{enter}': 'submit',
'{shift}': 'shift', // < Merged from default among others
....
}
'{s}': 'shift',
'{tab}': 'tab',
'{lock}': 'caps',
'{accept}': 'Submit',
'{space}': ' ',
'{//}': ' '
}}
```
### theme
> A prop to add your own css classes _to the keyboard wrapper_. You can add multiple classes separated by a space.
> A prop to add your own css classes. You can add multiple classes separated by a space.
```js
theme: "hg-theme-default"
theme={"hg-theme-default"}
```
### buttonTheme
A prop to add your own css classes _to one or several buttons_.
To add or remove individual `buttonTheme` entries, check out the methods `addButtonTheme` and `removeButtonTheme` below.
```js
buttonTheme: [
{
class: "myCustomClass",
buttons: "Q W E R T Y q w e r t y"
},
{
class: "anotherCustomClass",
buttons: "Q q"
},
...
]
```
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_customization" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### debug
> Runs a console.log every time a key is pressed. Displays the buttons pressed and the current input.
```js
debug: false
debug={false}
```
### newLineOnEnter
@@ -215,137 +125,22 @@ debug: false
> Specifies whether clicking the "ENTER" button will input a newline (`\n`) or not.
```js
newLineOnEnter: false
```
### tabCharOnTab
> Specifies whether clicking the "TAB" button will input a tab character (`\t`) or not.
```js
tabCharOnTab: true
```
### inputName
> Allows you to use a single simple-keyboard instance for several inputs.
```js
inputName: "default"
```
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_multiple-inputs" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### maxLength
> Restrains simple-keyboard's input to a certain length. This should be used in addition to the input element's `maxlength` attribute.
```js
// Applies to all internal inputs
maxLength: 5
// Specifies different limiters for each input set, in case you are using the "inputName" option
maxLength: {
'default': 5,
'myFancyInput': 10
}
```
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_max-length" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### syncInstanceInputs
> When set to true, this option synchronizes the internal input of every simple-keyboard instance.
```js
syncInstanceInputs: false
```
### physicalKeyboardHighlight
Enable highlighting of keys pressed on physical keyboard.
For functional keys such as `shift`, note that the key's `event.code` is used. In that instance, pressing the left key will result in the code `ShiftLeft`. Therefore, the key must be named `{shiftleft}`.
[Click here](https://github.com/hodgef/simple-keyboard/blob/master/src/lib/services/Utilities.js#L58) for some of keys supported out of the box.
If in doubt, you can also set the `debug` option to `true` to see the key events.
```js
physicalKeyboardHighlight: true
```
<a href="https://codesandbox.io/s/github/hodgef/demo_cdn_simple-keyboard_extended-full-keyboard" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### physicalKeyboardHighlightTextColor
Define the text color that the physical keyboard highlighted key should have. Used when `physicalKeyboardHighlight` is set to true.
```js
physicalKeyboardHighlightTextColor: "white"
```
### physicalKeyboardHighlightBgColor
Define the background color that the physical keyboard highlighted key should have. Used when `physicalKeyboardHighlight` is set to true.
```js
physicalKeyboardHighlightBgColor: "#9ab4d0"
```
### onKeyPress
> Executes the callback function on key press. Returns button layout name (i.e.: "{shift}").
```js
onKeyPress: (button) => console.log(button)
```
### onChange
> Executes the callback function on input change. Returns the current input's string.
```js
onChange: (input) => console.log(input)
```
### onRender
> Executes the callback function every time simple-keyboard is rendered (e.g: when you change layouts).
```js
onRender: () => console.log("simple-keyboard refreshed")
```
### onInit
> Executes the callback function once simple-keyboard is rendered for the first time (on initialization).
```js
onInit: () => console.log("simple-keyboard initialized")
```
### onChangeAll
> Executes the callback function on input change. Returns the input object with all defined inputs. This is useful if you're handling several inputs with simple-keyboard, as specified in the "*[Using several inputs](#using-several-inputs)*" guide.
```js
onChangeAll: (inputs) => console.log(inputs)
newLineOnEnter={false}
```
## Methods
simple-keyboard has a few methods you can use to further control it's behavior.
To access these functions, you need the instance the simple-keyboard component, like so:
simple-keybord has a few methods you can use to further control it's behavior.
To access these functions, you need a `ref` of the simple-keyboard component, like so:
```js
var keyboard = new Keyboard({
...
});
<Keyboard
ref={r => this.keyboard = r}
[...]
/>
// Then, use as follows...
keyboard.methodName(params);
// Then, on componentDidMount ..
this.keyboard.methodName(params);
```
### clearInput
@@ -353,12 +148,7 @@ keyboard.methodName(params);
> Clear the keyboard's input.
```js
// For default input (i.e. if you have only one)
keyboard.clearInput();
// For specific input
// Must have been previously set using the "inputName" prop.
keyboard.clearInput("myInputName");
this.keyboard.clearInput();
```
### getInput
@@ -366,231 +156,34 @@ keyboard.clearInput("myInputName");
> Get the keyboard's input (You can also get it from the _onChange_ prop).
```js
// For default input (i.e. if you have only one)
let input = keyboard.getInput();
// For specific input
// Must have been previously set using the "inputName" prop.
let input = keyboard.getInput("myInputName");
let input = this.keyboard.getInput();
```
### setInput
> Set the keyboard's input. Useful if you want to track input changes made outside simple-keyboard.
> Set the keyboard's input. Useful if you want the keybord to initialize with a default value, for example.
```js
// For default input (i.e. if you have only one)
keyboard.setInput("Hello World!");
// For specific input
// Must have been previously set using the "inputName" prop.
keyboard.setInput("Hello World!", "myInputName");
this.keyboard.setInput("Hello World!");
```
### setOptions
> Set new option or modify existing ones after initialization. The changes are applied immediately.
It returns a promise, so if you want to run something after it's applied, call it as so:
```js
keyboard.setOptions({
theme: "my-custom-theme"
let inputSetPromise = this.keyboard.setInput("Hello World!");
inputSetPromise.then((result) => {
console.log("Input set");
});
```
### dispatch
> Send a command to all simple-keyboard instances at once (if you have multiple instances).
```js
keyboard.dispatch(instance => {
instance.setOptions({
buttonTheme: [
{
class: "myClass",
buttons: `a b c`
}
]
})
});
```
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_dispatch-method" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### getButtonElement
> Get the DOM Element of a button. If there are several buttons with the same name, an array of the DOM Elements is returned.
```js
this.keyboard.getButtonElement('a'); // Gets the "a" key as per your layout
this.keyboard.getButtonElement('{shift}') // Gets all keys with that name in an array
```
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_get-button-element" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### addButtonTheme
Adds an entry to the `buttonTheme`. Basically a way to add a class to a button.
Unlike the `buttonTheme` property, which replaces entries, `addButtonTheme` creates entries or modifies existing ones.
```js
this.keyboard.addButtonTheme("a b c {enter}", "myClass1 myClass2");
```
### removeButtonTheme
Removes an entry to the `buttonTheme`. Basically a way to remove a class previously added to a button through `buttonTheme` or `addButtonTheme`.
Unlike the `buttonTheme` property, which replaces entries, `removeButtonTheme` removes entries or modifies existing ones.
```js
this.keyboard.removeButtonTheme("b c", "myClass1 myClass2");
```
## Q&A / Use-cases
### How to give a different base class to my keyboard
As you may have seen on the code samples, this is the default setup that simple-keyboard uses:
```html
<div class="simple-keyboard"></div>
```
```js
let keyboard = new Keyboard({
// Add options here
});
```
You can however change this by setting up simple-keyboard like so:
```html
<div class="myFavouriteClass"></div>
```
```js
let keyboard = new Keyboard(".myFavouriteClass", {
// Add options here
});
```
This can come in handy especially when dealing with multiple simple keyboard instances.
### How to syncronize multiple instances of simple-keyboard
As shown above, you can run multiple instances of simple-keyboard. To keep their internal inputs in sync, set the *[syncInstanceInputs](#syncinstanceinputs)* option to `true`.
If you want to send a command to all your simple-keyboard instances at once, you can use the *[dispatch](#dispatch)* method.
Here's a demo with both these features in action:
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_dispatch-method" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
Here's an example of a full keyboard made out of multiple simple-keyboard instances:
<a href="https://codesandbox.io/s/github/hodgef/demo_cdn_simple-keyboard_extended-full-keyboard" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### Using several inputs
Set the *[inputName](#inputname)* option for each input you want to handle with simple-keyboard.
For example:
```html
<input class="input" id="input1" value=""/>
<input class="input" id="input2" value=""/>
```
```js
// Here we'll store the input id that simple-keyboard will be using.
var selectedInput;
// Initialize simple-keyboard as usual
var keyboard = new Keyboard({
onChange: input => onChange(input)
});
// Add an event listener for the inputs to be tracked
document.querySelectorAll('.input')
.forEach(input => input.addEventListener('focus', onInputFocus));
/**
* When an input is focused, it will be marked as selected (selectedInput)
* This is so we can replace it's value on the onChange function
*
* Also, we will set the inputName option to a unique string identifying the input (id)
* simple-keyboard save the input in this key and report changes through onChange
*/
onInputFocus = event => {
// Setting input as selected
selectedInput = `#${event.target.id}`;
// Set the inputName option on the fly !
keyboard.setOptions({
inputName: event.target.id
});
}
// When the current input is changed, this is called
onChange = input => {
// If the input is not defined, grabbing the first ".input".
let currentInput = selectedInput || '.input';
// Updating the selected input's value
document.querySelector(currentInput).value = input;
}
```
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_multiple-inputs" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### Having keys in a different language configuration
There's a number of key layouts available. To apply them, check out [simple-keyboard-layouts](https://github.com/hodgef/simple-keyboard-layouts).
If you'd like to contribute your own layouts, please submit your pull request at the simple-keyboard-layouts repository.
### How to customize my keyboard layout
If you'd like to create a layout in a language not currently supported by [simple-keyboard-layouts](https://github.com/hodgef/simple-keyboard-layouts), you definitely can.
Take following demo as an example:
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_customization" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
If you have issues displaying a character, you might need its unicode code to display it. Here an useful converter tool:
[r12a Unicode converter](https://r12a.github.io/app-conversion/)
### Why is the caps lock button working like shift button
For the sake of simplicity, caps lock and shift do the same action in the main demos.
If you'd like to show a different layout when you press caps lock, check out the following demo:
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard_handling-shift-caps-lock" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### How to display a full keyboard
You can display a full keyboard by linking together multiple Simple Keyboard instances.
This is because you might want different sections of your keyboard to have different spacing and styling.
Please refer to the documentation on the *[syncInstanceInputs](#syncInstanceInputs)* option, which allows you to sync the input of all your simple-keyboard instances.
Also, check out this demo:
<a href="https://codesandbox.io/s/github/hodgef/demo_cdn_simple-keyboard_extended-full-keyboard" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
## Demo
[https://franciscohodge.com/simple-keyboard/demo](https://franciscohodge.com/simple-keyboard/demo)
<img src="src/demo/images/demo.gif" align="center" width="600">
<a href="https://codesandbox.io/s/github/hodgef/demo_npm_simple-keyboard" title="run demo" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/rundemo200.png" width="150" align="center"></a>
### Live demo
[https://franciscohodge.com/simple-keyboard/demo](https://franciscohodge.com/simple-keyboard/demo)
### To run demo on your own computer
@@ -599,15 +192,7 @@ Also, check out this demo:
* `npm start`
* Visit [http://localhost:3000/](http://localhost:3000/)
### Other versions
## Note
* ReactJS - [react-simple-keyboard](https://github.com/hodgef/react-simple-keyboard)
### Questions?
<a href="http://franciscohodge.com/simple-keyboard/chat/join" title="Join our Discord chat" target="_blank"><img src="https://franciscohodge.com/project-pages/simple-keyboard/images/discord.png" align="center" width="200"></a>
## Contributing
PR's and issues are welcome. Feel free to submit any issues you have at:
This is a work in progress. Feel free to submit any issues you have at:
[https://github.com/hodgef/simple-keyboard/issues](https://github.com/hodgef/simple-keyboard/issues)
-10
View File
@@ -1,10 +0,0 @@
console.log('\x1b[36m%s\x1b[0m', `
______________________________________\n`);
console.log('\x1b[33m%s\x1b[0m', `Thank you for installing simple-keyboard !`);
console.log('\x1b[36m%s\x1b[0m', `
Please consider starring the repository so others can also find it.
https://github.com/hodgef/simple-keyboard/stargazers
______________________________________
`);
-13
View File
@@ -1,13 +0,0 @@
/*!
*
* simple-keyboard v2.6.0
* https://github.com/hodgef/simple-keyboard
*
* Copyright (c) Francisco Hodge (https://github.com/hodgef)
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
body,html{margin:0;padding:0}.simple-keyboard{font-family:HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;width:100%;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;-ms-touch-action:manipulation;touch-action:manipulation}.simple-keyboard .hg-row{display:-ms-flexbox;display:flex}.simple-keyboard .hg-row:not(:last-child){margin-bottom:5px}.simple-keyboard .hg-row .hg-button:not(:last-child){margin-right:5px}.simple-keyboard .hg-button{display:inline-block;-ms-flex-positive:1;flex-grow:1;cursor:pointer}.hg-standardBtn{max-width:100px}.simple-keyboard.hg-theme-default{background-color:rgba(0,0,0,.1);padding:5px;border-radius:5px}.simple-keyboard.hg-theme-default .hg-button{-webkit-box-shadow:0 0 3px -1px rgba(0,0,0,.3);box-shadow:0 0 3px -1px rgba(0,0,0,.3);height:40px;border-radius:5px;-webkit-box-sizing:border-box;box-sizing:border-box;padding:5px;background:#fff;border-bottom:1px solid #b5b5b5;cursor:pointer;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.simple-keyboard.hg-theme-default .hg-button:active{background:#e4e4e4}.simple-keyboard.hg-theme-default.hg-layout-numeric .hg-button{width:33.3%;height:60px;-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center}.simple-keyboard.hg-theme-default .hg-button.hg-button-numpadadd,.simple-keyboard.hg-theme-default .hg-button.hg-button-numpadenter{height:85px}.simple-keyboard.hg-theme-default .hg-button.hg-button-numpad0{width:105px}.simple-keyboard.hg-theme-default .hg-button.hg-button-com{max-width:85px}.simple-keyboard.hg-theme-default .hg-button.hg-standardBtn.hg-button-at{max-width:45px}.simple-keyboard.hg-theme-default .hg-button.hg-selectedButton{background:rgba(5,25,70,.53);color:#fff}
/*# sourceMappingURL=index.css.map*/
-1
View File
@@ -1 +0,0 @@
{"version":3,"sources":["webpack:///./src/lib/components/Keyboard.css"],"names":[],"mappings":";;;;;;;;;;;AAAA,UACE,SACA,SAAW,CAGb,iBACE,6GACA,WACA,yBACG,sBACC,qBACI,iBACR,8BACQ,sBACR,gBACA,8BACI,yBAA2B,CAGjC,yBACE,oBACA,YAAc,CAGhB,0CACE,iBAAmB,CAGrB,qDACE,gBAAkB,CAGpB,4BACE,qBACA,oBACI,YACJ,cAAgB,CAGlB,gBACE,eAAiB,CAMnB,kCACE,gCACA,YACA,iBAAmB,CAGrB,6CACE,+CACQ,uCACR,YACA,kBACA,8BACQ,sBACR,YACA,gBACA,gCACA,eACA,oBACA,aACA,sBACI,mBACJ,qBACI,sBAAwB,CAG7B,oDACC,kBAAoB,CAGtB,+DACE,YACA,YACA,sBACI,mBACJ,oBACA,aACA,qBACI,sBAAwB,CAO9B,oIACE,WAAa,CAGf,+DACE,WAAa,CAGf,2DACE,cAAgB,CAGlB,yEACE,cAAgB,CAGlB,+DACE,6BACA,UAAa","file":"css/index.css","sourcesContent":["body, html {\r\n margin: 0;\r\n padding: 0;\r\n}\r\n\r\n.simple-keyboard {\r\n font-family: \"HelveticaNeue-Light\", \"Helvetica Neue Light\", \"Helvetica Neue\", Helvetica, Arial, \"Lucida Grande\", sans-serif;\r\n width: 100%;\r\n -webkit-user-select: none;\r\n -moz-user-select: none;\r\n -ms-user-select: none;\r\n user-select: none;\r\n -webkit-box-sizing: border-box;\r\n box-sizing: border-box;\r\n overflow: hidden;\r\n -ms-touch-action: manipulation;\r\n touch-action: manipulation;\r\n}\r\n\r\n.simple-keyboard .hg-row {\r\n display: -ms-flexbox;\r\n display: flex;\r\n}\r\n\r\n.simple-keyboard .hg-row:not(:last-child) {\r\n margin-bottom: 5px;\r\n}\r\n\r\n.simple-keyboard .hg-row .hg-button:not(:last-child) {\r\n margin-right: 5px;\r\n}\r\n\r\n.simple-keyboard .hg-button {\r\n display: inline-block;\r\n -ms-flex-positive: 1;\r\n flex-grow: 1;\r\n cursor: pointer;\r\n}\r\n\r\n.hg-standardBtn {\r\n max-width: 100px;\r\n}\r\n\r\n/**\r\n * hg-theme-default theme\r\n */\r\n.simple-keyboard.hg-theme-default {\r\n background-color: rgba(0,0,0,0.1);\r\n padding: 5px;\r\n border-radius: 5px;\r\n }\r\n\r\n.simple-keyboard.hg-theme-default .hg-button {\r\n -webkit-box-shadow: 0px 0px 3px -1px rgba(0,0,0,0.3);\r\n box-shadow: 0px 0px 3px -1px rgba(0,0,0,0.3);\r\n height: 40px;\r\n border-radius: 5px;\r\n -webkit-box-sizing: border-box;\r\n box-sizing: border-box;\r\n padding: 5px;\r\n background: white;\r\n border-bottom: 1px solid #b5b5b5;\r\n cursor: pointer;\r\n display: -ms-flexbox;\r\n display: flex;\r\n -ms-flex-align: center;\r\n align-items: center;\r\n -ms-flex-pack: center;\r\n justify-content: center;\r\n }\r\n\r\n .simple-keyboard.hg-theme-default .hg-button:active {\r\n background: #e4e4e4;\r\n }\r\n\r\n.simple-keyboard.hg-theme-default.hg-layout-numeric .hg-button {\r\n width: 33.3%;\r\n height: 60px;\r\n -ms-flex-align: center;\r\n align-items: center;\r\n display: -ms-flexbox;\r\n display: flex;\r\n -ms-flex-pack: center;\r\n justify-content: center;\r\n}\r\n\r\n.simple-keyboard.hg-theme-default .hg-button.hg-button-numpadadd {\r\n height: 85px;\r\n}\r\n\r\n.simple-keyboard.hg-theme-default .hg-button.hg-button-numpadenter {\r\n height: 85px;\r\n}\r\n\r\n.simple-keyboard.hg-theme-default .hg-button.hg-button-numpad0 {\r\n width: 105px;\r\n}\r\n\r\n.simple-keyboard.hg-theme-default .hg-button.hg-button-com {\r\n max-width: 85px;\r\n}\r\n\r\n.simple-keyboard.hg-theme-default .hg-button.hg-standardBtn.hg-button-at {\r\n max-width: 45px;\r\n}\r\n\r\n.simple-keyboard.hg-theme-default .hg-button.hg-selectedButton {\r\n background: rgba(5, 25, 70, 0.53);\r\n color: white;\r\n}\n\n\n// WEBPACK FOOTER //\n// ./src/lib/components/Keyboard.css"],"sourceRoot":""}
-13
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-25
View File
@@ -1,25 +0,0 @@
const fs = require('fs');
const path = require('path');
/**
* A module to get package informations from package.json
* @module getPackageJson
* @param {...string} keys from package.json if no arguments passed it returns package.json content as object
* @returns {object} with given keys or content of package.json as object
*/
/**
* Returns package info
*/
const getPackageJson = function(...args) {
const packageJSON = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json')));
if (!args.length) {
return packageJSON;
}
return args.reduce((out, key) => {
out[key] = packageJSON[key];
return out;
}, {});
};
module.exports = getPackageJson;
+1 -2
View File
@@ -60,8 +60,7 @@ module.exports = {
// CRL: Updated whole block with library specific info
path: paths.appDemoBuild,
filename: 'index.js',
libraryTarget: 'umd',
library: 'SimpleKeyboard'
libraryTarget: 'umd'
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
+1 -25
View File
@@ -8,7 +8,6 @@ const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
const getPackageJson = require('./getPackageJson');
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
@@ -43,24 +42,6 @@ const extractTextPluginOptions = shouldUseRelativeAssetPaths
{ publicPath: Array(cssFilename.split('/').length).join('../') }
: {};
const {
version,
name,
license,
repository,
author,
} = getPackageJson('version', 'name', 'license', 'repository', 'author');
const banner = `
${name} v${version}
${repository.url}
Copyright (c) ${author.replace(/ *\<[^)]*\> */g, " ")}
This source code is licensed under the ${license} license found in the
LICENSE file in the root directory of this source tree.
`;
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
@@ -76,8 +57,7 @@ module.exports = {
// CRL: Updated whole block with library specific info
path: paths.appBuild,
filename: 'index.js',
libraryTarget: 'umd',
library: 'SimpleKeyboard'
libraryTarget: 'umd'
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
@@ -266,10 +246,6 @@ module.exports = {
},
sourceMap: shouldUseSourceMap,
}),
new webpack.BannerPlugin({
banner: banner,
entryOnly: true
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin({
filename: cssFilename,
+2738 -4034
View File
File diff suppressed because it is too large Load Diff
+14 -16
View File
@@ -1,14 +1,13 @@
{
"name": "simple-keyboard",
"version": "2.6.1",
"description": "On-screen Javascript Virtual Keyboard",
"version": "1.1.9",
"description": "React.js Virtual Keyboard",
"main": "build/index.js",
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"demo": "node scripts/demo.js",
"test": "node scripts/test.js --env=jsdom",
"postinstall": "node bin/postinstall",
"prepublish": "npm run build"
},
"repository": {
@@ -21,8 +20,8 @@
},
"homepage": "https://franciscohodge.com/simple-keyboard",
"keywords": [
"javascript",
"es6",
"react",
"reactjs",
"digital",
"keyboard",
"onscreen",
@@ -30,18 +29,17 @@
"component",
"virtual-keyboard",
"touchscreen",
"touch-screen",
"osk"
"touch-screen"
],
"license": "MIT",
"dependencies": {},
"devDependencies": {
"autoprefixer": "7.1.6",
"babel-core": "^6.26.3",
"babel-core": "6.26.0",
"babel-eslint": "7.2.3",
"babel-jest": "20.0.3",
"babel-loader": "7.1.2",
"babel-preset-react-app": "^3.1.2",
"babel-preset-react-app": "^3.1.0",
"babel-runtime": "6.26.0",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
@@ -59,15 +57,11 @@
"file-loader": "1.1.5",
"fs-extra": "3.0.1",
"html-webpack-plugin": "2.29.0",
"istanbul": "^0.4.5",
"istanbul-api": "^2.0.6",
"istanbul-reports": "^2.0.1",
"jest": "20.0.4",
"object-assign": "4.1.1",
"postcss-flexbugs-fixes": "3.2.0",
"postcss-loader": "2.0.8",
"promise": "8.0.1",
"prop-types": "^15.6.1",
"raf": "3.4.0",
"react": "^16.2.0",
"react-dev-utils": "^4.2.1",
@@ -78,12 +72,16 @@
"webpack": "3.8.1",
"webpack-dev-server": "2.9.4",
"webpack-manifest-plugin": "1.3.2",
"whatwg-fetch": "2.0.3"
"whatwg-fetch": "2.0.3",
"prop-types": "^15.6.1"
},
"peerDependencies": {
"react": ">=0.14",
"react-dom": ">=0.14"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}",
"!**/tests/**"
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
+2 -16
View File
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
@@ -20,26 +20,12 @@
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>simple-keyboard</title>
<style>
/**
* Disabling double-tap to zoom in iOS 10+
* as it interferes with simple-keyboard
*/
body,
html {
touch-action: manipulation;
}
</style>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root">
<div class="simple-keyboard"></div>
</div>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
@@ -1,11 +1,11 @@
#root {
.demoPage {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
max-width: 850px;
max-width: 1000px;
margin: 0 auto;
padding-top: 20px;
}
#root .screenContainer {
.demoPage .screenContainer {
background: rgba(0,0,0,0.8);
border: 20px solid;
height: 300px;
@@ -15,7 +15,7 @@
box-sizing: border-box;
}
#root .inputContainer {
.demoPage .inputContainer {
color: white;
background: transparent;
border: none;
@@ -28,15 +28,4 @@
.simple-keyboard.hg-layout-custom {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
}
input {
padding: 10px;
margin: 10px 0;
width: 100%;
box-sizing: border-box;
}
label {
display: block;
}
+76 -43
View File
@@ -1,61 +1,94 @@
import React, {Component} from 'react';
import Keyboard from '../lib';
import './css/App.css';
import './App.css';
class App {
constructor(){
document.addEventListener('DOMContentLoaded', this.onDOMLoaded);
this.layoutName = "default";
class App extends Component {
state = {
input: '',
layoutName: "default"
}
onDOMLoaded = () => {
this.keyboard = new Keyboard({
debug: true,
layoutName: this.layoutName,
onChange: input => this.onChange(input),
onKeyPress: button => this.onKeyPress(button),
newLineOnEnter: true,
physicalKeyboardHighlight: true,
});
componentDidMount(){
this.keyboard.setInput("Hello World!")
.then(input => {
this.setState({input: input});
});
}
/**
* Adding preview (demo only)
*/
document.querySelector('.simple-keyboard').insertAdjacentHTML('beforebegin', `
<div class="simple-keyboard-preview">
<textarea class="input"></textarea>
</div>
`);
document.querySelector('.input').addEventListener('change', (event) => {
this.keyboard.setInput(event.target.value);
onChange = (input) => {
this.setState({
input: input
}, () => {
console.log("Input changed", input);
});
}
onKeyPress = (button) => {
console.log("Button pressed", button);
/**
* Shift functionality
*/
if(button === "{lock}" || button === "{shift}")
this.handleShiftButton();
console.log(this.keyboard);
}
handleShiftButton = () => {
let layoutName = this.layoutName;
let shiftToggle = this.layoutName = layoutName === "default" ? "shift" : "default";
this.keyboard.setOptions({
let layoutName = this.state.layoutName;
let shiftToggle = layoutName === "default" ? "shift" : "default";
this.setState({
layoutName: shiftToggle
});
}
onChange = input => {
document.querySelector('.input').value = input;
}
onKeyPress = button => {
console.log("Button pressed", button);
/**
* Shift functionality
*/
if(button === "{lock}" || button === "{shift}")
this.handleShiftButton();
render(){
return (
<div className={"demoPage"}>
<div className={"screenContainer"}>
<textarea className={"inputContainer"} value={this.state.input} />
</div>
<Keyboard
ref={r => this.keyboard = r}
onChange={input => this.onChange(input)}
onKeyPress={button => this.onKeyPress(button)}
layoutName={this.state.layoutName}
newLineOnEnter={true}
layout={{
'default': [
'` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
'{tab} q w e r t y u i o p [ ] \\',
'{lock} a s d f g h j k l ; \' {enter}',
'{shift} z x c v b n m , . / {shift}',
'.com @ {space}'
],
'shift': [
'~ ! @ # $ % ^ & * ( ) _ + {bksp}',
'{tab} Q W E R T Y U I O P { } |',
'{lock} A S D F G H J K L : " {enter}',
'{shift} Z X C V B N M < > ? {shift}',
'.com @ {space}'
]
}}
theme={"hg-layout-default hg-theme-default"}
debug={true}
display={{
'{bksp}': 'delete',
'{enter}': '< enter',
'{shift}': 'shift',
'{s}': 'shift',
'{tab}': 'tab',
'{lock}': 'caps',
'{accept}': 'Submit',
'{space}': ' ',
'{//}': ' '
}}
/>
</div>
);
}
}
export default App;
-32
View File
@@ -1,32 +0,0 @@
#root {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
max-width: 850px;
margin: 0 auto;
padding-top: 20px;
}
#root .simple-keyboard-preview {
background: rgba(0,0,0,0.8);
border: 20px solid rgba(0,0,0,0.1);
height: 260px;
border-top-right-radius: 5px;
border-top-left-radius: 5px;
padding: 10px;
box-sizing: border-box;
}
#root .input {
color: rgba(255,255,255,0.9);
background: transparent;
border: none;
outline: none;
font-family: monospace;
width: 100%;
height: 100%;
font-size: 18px;
}
.simple-keyboard.hg-layout-custom {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
}
-116
View File
@@ -1,116 +0,0 @@
input {
width: 100%;
height: 100px;
padding: 20px;
font-size: 20px;
border: none;
box-sizing: border-box;
}
.keyboardContainer {
display: flex;
background-color: rgba(0, 0, 0, 0.1);
justify-content: center;
width: 1024px;
margin: 0 auto;
border-radius: 5px;
}
.simple-keyboard.hg-theme-default {
display: inline-block;
}
.simple-keyboard-main.simple-keyboard {
width: 640px;
min-width: 640px;
background: none;
}
.simple-keyboard-main.simple-keyboard .hg-row:first-child {
margin-bottom: 10px;
}
.simple-keyboard-arrows.simple-keyboard {
align-self: flex-end;
background: none;
}
.simple-keyboard .hg-button.hg-selectedButton {
background: rgba(5, 25, 70, 0.53);
color: white;
}
.simple-keyboard .hg-button.emptySpace {
pointer-events: none;
background: none;
border: none;
box-shadow: none;
}
.simple-keyboard-arrows .hg-row {
justify-content: center;
}
.simple-keyboard-arrows .hg-button {
width: 50px;
flex-grow: 0;
justify-content: center;
display: flex;
align-items: center;
}
.controlArrows {
display: flex;
align-items: center;
justify-content: space-between;
flex-flow: column;
}
.simple-keyboard-control.simple-keyboard {
background: none;
}
.simple-keyboard-control.simple-keyboard .hg-row:first-child {
margin-bottom: 10px;
}
.simple-keyboard-control .hg-button {
width: 50px;
flex-grow: 0;
justify-content: center;
display: flex;
align-items: center;
}
.numPad {
display: flex;
align-items: flex-end;
}
.simple-keyboard-numpad.simple-keyboard {
background: none;
}
.simple-keyboard-numpad.simple-keyboard {
width: 160px;
}
.simple-keyboard-numpad.simple-keyboard .hg-button {
width: 50px;
justify-content: center;
display: flex;
align-items: center;
}
.simple-keyboard-numpadEnd.simple-keyboard {
width: 50px;
background: none;
margin: 0;
padding: 5px 5px 5px 0;
}
.simple-keyboard-numpadEnd.simple-keyboard .hg-button {
align-items: center;
justify-content: center;
display: flex;
}
+3 -4
View File
@@ -1,6 +1,5 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
/**
* Initializing demo
*/
new App();
ReactDOM.render(<App />, document.getElementById('root'));
-67
View File
@@ -1,67 +0,0 @@
import TestUtility from '../../lib/tests/TestUtility';
import Index from '../index';
import App from '../App';
let testUtil = new TestUtility();
it('Demo will load', () => {
testUtil.setDOM();
let demo = new App();
});
it('Demo onDOMLoaded will work', () => {
testUtil.setDOM();
let demo = new App();
demo.onDOMLoaded();
expect(demo.keyboard).toBeTruthy();
});
it('Demo onChange will work', () => {
testUtil.setDOM();
let demo = new App();
demo.onDOMLoaded();
demo.onChange("test");
expect(document.body.querySelector('.input').value).toBe("test");
});
it('Demo onChange will work', () => {
testUtil.setDOM();
let demo = new App();
demo.onDOMLoaded();
demo.keyboard.getButtonElement("q").onclick();
expect(document.body.querySelector('.input').value).toBe("q");
});
it('Demo input change will work', () => {
testUtil.setDOM();
let demo = new App();
demo.onDOMLoaded();
document.body.querySelector('.input').value = "test";
document.body.querySelector('.input').dispatchEvent(new Event('change'));
expect(demo.keyboard.getInput()).toBe("test");
});
it('Demo handleShiftButton will work', () => {
testUtil.setDOM();
let demo = new App();
demo.onDOMLoaded();
demo.keyboard.getButtonElement("{shift}")[0].onclick();
expect(demo.keyboard.options.layoutName).toBe("shift");
demo.keyboard.getButtonElement("{shift}")[0].onclick();
expect(demo.keyboard.options.layoutName).toBe("default");
});
+4 -33
View File
@@ -9,7 +9,6 @@ body, html {
user-select: none;
box-sizing: border-box;
overflow: hidden;
touch-action: manipulation;
}
.simple-keyboard .hg-row {
@@ -30,7 +29,7 @@ body, html {
cursor: pointer;
}
.hg-standardBtn {
.simple-keyboard.hg-layout-default .hg-button.hg-standardBtn {
max-width: 100px;
}
@@ -38,7 +37,7 @@ body, html {
* hg-theme-default theme
*/
.simple-keyboard.hg-theme-default {
background-color: rgba(0,0,0,0.1);
background-color: rgba(0,0,0,0.2);
padding: 5px;
border-radius: 5px;
}
@@ -46,15 +45,12 @@ body, html {
.simple-keyboard.hg-theme-default .hg-button {
box-shadow: 0px 0px 3px -1px rgba(0,0,0,0.3);
height: 40px;
border: 1px solid rgba(0,0,0,0.25);
border-radius: 5px;
box-sizing: border-box;
padding: 5px;
background: white;
border-bottom: 1px solid #b5b5b5;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
border-bottom: 1px solid gray;
}
.simple-keyboard.hg-theme-default .hg-button:active {
@@ -67,29 +63,4 @@ body, html {
align-items: center;
display: flex;
justify-content: center;
}
.simple-keyboard.hg-theme-default .hg-button.hg-button-numpadadd {
height: 85px;
}
.simple-keyboard.hg-theme-default .hg-button.hg-button-numpadenter {
height: 85px;
}
.simple-keyboard.hg-theme-default .hg-button.hg-button-numpad0 {
width: 105px;
}
.simple-keyboard.hg-theme-default .hg-button.hg-button-com {
max-width: 85px;
}
.simple-keyboard.hg-theme-default .hg-button.hg-standardBtn.hg-button-at {
max-width: 45px;
}
.simple-keyboard.hg-theme-default .hg-button.hg-selectedButton {
background: rgba(5, 25, 70, 0.53);
color: white;
}
+101 -430
View File
@@ -1,65 +1,54 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './Keyboard.css';
// Services
import PhysicalKeyboard from '../services/PhysicalKeyboard';
import KeyboardLayout from '../services/KeyboardLayout';
import Utilities from '../services/Utilities';
class SimpleKeyboard {
constructor(...params){
let keyboardDOMQuery = typeof params[0] === "string" ? params[0] : '.simple-keyboard';
let options = typeof params[0] === "object" ? params[0] : params[1];
class App extends Component {
state = {
input: ''
}
if(!options)
options = {};
/**
* Initializing Utilities
*/
this.utilities = new Utilities(this);
/**
* Processing options
*/
this.keyboardDOM = document.querySelector(keyboardDOMQuery);
this.options = options;
this.options.layoutName = this.options.layoutName || "default";
this.options.theme = this.options.theme || "hg-theme-default";
this.options.inputName = this.options.inputName || "default";
this.input = {};
this.input[this.options.inputName] = '';
this.keyboardDOMClass = keyboardDOMQuery.split('.').join("");
this.timers = {};
this.buttonElements = {};
/**
* Rendering keyboard
*/
if(this.keyboardDOM)
this.render();
else {
console.warn(`"${keyboardDOMQuery}" was not found in the DOM.`);
throw new Error("KEYBOARD_DOM_ERROR");
componentWillReceiveProps = (nextProps) => {
if(
this.props !== nextProps
){
this.setState({
layoutName: nextProps.layoutName,
layout: nextProps.layout,
themeClass: nextProps.theme
});
}
}
/**
* Saving instance
* This enables multiple simple-keyboard support with easier management
*/
if(!window['SimpleKeyboardInstances'])
window['SimpleKeyboardInstances'] = {};
window['SimpleKeyboardInstances'][this.utilities.camelCase(this.keyboardDOMClass)] = this;
clearInput = () => {
this.setState({
input: ''
});
}
/**
* Physical Keyboard support
*/
this.physicalKeyboardInterface = new PhysicalKeyboard(this);
getInput = () => {
return this.state.input;
}
setInput = input => {
return new Promise(resolve => {
this.setState({
input: input
}, () => {
resolve(input);
});
})
.catch(reason => {
console.warn(reason);
});
}
handleButtonClicked = (button) => {
let debug = this.options.debug;
let debug = this.props.debug;
/**
* Ignoring placeholder buttons
*/
@@ -69,39 +58,32 @@ class SimpleKeyboard {
/**
* Calling onKeyPress
*/
if(typeof this.options.onKeyPress === "function")
this.options.onKeyPress(button);
if(typeof this.props.onKeyPress === "function")
this.props.onKeyPress(button);
/**
* Updating input
*/
let options = {
newLineOnEnter: (this.props.newLineOnEnter === true)
}
if(!this.input[this.options.inputName])
this.input[this.options.inputName] = '';
let updatedInput = Utilities.getUpdatedInput(button, this.state.input, options);
let updatedInput = this.utilities.getUpdatedInput(button, this.input[this.options.inputName], this.options, this.caretPosition);
if(this.input[this.options.inputName] !== updatedInput){
/**
* If maxLength and handleMaxLength yield true, halting
*/
if(this.options.maxLength && this.utilities.handleMaxLength(this.input, this.options, updatedInput)){
return false;
}
this.input[this.options.inputName] = updatedInput;
if(debug)
console.log('Input changed:', this.input);
/**
* syncInstanceInputs
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
/**
* Calling onChange
*/
if(typeof this.options.onChange === "function")
this.options.onChange(this.input[this.options.inputName]);
if(this.state.input !== updatedInput){
this.setState({
input: updatedInput
}, () => {
if(debug){
console.log('Input changed:', this.state.input);
}
/**
* Calling onChange
*/
if(typeof this.props.onChange === "function")
this.props.onChange(this.state.input);
});
}
if(debug){
@@ -109,359 +91,48 @@ class SimpleKeyboard {
}
}
syncInstanceInputs = () => {
this.dispatch((section) => {
section.replaceInput(this.input);
});
}
render() {
let layoutName = this.props.layoutName || "default";
let layout = this.props.layout || KeyboardLayout.getLayout(layoutName);
let themeClass = this.props.theme || "hg-theme-default";
let layoutClass = this.props.layout ? "hg-layout-custom" : `hg-layout-${layoutName}`;
clearInput = (inputName) => {
inputName = inputName || this.options.inputName;
this.input[this.options.inputName] = '';
return (
<div className={`simple-keyboard ${themeClass} ${layoutClass}`}>
{layout[layoutName].map((row, index) => {
let rowArray = row.split(' ');
/**
* syncInstanceInputs
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
}
return (
<div key={`hg-row-${index}`} className="hg-row">
{rowArray.map((button, index) => {
let fctBtnClass = Utilities.getButtonClass(button);
let buttonDisplayName = Utilities.getButtonDisplayName(button, this.props.display);
getInput = (inputName) => {
inputName = inputName || this.options.inputName;
/**
* syncInstanceInputs
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
return this.input[this.options.inputName];
}
setInput = (input, inputName) => {
inputName = inputName || this.options.inputName;
this.input[inputName] = input;
/**
* syncInstanceInputs
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
}
replaceInput = (inputObj) => {
this.input = inputObj;
}
setOptions = option => {
option = option || {};
this.options = Object.assign(this.options, option);
this.render();
}
clear = () => {
this.keyboardDOM.innerHTML = '';
this.keyboardDOM.className = this.keyboardDOMClass;
this.buttonElements = {};
}
dispatch = (callback) => {
if(!window['SimpleKeyboardInstances']){
console.warn(`SimpleKeyboardInstances is not defined. Dispatch cannot be called.`);
throw new Error("INSTANCES_VAR_ERROR");
}
return Object.keys(window['SimpleKeyboardInstances']).forEach((key) => {
callback(window['SimpleKeyboardInstances'][key], key);
})
}
addButtonTheme = (buttons, className) => {
if(!className || !buttons)
return false;
buttons.split(" ").forEach(button => {
className.split(" ").forEach(classNameItem => {
if(!this.options.buttonTheme)
this.options.buttonTheme = [];
let classNameFound = false;
/**
* If class is already defined, we add button to class definition
*/
this.options.buttonTheme.map(buttonTheme => {
if(buttonTheme.class.split(" ").includes(classNameItem)){
classNameFound = true;
let buttonThemeArray = buttonTheme.buttons.split(" ");
if(!buttonThemeArray.includes(button)){
classNameFound = true;
buttonThemeArray.push(button);
buttonTheme.buttons = buttonThemeArray.join(" ");
}
}
return buttonTheme;
});
/**
* If class is not defined, we create a new entry
*/
if(!classNameFound){
this.options.buttonTheme.push({
class: classNameItem,
buttons: buttons
});
}
});
});
this.render();
}
removeButtonTheme = (buttons, className) => {
/**
* When called with empty parameters, remove all button themes
*/
if(!buttons && !className){
this.options.buttonTheme = [];
this.render();
return false;
}
/**
* If buttons are passed and buttonTheme has items
*/
if(buttons && Array.isArray(this.options.buttonTheme) && this.options.buttonTheme.length){
let buttonArray = buttons.split(" ");
buttonArray.forEach((button, key) => {
this.options.buttonTheme.map((buttonTheme, index) => {
/**
* If className is set, we affect the buttons only for that class
* Otherwise, we afect all classes
*/
if(
(className && className.includes(buttonTheme.class)) ||
!className
){
let filteredButtonArray = buttonTheme.buttons.split(" ").filter(item => item !== button);
/**
* If buttons left, return them, otherwise, remove button Theme
*/
if(filteredButtonArray.length){
buttonTheme.buttons = filteredButtonArray.join(" ");
} else {
this.options.buttonTheme.splice(index, 1);
buttonTheme = null;
}
}
return buttonTheme;
});
});
this.render();
}
}
getButtonElement = (button) => {
let output;
let buttonArr = this.buttonElements[button];
if(buttonArr){
if(buttonArr.length > 1){
output = buttonArr;
} else {
output = buttonArr[0];
}
}
return output;
}
handleCaret = () => {
if(this.options.debug){
console.log("Caret handling started");
}
document.addEventListener("keyup", this.caretEventHandler);
document.addEventListener("mouseup", this.caretEventHandler);
document.addEventListener("touchend", this.caretEventHandler);
}
caretEventHandler = (event) => {
let targetTagName = event.target.tagName.toLowerCase();
if(
targetTagName === "textarea" ||
targetTagName === "input"
){
this.caretPosition = event.target.selectionStart;
if(this.options.debug){
console.log('Caret at: ', event.target.selectionStart, event.target.tagName.toLowerCase());
}
}
}
onInit = () => {
if(this.options.debug){
console.log("Initialized");
}
/**
* Caret handling
*/
this.handleCaret();
if(typeof this.options.onInit === "function")
this.options.onInit();
}
onRender = () => {
if(typeof this.options.onRender === "function")
this.options.onRender();
}
render = () => {
/**
* Clear keyboard
*/
this.clear();
let layoutClass = this.options.layout ? "hg-layout-custom" : `hg-layout-${this.options.layoutName}`;
let layout = this.options.layout || KeyboardLayout.getDefaultLayout();
/**
* Account for buttonTheme, if set
*/
let buttonThemesParsed = {};
if(Array.isArray(this.options.buttonTheme)){
this.options.buttonTheme.forEach(themeObj => {
if(themeObj.buttons && themeObj.class){
let themeButtons;
if(typeof themeObj.buttons === "string"){
themeButtons = themeObj.buttons.split(' ');
}
if(themeButtons){
themeButtons.forEach(themeButton => {
let themeParsed = buttonThemesParsed[themeButton];
// If the button has already been added
if(themeParsed){
// Making sure we don't add duplicate classes, even when buttonTheme has duplicates
if(!this.utilities.countInArray(themeParsed.split(" "), themeObj.class)){
buttonThemesParsed[themeButton] = `${themeParsed} ${themeObj.class}`;
}
} else {
buttonThemesParsed[themeButton] = themeObj.class;
}
});
}
} else {
console.warn(`buttonTheme row is missing the "buttons" or the "class". Please check the documentation.`)
}
});
}
/**
* Adding themeClass, layoutClass to keyboardDOM
*/
this.keyboardDOM.className += ` ${this.options.theme} ${layoutClass}`;
/**
* Iterating through each row
*/
layout[this.options.layoutName].forEach((row, rIndex) => {
let rowArray = row.split(' ');
/**
* Creating empty row
*/
var rowDOM = document.createElement('div');
rowDOM.className += "hg-row";
/**
* Iterating through each button in row
*/
rowArray.forEach((button, bIndex) => {
let fctBtnClass = this.utilities.getButtonClass(button);
let buttonThemeClass = buttonThemesParsed[button];
let buttonDisplayName = this.utilities.getButtonDisplayName(button, this.options.display, this.options.mergeDisplay);
/**
* Creating button
*/
var buttonDOM = document.createElement('div');
buttonDOM.className += `hg-button ${fctBtnClass}${buttonThemeClass ? " "+buttonThemeClass : ""}`;
buttonDOM.onclick = () => this.handleButtonClicked(button);
/**
* Adding identifier
*/
buttonDOM.setAttribute("data-skBtn", button);
/**
* Adding unique id
* Since there's no limit on spawning same buttons, the unique id ensures you can style every button
*/
let buttonUID = `${this.options.layoutName}-r${rIndex}b${bIndex}`;
buttonDOM.setAttribute("data-skBtnUID", buttonUID);
/**
* Adding display label
*/
buttonDOM.setAttribute("data-displayLabel", buttonDisplayName);
/**
* Adding button label to button
*/
var buttonSpanDOM = document.createElement('span');
buttonSpanDOM.innerHTML = buttonDisplayName;
buttonDOM.appendChild(buttonSpanDOM);
/**
* Adding to buttonElements
*/
if(!this.buttonElements[button])
this.buttonElements[button] = [];
this.buttonElements[button].push(buttonDOM);
/**
* Appending button to row
*/
rowDOM.appendChild(buttonDOM);
});
/**
* Appending row to keyboard
*/
this.keyboardDOM.appendChild(rowDOM);
});
/**
* Calling onRender
*/
this.onRender();
if(!this.initialized){
this.initialized = true;
/**
* Calling onInit
*/
this.onInit();
}
return (
<div
key={`hg-button-${index}`}
className={`hg-button ${fctBtnClass}`}
onClick={() => this.handleButtonClicked(button)}
><span>{buttonDisplayName}</span></div>
);
})}
</div>
);
})}
</div>
);
}
}
export default SimpleKeyboard;
App.propTypes = {
layoutName: PropTypes.string,
layout: PropTypes.object,
theme: PropTypes.string,
display: PropTypes.object,
onChange: PropTypes.func,
onKeyPress: PropTypes.func,
debug: PropTypes.bool
};
export default App;
+8
View File
@@ -0,0 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom';
import Keyboard from './Keyboard';
it('Keyboard renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<Keyboard />, div);
});
-709
View File
@@ -1,709 +0,0 @@
import Keyboard from '../Keyboard';
import TestUtility from '../../tests/TestUtility';
let testUtil = new TestUtility();
it('Keyboard will not render without target element', () => {
try {
new Keyboard();
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe("KEYBOARD_DOM_ERROR");
}
});
it('Keyboard will run without options', () => {
// Prepare target DOM element
testUtil.setDOM();
// No options
new Keyboard();
});
it('Keyboard will run with empty options', () => {
// Prepare target DOM element
testUtil.setDOM();
// No options
new Keyboard({});
});
it('Keyboard will run with custom DOM target', () => {
testUtil.setDOM("myTestDiv");
new Keyboard(".myTestDiv");
expect(document.body.querySelector(".myTestDiv")).toBeDefined();
});
it('Keyboard will run with debug option set', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
debug: true
});
expect(keyboard.options.debug).toBeTruthy();
});
it('Keyboard standard buttons will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: {
"default": 10
}
});
testUtil.testLayoutStdButtons(keyboard);
});
it('Keyboard shift buttons will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.setOptions({
layoutName: "shift",
maxLength: 42
});
testUtil.testLayoutStdButtons(keyboard);
});
it('Keyboard setOptions will work without a param', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.setOptions();
});
it('Keyboard empty buttons wont do anything as expected', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
layout: {
default: [
"{//} {button} d",
"a b c d e f g h i j",
]
}
});
keyboard.getButtonElement("{//}").onclick();
});
it('Keyboard onKeyPress will work', () => {
testUtil.setDOM();
let pressed = false;
let keyboard = new Keyboard({
onKeyPress: () => {
pressed = true;
},
debug: true
});
keyboard.getButtonElement("q").onclick();
expect(pressed).toBeTruthy();
});
it('Keyboard standard function buttons will not change input', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
testUtil.iterateButtons((button) => {
if(button.getAttribute("data-skbtn") === "{shift}"){
button.onclick();
}
});
expect(keyboard.getInput()).toBeFalsy();
});
it('Keyboard syncInstanceInputs will work', () => {
testUtil.clear();
document.body.innerHTML = `
<div class="keyboard1"></div>
<div class="keyboard2"></div>
`;
let sharedOptions = {
syncInstanceInputs: true
};
let keyboard1 = new Keyboard(".keyboard1", sharedOptions);
let keyboard2 = new Keyboard(".keyboard2", sharedOptions);
keyboard1.getButtonElement("q").onclick();
expect(keyboard2.getInput()).toBe("q");
});
it('Keyboard onChange will work', () => {
testUtil.setDOM();
let output = false;
let keyboard = new Keyboard({
onChange: (input) => {
output = input;
}
});
keyboard.getButtonElement("q").onclick();
expect(output).toBe("q");
});
it('Keyboard clearInput will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.input = {
"default": "hello"
};
keyboard.clearInput();
expect(keyboard.getInput()).toBeFalsy();
});
it('Keyboard clearInput will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
/**
* Avoid setInput for this test
*/
keyboard.input = {
"default": "hello"
};
keyboard.clearInput();
expect(keyboard.getInput()).toBeFalsy();
});
it('Keyboard clearInput will work with syncInstanceInputs', () => {
testUtil.clear();
document.body.innerHTML = `
<div class="keyboard1"></div>
<div class="keyboard2"></div>
`;
let sharedOptions = {
syncInstanceInputs: true
};
let keyboard1 = new Keyboard(".keyboard1", sharedOptions);
let keyboard2 = new Keyboard(".keyboard2", sharedOptions);
/**
* Avoid setInput for this test
*/
keyboard1.input = {
"default": "hello"
};
keyboard2.clearInput();
expect(keyboard1.getInput()).toBeFalsy();
});
it('Keyboard setInput will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.setInput("hello");
expect(keyboard.getInput()).toBe("hello");
});
it('Keyboard setInput will work with syncInstanceInputs', () => {
testUtil.clear();
document.body.innerHTML = `
<div class="keyboard1"></div>
<div class="keyboard2"></div>
`;
let sharedOptions = {
syncInstanceInputs: true
};
let keyboard1 = new Keyboard(".keyboard1", sharedOptions);
let keyboard2 = new Keyboard(".keyboard2", sharedOptions);
keyboard1.setInput("hello");
expect(keyboard2.getInput()).toBe("hello");
});
it('Keyboard dispatch will work', () => {
testUtil.setDOM();
document.body.innerHTML = `
<div class="keyboard1"></div>
<div class="keyboard2"></div>
`;
let keyboard1 = new Keyboard(".keyboard1");
let keyboard2 = new Keyboard(".keyboard2");
keyboard1.dispatch(instance => {
instance.setOptions({
buttonTheme: [
{
class: "myCustomClass",
buttons: "Q"
}
]
})
});
expect(keyboard2.options.buttonTheme[0].class).toBe("myCustomClass");
});
it('Keyboard dispatch will not work without SimpleKeyboardInstances', () => {
testUtil.setDOM();
document.body.innerHTML = `
<div class="keyboard1"></div>
<div class="keyboard2"></div>
`;
let keyboard1 = new Keyboard(".keyboard1");
let keyboard2 = new Keyboard(".keyboard2");
window['SimpleKeyboardInstances'] = null;
try {
keyboard1.dispatch(instance => {
instance.setOptions({
buttonTheme: [
{
class: "myCustomClass",
buttons: "Q"
}
]
})
});
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe("INSTANCES_VAR_ERROR");
}
});
it('Keyboard addButtonTheme will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let returnVal = keyboard.addButtonTheme("q", "test");
expect(keyboard.options.buttonTheme[0].class).toBe("test");
});
it('Keyboard addButtonTheme will not work without params', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let returnVal = keyboard.addButtonTheme();
expect(returnVal).toBeFalsy();
});
it('Keyboard addButtonTheme will amend a buttonTheme', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "s"
}
]
});
keyboard.addButtonTheme("q", "test");
expect(keyboard.options.buttonTheme[0].class).toBe("test");
});
it('Keyboard addButtonTheme will create a buttonTheme', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "blurb",
buttons: "s"
}
]
});
keyboard.addButtonTheme("q", "test");
expect(keyboard.options.buttonTheme[1].class).toBe("test");
});
it('Keyboard addButtonTheme will ignore a repeated buttonTheme', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "s a"
}
]
});
keyboard.addButtonTheme("a", "test");
expect(keyboard.options.buttonTheme[0].buttons).toBe("s a");
});
it('Keyboard addButtonTheme will amend a buttonTheme', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "s"
}
]
});
keyboard.addButtonTheme("q", "test");
expect(keyboard.options.buttonTheme[0].buttons).toBe("s q");
});
it('Keyboard removeButtonTheme without params will remove all button themes', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "s"
}
]
});
keyboard.removeButtonTheme();
expect(keyboard.options.buttonTheme.length).toBe(0);
});
it('Keyboard removeButtonTheme will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "s"
}
]
});
keyboard.removeButtonTheme("s", "test");
expect(keyboard.options.buttonTheme.length).toBe(0);
});
it('Keyboard removeButtonTheme will work wihtout a class', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "s"
}
]
});
keyboard.removeButtonTheme("s");
expect(keyboard.options.buttonTheme.length).toBe(0);
});
it('Keyboard removeButtonTheme will do nothing without a button param', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "s"
}
]
});
keyboard.removeButtonTheme(null, "test");
expect(keyboard.options.buttonTheme.length).toBe(1);
});
it('Keyboard removeButtonTheme does nothing if req button doesnt have a buttonTheme', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "a"
}
]
});
keyboard.removeButtonTheme("s", "test");
expect(keyboard.options.buttonTheme.length).toBe(1);
});
it('Keyboard removeButtonTheme does nothing if buttonTheme class does not exist', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "testy",
buttons: "a"
}
]
});
keyboard.removeButtonTheme("a", "test");
expect(keyboard.options.buttonTheme.length).toBe(1);
});
it('Keyboard removeButtonTheme does nothing if buttonTheme doesnt have the requested buttons', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "a b c d e f"
}
]
});
keyboard.removeButtonTheme("g", "test");
expect(keyboard.options.buttonTheme[0].buttons).toBe("a b c d e f");
});
it('Keyboard getButtonElement will not return anything if empty match', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
layout: {
default: [
"{//} {button} d",
"a b c d e f g h i j",
]
}
});
expect(keyboard.getButtonElement("{waldo}")).toBeFalsy();
});
it('Keyboard getButtonElement will return multiple matched buttons', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
expect(keyboard.getButtonElement("{shift}").length).toBe(2);
});
it('Keyboard will receive physical keyboard events', () => {
testUtil.setDOM();
new Keyboard({
debug: true,
physicalKeyboardHighlight: true
});
document.dispatchEvent(new KeyboardEvent('keyup', {
charCode: 0,
code: "KeyF",
key: "f",
which: 70,
target: {
tagName: "input"
}
}));
});
it('Keyboard caretEventHandler will detect input, textarea focus', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.caretEventHandler({
charCode: 0,
code: "KeyF",
key: "f",
which: 70,
target: {
tagName: "input",
selectionStart: 3
}
});
expect(keyboard.caretPosition).toBe(3);
});
it('Keyboard caretEventHandler ignore positioning if input, textarea is blur', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.caretEventHandler({
charCode: 0,
code: "KeyF",
key: "f",
which: 70,
target: {
tagName: "div",
selectionStart: 4
}
});
expect(keyboard.caretPosition).toBeFalsy();
});
it('Keyboard caretEventHandler will work with debug', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
debug: true
});
keyboard.caretEventHandler({
charCode: 0,
code: "KeyF",
key: "f",
which: 70,
target: {
tagName: "input",
selectionStart: 3
}
});
expect(keyboard.caretPosition).toBe(3);
});
it('Keyboard onInit will work', () => {
testUtil.setDOM();
let passed = false;
let keyboard = new Keyboard({
onInit: () => {
passed = true
}
});
expect(passed).toBeTruthy();
});
it('Keyboard onRender will work', () => {
testUtil.setDOM();
let passed = false;
let keyboard = new Keyboard({
onRender: () => {
passed = true
}
});
expect(passed).toBeTruthy();
});
it('Keyboard buttonTheme that is invalid will be ignored and not throw', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: null,
buttons: null
}
]
});
});
it('Keyboard buttonTheme buttons that are invalid will be ignored and not throw', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: null,
buttons: undefined
}
]
});
});
it('Keyboard buttonTheme will be ignored if buttons param not a string', () => {
testUtil.setDOM();
new Keyboard({
buttonTheme: [
{
class: "test",
buttons: {
wrong: true
}
}
]
});
});
it('Keyboard buttonTheme will be ignored if already added', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
buttonTheme: [
{
class: "test",
buttons: "a b c"
},
{
class: "test",
buttons: "c"
},
{
class: "anotherclass",
buttons: "c"
},
{
class: "yetAnotherclass",
buttons: "c"
},
{
class: "anotherclass",
buttons: "c"
},
]
});
});
+2 -2
View File
@@ -1,2 +1,2 @@
import SimpleKeyboard from './components/Keyboard';
export default SimpleKeyboard;
import Keyboard from './components/Keyboard';
export default Keyboard;
+32 -17
View File
@@ -1,22 +1,37 @@
class KeyboardLayout {
static getDefaultLayout = () => {
return {
'default': [
'` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
'{tab} q w e r t y u i o p [ ] \\',
'{lock} a s d f g h j k l ; \' {enter}',
'{shift} z x c v b n m , . / {shift}',
'.com @ {space}'
],
'shift': [
'~ ! @ # $ % ^ & * ( ) _ + {bksp}',
'{tab} Q W E R T Y U I O P { } |',
'{lock} A S D F G H J K L : " {enter}',
'{shift} Z X C V B N M < > ? {shift}',
'.com @ {space}'
]
}
static getLayout = layout => {
if(layout === "qwerty"){
return {
'default': [
'` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
'{tab} q w e r t y u i o p [ ] \\',
'{lock} a s d f g h j k l ; \' {enter}',
'{shift} z x c v b n m , . / {shift}',
'.com @ {space}'
],
'shift': [
'~ ! @ # $ % ^ & * ( ) _ + {bksp}',
'{tab} Q W E R T Y U I O P { } |',
'{lock} A S D F G H J K L : " {enter}',
'{shift} Z X C V B N M < > ? {shift}',
'.com @ {space}'
]
};
} else if(layout === "numeric"){
return {
'default': [
'1 2 3',
'4 5 6',
'7 8 9',
'{//} 0 {bksp}'
]
};
} else {
return KeyboardLayout.getLayout("qwerty");
}
}
}
export default KeyboardLayout;
-76
View File
@@ -1,76 +0,0 @@
class PhysicalKeyboard {
constructor(simpleKeyboardInstance){
this.simpleKeyboardInstance = simpleKeyboardInstance;
this.initKeyboardListener();
}
initKeyboardListener = () => {
// Normal Keyboard
document.addEventListener("keydown", (event) => {
if(this.simpleKeyboardInstance.options.physicalKeyboardHighlight){
let buttonPressed = this.getSimpleKeyboardLayoutKey(event);
this.simpleKeyboardInstance.dispatch(instance => {
let buttonDOM = instance.getButtonElement(buttonPressed) || instance.getButtonElement(`{${buttonPressed}}`);
if(buttonDOM){
buttonDOM.style.backgroundColor = this.simpleKeyboardInstance.options.physicalKeyboardHighlightBgColor || "#9ab4d0";
buttonDOM.style.color = this.simpleKeyboardInstance.options.physicalKeyboardHighlightTextColor || "white";
}
});
}
});
// Removing button style on keyup
document.addEventListener("keyup", (event) => {
if(this.simpleKeyboardInstance.options.physicalKeyboardHighlight){
let buttonPressed = this.getSimpleKeyboardLayoutKey(event);
this.simpleKeyboardInstance.dispatch(instance => {
let buttonDOM = instance.getButtonElement(buttonPressed) || instance.getButtonElement(`{${buttonPressed}}`);
if(buttonDOM){
buttonDOM.removeAttribute("style");
}
});
}
});
}
getSimpleKeyboardLayoutKey = (event) => {
if(this.simpleKeyboardInstance.options.debug){
console.log(event);
}
let output;
if(
event.code.includes("Numpad") ||
event.code.includes("Shift") ||
event.code.includes("Space") ||
event.code.includes("Backspace") ||
event.code.includes("Control") ||
event.code.includes("Alt") ||
event.code.includes("Meta")
){
output = event.code;
} else {
output = event.key;
}
/**
* If button is not uppercase, casting to lowercase
*/
if (
output !== output.toUpperCase() ||
(event.code[0] === "F" && Number.isInteger(Number(event.code[1])) && event.code.length <= 3)
) {
output = output.toLowerCase();
}
return output;
}
}
export default PhysicalKeyboard;
+61 -237
View File
@@ -1,268 +1,92 @@
class Utilities {
constructor(simpleKeyboardInstance){
this.simpleKeyboardInstance = simpleKeyboardInstance;
static normalizeString(string){
let output;
if(string === "@")
output = 'at';
else if(string === ",")
output = 'comma';
else if(string === ".")
output = 'dot';
else if(string === "\\")
output = 'backslash';
else if(string === "/")
output = 'fordardslash';
else if(string === "*")
output = 'asterisk';
else if(string === "&")
output = 'ampersand';
else if(string === "$")
output = 'dollarsign';
else if(string === "=")
output = 'equals';
else if(string === "+")
output = 'plus';
else if(string === "-")
output = 'minus';
else if(string === "'")
output = 'apostrophe';
else if(string === ";")
output = 'colon';
else if(string === "[")
output = 'openbracket';
else if(string === "]")
output = 'closebracket';
else if(string === "//")
output = 'emptybutton';
else
output = '';
return output ? ` hg-button-${output}` : '';
}
getButtonClass = button => {
let buttonTypeClass = (button.includes("{") && button.includes("}") && button !== '{//}') ? "functionBtn" : "standardBtn";
static getButtonClass = button => {
let buttonTypeClass = (button.includes("{") && button !== '{//}') ? "functionBtn" : "standardBtn";
let buttonWithoutBraces = button.replace("{", "").replace("}", "");
let buttonNormalized = '';
if(buttonTypeClass !== "standardBtn")
buttonNormalized = ` hg-button-${buttonWithoutBraces}`;
let buttonNormalized =
buttonTypeClass === "standardBtn" ?
Utilities.normalizeString(buttonWithoutBraces) : ` hg-button-${buttonWithoutBraces}`;
return `hg-${buttonTypeClass}${buttonNormalized}`;
}
getDefaultDiplay(){
static getDefaultDiplay(){
return {
'{bksp}': 'backspace',
'{backspace}': 'backspace',
'{bksp}': 'delete',
'{enter}': '< enter',
'{shift}': 'shift',
'{shiftleft}': 'shift',
'{shiftright}': 'shift',
'{alt}': 'alt',
'{s}': 'shift',
'{tab}': 'tab',
'{lock}': 'caps',
'{capslock}': 'caps',
'{accept}': 'Submit',
'{space}': ' ',
'{//}': ' ',
"{esc}": "esc",
"{escape}": "esc",
"{f1}": "f1",
"{f2}": "f2",
"{f3}": "f3",
"{f4}": "f4",
"{f5}": "f5",
"{f6}": "f6",
"{f7}": "f7",
"{f8}": "f8",
"{f9}": "f9",
"{f10}": "f10",
"{f11}": "f11",
"{f12}": "f12",
'{numpaddivide}': '/',
'{numlock}': 'lock',
"{arrowup}": "↑",
"{arrowleft}": "←",
"{arrowdown}": "↓",
"{arrowright}": "→",
"{prtscr}": "print",
"{scrolllock}": "scroll",
"{pause}": "pause",
"{insert}": "ins",
"{home}": "home",
"{pageup}": "up",
"{delete}": "del",
"{end}": "end",
"{pagedown}": "down",
"{numpadmultiply}": "*",
"{numpadsubtract}": "-",
"{numpadadd}": "+",
"{numpadenter}": "enter",
"{period}": ".",
"{numpaddecimal}": ".",
"{numpad0}": "0",
"{numpad1}": "1",
"{numpad2}": "2",
"{numpad3}": "3",
"{numpad4}": "4",
"{numpad5}": "5",
"{numpad6}": "6",
"{numpad7}": "7",
"{numpad8}": "8",
"{numpad9}": "9",
'{//}': ' '
};
}
getButtonDisplayName = (button, display, mergeDisplay) => {
if(mergeDisplay){
display = Object.assign({}, this.getDefaultDiplay(), display);
} else {
display = display || this.getDefaultDiplay();
}
static getButtonDisplayName = (button, display) => {
display = display || Utilities.getDefaultDiplay();
return display[button] || button;
}
getUpdatedInput = (button, input, options, caretPos) => {
static getUpdatedInput = (button, input, options) => {
let output = input;
let newLineOnEnter = options.newLineOnEnter;
if((button === "{bksp}" || button === "{backspace}") && output.length > 0){
output = this.removeAt(output, caretPos);
} else if(button === "{space}")
output = this.addStringAt(output, " ", caretPos);
else if(button === "{tab}" && !(typeof options.tabCharOnTab === "boolean" && options.tabCharOnTab === false)){
output = this.addStringAt(output, "\t", caretPos);
} else if((button === "{enter}" || button === "{numpadenter}") && options.newLineOnEnter)
output = this.addStringAt(output, "\n", caretPos);
else if(button.includes("numpad") && Number.isInteger(Number(button[button.length - 2]))){
output = this.addStringAt(output, button[button.length - 2], caretPos);
}
else if(button === "{numpaddivide}")
output = this.addStringAt(output, '/', caretPos);
else if(button === "{numpadmultiply}")
output = this.addStringAt(output, '*', caretPos);
else if(button === "{numpadsubtract}")
output = this.addStringAt(output, '-', caretPos);
else if(button === "{numpadadd}")
output = this.addStringAt(output, '+', caretPos);
else if(button === "{numpaddecimal}")
output = this.addStringAt(output, '.', caretPos);
else if(button === "{" || button === "}")
output = this.addStringAt(output, button, caretPos);
else if(!button.includes("{") && !button.includes("}"))
output = this.addStringAt(output, button, caretPos);
if(button === "{bksp}" && output.length > 0)
output = output.slice(0, -1);
else if(button === "{space}")
output = output + ' ';
else if(button === "{tab}")
output = output + "\t";
else if(button === "{enter}" && newLineOnEnter)
output = output + "\n";
else if(!button.includes("{") && !button.includes("{"))
output = output + button;
return output;
}
updateCaretPos = (length, minus) => {
if(minus){
if(this.simpleKeyboardInstance.caretPosition > 0)
this.simpleKeyboardInstance.caretPosition = this.simpleKeyboardInstance.caretPosition - length
} else {
this.simpleKeyboardInstance.caretPosition = this.simpleKeyboardInstance.caretPosition + length;
}
}
addStringAt(source, string, position){
let output;
if(this.simpleKeyboardInstance.options.debug){
console.log("Caret at:", position);
}
if(!position && position !== 0){
output = source + string;
} else {
output = [source.slice(0, position), string, source.slice(position)].join('');
/**
* Avoid caret position change when maxLength is set
*/
if(!this.isMaxLengthReached()){
this.updateCaretPos(string.length);
}
}
return output;
}
removeAt(source, position){
if(this.simpleKeyboardInstance.caretPosition === 0){
return source;
}
let output;
let prevTwoChars;
let emojiMatched;
let emojiMatchedReg = /([\uD800-\uDBFF][\uDC00-\uDFFF])/g;
/**
* Emojis are made out of two characters, so we must take a custom approach to trim them.
* For more info: https://mathiasbynens.be/notes/javascript-unicode
*/
if(position && position >= 0){
prevTwoChars = source.substring(position - 2, position)
emojiMatched = prevTwoChars.match(emojiMatchedReg);
if(emojiMatched){
output = source.substr(0, (position - 2)) + source.substr(position);
this.updateCaretPos(2, true);
} else {
output = source.substr(0, (position - 1)) + source.substr(position);
this.updateCaretPos(1, true);
}
} else {
prevTwoChars = source.slice(-2);
emojiMatched = prevTwoChars.match(emojiMatchedReg);
if(emojiMatched){
output = source.slice(0, -2);
this.updateCaretPos(2, true);
} else {
output = source.slice(0, -1);
this.updateCaretPos(1, true);
}
}
return output;
}
handleMaxLength(inputObj, options, updatedInput){
let maxLength = options.maxLength;
let currentInput = inputObj[options.inputName];
let condition = currentInput.length === maxLength;
if(
/**
* If pressing this button won't add more characters
* We exit out of this limiter function
*/
updatedInput.length <= currentInput.length
){
return false;
}
if(Number.isInteger(maxLength)){
if(options.debug){
console.log("maxLength (num) reached:", condition);
}
if(condition){
this.maxLengthReached = true;
return true;
} else {
this.maxLengthReached = false;
return false;
}
}
if(typeof maxLength === "object"){
let condition = currentInput.length === maxLength[options.inputName];
if(options.debug){
console.log("maxLength (obj) reached:", condition);
}
if(condition){
this.maxLengthReached = true;
return true;
} else {
this.maxLengthReached = false;
return false;
}
}
}
isMaxLengthReached = () => {
return Boolean(this.maxLengthReached);
}
camelCase = (string) => {
return string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1));
};
countInArray = (array, value) => {
return array.reduce((n, x) => n + (x === value), 0);
}
}
export default Utilities;
@@ -1,118 +0,0 @@
import Keyboard from '../../components/Keyboard';
import TestUtility from '../../tests/TestUtility';
let testUtil = new TestUtility();
it('PhysicalKeyboard keydown will be handled with physicalKeyboardHighlight', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
physicalKeyboardHighlight: true
});
document.dispatchEvent(new KeyboardEvent('keydown', {
code: "KeyF",
key: "f",
target: {
tagName: "input"
}
}));
});
it('PhysicalKeyboard keydown will be handled without physicalKeyboardHighlight', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
physicalKeyboardHighlight: false
});
document.dispatchEvent(new KeyboardEvent('keydown', {
code: "KeyF",
key: "f",
target: {
tagName: "input"
}
}));
});
it('PhysicalKeyboard keydown will not style non-existent buttons', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
physicalKeyboardHighlight: true
});
document.dispatchEvent(new KeyboardEvent('keydown', {
code: "WRONG",
key: "WRONG",
target: {
tagName: "input"
}
}));
});
it('PhysicalKeyboard keyup will be handled with physicalKeyboardHighlight', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
physicalKeyboardHighlight: true
});
document.dispatchEvent(new KeyboardEvent('keyup', {
code: "KeyF",
key: "f",
target: {
tagName: "input"
}
}));
});
it('PhysicalKeyboard keyup will be handle special buttons', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
physicalKeyboardHighlight: true
});
document.dispatchEvent(new KeyboardEvent('keyup', {
code: "Shift",
key: "Shift",
target: {
tagName: "input"
}
}));
});
it('PhysicalKeyboard keyup will not style non-existent buttons', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
physicalKeyboardHighlight: true,
debug: true
});
document.dispatchEvent(new KeyboardEvent('keyup', {
code: "WRONG",
key: "WRONG",
target: {
tagName: "input"
}
}));
});
it('PhysicalKeyboard will work with F1-F12 keys', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
physicalKeyboardHighlight: true,
debug: true
});
document.dispatchEvent(new KeyboardEvent('keyup', {
code: "F12",
key: "F12",
target: {
tagName: "input"
}
}));
});
-456
View File
@@ -1,456 +0,0 @@
import Keyboard from '../../components/Keyboard';
import TestUtility from '../../tests/TestUtility';
let testUtil = new TestUtility();
it('Keyboard mergeDisplay will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
mergeDisplay: true,
display: {
"q": "qreplaced"
}
});
expect(keyboard.getButtonElement("q").getAttribute("data-displaylabel")).toBe("qreplaced");
});
it('Keyboard function buttons will work', () => {
testUtil.setDOM();
new Keyboard();
testUtil.testLayoutFctButtons((fctBtnCount, fctBtnHasOnclickCount) => {
expect(fctBtnCount).toBe(fctBtnHasOnclickCount);
});
});
it('Keyboard {bksp} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{bksp}", "test", keyboard.options);
expect(output).toBe("tes");
});
it('Keyboard {space} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{space}", "test", keyboard.options);
expect(output).toBe("test ");
});
it('Keyboard {tab} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{tab}", "test", keyboard.options);
expect(output).toBe("test\t");
});
it('Keyboard {tab} button will work with tabCharOnTab:false', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
tabCharOnTab: false
});
let output = keyboard.utilities.getUpdatedInput("{tab}", "test", keyboard.options);
expect(output).toBe("test");
});
it('Keyboard {enter} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{enter}", "test", keyboard.options);
expect(output).toBe("test");
});
it('Keyboard {enter} button will work with newLineOnEnter:true', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
newLineOnEnter: true
});
let output = keyboard.utilities.getUpdatedInput("{enter}", "test", keyboard.options);
expect(output).toBe("test\n");
});
it('Keyboard {numpadX} buttons will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
for(let i = 0;i<=9;i++){
let output = keyboard.utilities.getUpdatedInput(`{numpad${i}}`, "test", keyboard.options);
expect(output).toBe(`test${i}`);
}
});
it('Keyboard {numpaddivide} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{numpaddivide}", "test", keyboard.options);
expect(output).toBe("test/");
});
it('Keyboard {numpadmultiply} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{numpadmultiply}", "test", keyboard.options);
expect(output).toBe("test*");
});
it('Keyboard {numpadsubtract} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{numpadsubtract}", "test", keyboard.options);
expect(output).toBe("test-");
});
it('Keyboard {numpadadd} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{numpadadd}", "test", keyboard.options);
expect(output).toBe("test+");
});
it('Keyboard {numpadadd} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{numpadadd}", "test", keyboard.options);
expect(output).toBe("test+");
});
it('Keyboard {numpaddecimal} button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{numpaddecimal}", "test", keyboard.options);
expect(output).toBe("test.");
});
it('Keyboard custom function buttons will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
layout: {
default: [
"{randombuttontest}"
]
}
});
let output = keyboard.utilities.getUpdatedInput("{randombuttontest}", "test", keyboard.options);
expect(output).toBe("test");
expect(keyboard.getButtonElement("{randombuttontest}").onclick).toBeTruthy();
});
it('Keyboard "{" button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("{", "test", keyboard.options);
expect(output).toBe("test{");
});
it('Keyboard "}" button will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.getUpdatedInput("}", "test", keyboard.options);
expect(output).toBe("test}");
});
it('Keyboard standard button will affect input', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
for (let i = 65; i <= 90; i++) {
let char = String.fromCharCode(i);
let output = keyboard.utilities.getUpdatedInput(char, "test", keyboard.options);
expect(output).toBe(`test${char}`);
}
});
it('Keyboard updateCaretPos will work with minus', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.caretPosition = 5;
keyboard.utilities.updateCaretPos(2, true);
expect(keyboard.caretPosition).toBe(3);
});
it('Keyboard updateCaretPos will work with plus', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.caretPosition = 5;
keyboard.utilities.updateCaretPos(2);
expect(keyboard.caretPosition).toBe(7);
});
it('Keyboard addStringAt will work with debug', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
debug: true
});
keyboard.getButtonElement("q").onclick();
expect(keyboard.getInput()).toBe("q");
});
it('Keyboard addStringAt will work with position', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
debug: true
});
keyboard.setInput("test");
keyboard.caretPosition = 4;
keyboard.getButtonElement("q").onclick();
expect(keyboard.getInput()).toBe("testq");
});
it('Keyboard addStringAt will respect maxLength', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
debug: true,
maxLength: 4
});
keyboard.setInput("test");
keyboard.caretPosition = 4;
keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "testq")
keyboard.utilities.addStringAt("test", "q", 4);
expect(keyboard.caretPosition).toBe(4);
});
it('Keyboard handleMaxLength will exit out on same updatedInput', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
debug: true
});
keyboard.setInput("test");
let output = keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "test")
expect(output).toBeFalsy();
});
it('Keyboard handleMaxLength will work with object maxLength', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: {
default: 4
}
});
keyboard.setInput("test");
let output = keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "testq");
expect(output).toBeTruthy();
});
it('Keyboard handleMaxLength will work with object maxLength and debug', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: {
default: 4
},
debug: true
});
keyboard.setInput("test");
let output = keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "testq");
expect(output).toBeTruthy();
});
it('Keyboard handleMaxLength will return false if obj maxLength not reached', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: {
default: 7
}
});
keyboard.setInput("test");
let output = keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "testq");
expect(output).toBeFalsy();
});
it('Keyboard handleMaxLength will work without debug', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: 4
});
keyboard.setInput("test");
let output = keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "testq");
expect(output).toBeTruthy();
});
it('Keyboard handleMaxLength will work with numeric maxLength', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: 3
});
keyboard.setInput("test");
let output = keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "testq");
expect(output).toBeFalsy();
});
it('Keyboard handleMaxLength wont work with non numeric or object maxLength', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: "wrong"
});
keyboard.setInput("test");
let output = keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "testq");
expect(output).toBeFalsy();
});
it('Keyboard handleMaxLength wont work with non numeric or object maxLength (with debug)', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: "wrong",
debug: true
});
keyboard.setInput("test");
let output = keyboard.utilities.handleMaxLength(keyboard.input, keyboard.options, "testq");
expect(output).toBeFalsy();
});
it('Keyboard isMaxLengthReached will work', () => {
testUtil.setDOM();
let keyboard = new Keyboard({
maxLength: 5
});
let output = keyboard.utilities.isMaxLengthReached();
expect(output).toBeFalsy();
});
it('Keyboard removeAt will exit out on caretPosition:0', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.setInput("test");
keyboard.caretPosition = 0;
keyboard.utilities.removeAt(keyboard.getInput(), 0);
expect(keyboard.getInput()).toBe("test");
});
it('Keyboard removeAt will remove multi-byte unicodes with caretPos>0', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.caretPosition = 6;
let output = keyboard.utilities.removeAt("test\uD83D\uDE00", 6);
expect(output).toBe("test");
});
it('Keyboard removeAt will not remove multi-byte unicodes with caretPos:0', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
let output = keyboard.utilities.removeAt("\uD83D\uDE00");
expect(output).toBeFalsy();
});
it('Keyboard removeAt will remove regular strings', () => {
testUtil.setDOM();
let keyboard = new Keyboard();
keyboard.caretPosition = 6;
let output = keyboard.utilities.removeAt("testie", 6);
expect(output).toBe("testi");
});
-93
View File
@@ -1,93 +0,0 @@
export default class TestUtility {
/**
* FUNCTIONS
*/
setDOM = (divClass) => {
this.clear();
const div = document.createElement('div');
div.className += divClass || "simple-keyboard";
document.body.appendChild(div);
}
clear = () => {
document.body.innerHTML = "";
}
testLayoutStdButtons = (keyboard) => {
let stdBtnCount = 0;
let fullInput = '';
this.iterateButtons((button) => {
let label = button.getAttribute("data-skbtn");
if(label.includes("{"))
return false;
// Click all standard buttons, respects maxLength
button.onclick();
// Recording fullInput, bypasses maxLength
fullInput = keyboard.utilities.getUpdatedInput(label, fullInput, keyboard.options, null);
stdBtnCount += label.length;
});
/**
* Check if maxLength is respected
*/
if(
(
typeof keyboard.options.maxLength === "object" &&
keyboard.getInput().length !== keyboard.options.maxLength[keyboard.options.layoutName]
) ||
(
typeof keyboard.options.maxLength !== "object" &&
keyboard.getInput().length !== keyboard.options.maxLength
)
)
throw new Error("MAX_LENGTH_ISSUE");
else
console.log("MAX_LENGTH PASSED:", keyboard.options.layoutName, keyboard.getInput().length, keyboard.options.maxLength);
/**
* Check if all standard buttons are inputting something
* (Regardless of maxLength)
*/
if(stdBtnCount !== fullInput.length)
throw new Error("STANDARD_BUTTONS_ISSUE");
else
console.log("STANDARD_BUTTONS PASSED:", keyboard.options.layoutName, stdBtnCount, fullInput.length);
}
testLayoutFctButtons = (callback) => {
let fctBtnCount = 0;
let fctBtnHasOnclickCount = 0;
this.iterateButtons((button) => {
let label = button.getAttribute("data-skbtn");
if(!label.includes("{") && !label.includes("}"))
return false;
fctBtnCount++;
if(button.onclick){
button.onclick();
fctBtnHasOnclickCount++;
}
callback(fctBtnCount, fctBtnHasOnclickCount);
});
}
iterateButtons = (callback, selector) => {
let rows = document.body.querySelector(selector || '.simple-keyboard').children;
Array.from(rows).forEach(row => {
Array.from(row.children).forEach((button) => {
callback(button);
});
});
}
}