Adding PrettierPlugin to build process

This commit is contained in:
Francisco Hodge 2019-02-15 21:49:27 -05:00
parent 05976e0e7b
commit 70d2cca7ac
7 changed files with 412 additions and 361 deletions

View File

@ -11,9 +11,7 @@ const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const safePostCssParser = require('postcss-safe-parser');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const paths = require('./paths');
@ -23,7 +21,7 @@ const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin-alt')
const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const getPackageJson = require('./getPackageJson');
var PrettierPlugin = require("prettier-webpack-plugin");
// 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.
@ -517,6 +515,7 @@ module.exports = {
to: paths.appBuild
}
]),
new PrettierPlugin(),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
/*new WorkboxWebpackPlugin.GenerateSW({

View File

@ -1,10 +1,12 @@
body, html {
body,
html {
margin: 0;
padding: 0;
}
.simple-keyboard {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue",
Helvetica, Arial, "Lucida Grande", sans-serif;
width: 100%;
user-select: none;
box-sizing: border-box;

View File

@ -1,9 +1,9 @@
import './Keyboard.css';
import "./Keyboard.css";
// Services
import PhysicalKeyboard from '../services/PhysicalKeyboard';
import KeyboardLayout from '../services/KeyboardLayout';
import Utilities from '../services/Utilities';
import PhysicalKeyboard from "../services/PhysicalKeyboard";
import KeyboardLayout from "../services/KeyboardLayout";
import Utilities from "../services/Utilities";
/**
* Root class for simple-keyboard
@ -18,11 +18,11 @@ class SimpleKeyboard {
* @param {Array} params If first parameter is a string, it is considered the container class. The second parameter is then considered the options object. If first parameter is an object, it is considered the options object.
*/
constructor(...params) {
let keyboardDOMQuery = typeof params[0] === "string" ? params[0] : ".simple-keyboard";
let keyboardDOMQuery =
typeof params[0] === "string" ? params[0] : ".simple-keyboard";
let options = typeof params[0] === "object" ? params[0] : params[1];
if(!options)
options = {};
if (!options) options = {};
/**
* Initializing Utilities
@ -66,12 +66,13 @@ class SimpleKeyboard {
this.options.layoutName = this.options.layoutName || "default";
this.options.theme = this.options.theme || "hg-theme-default";
this.options.inputName = this.options.inputName || "default";
this.options.preventMouseDownDefault = this.options.preventMouseDownDefault || false;
this.options.preventMouseDownDefault =
this.options.preventMouseDownDefault || false;
/**
* @type {object} Classes identifying loaded plugins
*/
this.keyboardPluginClasses = '';
this.keyboardPluginClasses = "";
/**
* Bindings
@ -114,12 +115,12 @@ class SimpleKeyboard {
* @property {object} myInputName Example input that can be set through `options.inputName:"myInputName"`.
*/
this.input = {};
this.input[this.options.inputName] = '';
this.input[this.options.inputName] = "";
/**
* @type {string} DOM class of the keyboard wrapper, normally "simple-keyboard" by default.
*/
this.keyboardDOMClass = keyboardDOMQuery.split('.').join("");
this.keyboardDOMClass = keyboardDOMQuery.split(".").join("");
/**
* @type {object} Contains the DOM elements of every rendered button, the key being the button's layout name (e.g.: "{enter}").
@ -129,8 +130,7 @@ class SimpleKeyboard {
/**
* Rendering keyboard
*/
if(this.keyboardDOM)
this.render();
if (this.keyboardDOM) this.render();
else {
console.warn(`"${keyboardDOMQuery}" was not found in the DOM.`);
throw new Error("KEYBOARD_DOM_ERROR");
@ -140,10 +140,12 @@ class SimpleKeyboard {
* Saving instance
* This enables multiple simple-keyboard support with easier management
*/
if(!window['SimpleKeyboardInstances'])
window['SimpleKeyboardInstances'] = {};
if (!window["SimpleKeyboardInstances"])
window["SimpleKeyboardInstances"] = {};
window['SimpleKeyboardInstances'][this.utilities.camelCase(this.keyboardDOMClass)] = this;
window["SimpleKeyboardInstances"][
this.utilities.camelCase(this.keyboardDOMClass)
] = this;
/**
* Physical Keyboard support
@ -167,8 +169,7 @@ class SimpleKeyboard {
/**
* Ignoring placeholder buttons
*/
if(button === '{//}')
return false;
if (button === "{//}") return false;
/**
* Calling onKeyPress
@ -177,43 +178,48 @@ class SimpleKeyboard {
this.options.onKeyPress(button);
if (!this.input[this.options.inputName])
this.input[this.options.inputName] = '';
this.input[this.options.inputName] = "";
let updatedInput = this.utilities.getUpdatedInput(
button, this.input[this.options.inputName], this.options, this.caretPosition
button,
this.input[this.options.inputName],
this.options,
this.caretPosition
);
if (
// If input will change as a result of this button press
this.input[this.options.inputName] !== updatedInput &&
// This pertains to the "inputPattern" option:
(
// If inputPattern isn't set
!this.options.inputPattern ||
(!this.options.inputPattern ||
// Or, if it is set and if the pattern is valid - we proceed.
(this.options.inputPattern && this.inputPatternIsValid(updatedInput))
)
(this.options.inputPattern && this.inputPatternIsValid(updatedInput)))
) {
/**
* If maxLength and handleMaxLength yield true, halting
*/
if(this.options.maxLength && this.utilities.handleMaxLength(this.input, this.options, updatedInput)){
if (
this.options.maxLength &&
this.utilities.handleMaxLength(this.input, this.options, updatedInput)
) {
return false;
}
this.input[this.options.inputName] = this.utilities.getUpdatedInput(
button, this.input[this.options.inputName], this.options, this.caretPosition, true
button,
this.input[this.options.inputName],
this.options,
this.caretPosition,
true
);
if(debug)
console.log('Input changed:', this.input);
if (debug) console.log("Input changed:", this.input);
/**
* Enforce syncInstanceInputs, if set
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
if (this.options.syncInstanceInputs) this.syncInstanceInputs(this.input);
/**
* Calling onChange
@ -237,11 +243,9 @@ class SimpleKeyboard {
*/
this.isMouseHold = true;
if(this.holdInteractionTimeout)
clearTimeout(this.holdInteractionTimeout);
if (this.holdInteractionTimeout) clearTimeout(this.holdInteractionTimeout);
if(this.holdTimeout)
clearTimeout(this.holdTimeout);
if (this.holdTimeout) clearTimeout(this.holdTimeout);
/**
* @type {object} Time to wait until a key hold is detected
@ -249,15 +253,12 @@ class SimpleKeyboard {
this.holdTimeout = setTimeout(() => {
if (
this.isMouseHold &&
(
(!button.includes("{") && !button.includes("}")) ||
((!button.includes("{") && !button.includes("}")) ||
button === "{bksp}" ||
button === "{space}" ||
button === "{tab}"
)
button === "{tab}")
) {
if(this.options.debug)
console.log("Button held:", button);
if (this.options.debug) console.log("Button held:", button);
this.handleButtonHold(button, e);
}
@ -270,8 +271,7 @@ class SimpleKeyboard {
*/
handleButtonMouseUp() {
this.isMouseHold = false;
if(this.holdInteractionTimeout)
clearTimeout(this.holdInteractionTimeout);
if (this.holdInteractionTimeout) clearTimeout(this.holdInteractionTimeout);
}
/**
@ -279,8 +279,7 @@ class SimpleKeyboard {
*/
/* istanbul ignore next */
handleButtonHold(button) {
if(this.holdInteractionTimeout)
clearTimeout(this.holdInteractionTimeout);
if (this.holdInteractionTimeout) clearTimeout(this.holdInteractionTimeout);
/**
* @type {object} Timeout dictating the speed of key hold iterations
@ -299,7 +298,7 @@ class SimpleKeyboard {
* Send a command to all simple-keyboard instances (if you have several instances).
*/
syncInstanceInputs() {
this.dispatch((instance) => {
this.dispatch(instance => {
instance.replaceInput(this.input);
});
}
@ -310,13 +309,12 @@ class SimpleKeyboard {
*/
clearInput(inputName) {
inputName = inputName || this.options.inputName;
this.input[inputName] = '';
this.input[inputName] = "";
/**
* Enforce syncInstanceInputs, if set
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
if (this.options.syncInstanceInputs) this.syncInstanceInputs(this.input);
}
/**
@ -329,8 +327,7 @@ class SimpleKeyboard {
/**
* Enforce syncInstanceInputs, if set
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
if (this.options.syncInstanceInputs) this.syncInstanceInputs(this.input);
return this.input[this.options.inputName];
}
@ -347,8 +344,7 @@ class SimpleKeyboard {
/**
* Enforce syncInstanceInputs, if set
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
if (this.options.syncInstanceInputs) this.syncInstanceInputs(this.input);
}
/**
@ -367,14 +363,14 @@ class SimpleKeyboard {
option = option || {};
this.options = Object.assign(this.options, option);
this.render();
}
};
/**
* Remove all keyboard rows and reset keyboard values.
* Used interally between re-renders.
*/
clear() {
this.keyboardDOM.innerHTML = '';
this.keyboardDOM.innerHTML = "";
this.keyboardDOM.className = this.keyboardDOMClass;
this.buttonElements = {};
}
@ -384,14 +380,16 @@ class SimpleKeyboard {
* @param {function(instance: object, key: string)} callback Function to run on every instance
*/
dispatch(callback) {
if(!window['SimpleKeyboardInstances']){
console.warn(`SimpleKeyboardInstances is not defined. Dispatch cannot be called.`);
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);
})
return Object.keys(window["SimpleKeyboardInstances"]).forEach(key => {
callback(window["SimpleKeyboardInstances"][key], key);
});
}
/**
@ -400,13 +398,11 @@ class SimpleKeyboard {
* @param {string} className Classes to give to the selected buttons (separated by space).
*/
addButtonTheme(buttons, className) {
if(!className || !buttons)
return false;
if (!className || !buttons) return false;
buttons.split(" ").forEach(button => {
className.split(" ").forEach(classNameItem => {
if(!this.options.buttonTheme)
this.options.buttonTheme = [];
if (!this.options.buttonTheme) this.options.buttonTheme = [];
let classNameFound = false;
@ -414,7 +410,6 @@ class SimpleKeyboard {
* If class is already defined, we add button to class definition
*/
this.options.buttonTheme.map(buttonTheme => {
if (buttonTheme.class.split(" ").includes(classNameItem)) {
classNameFound = true;
@ -437,7 +432,6 @@ class SimpleKeyboard {
buttons: buttons
});
}
});
});
@ -462,11 +456,14 @@ class SimpleKeyboard {
/**
* If buttons are passed and buttonTheme has items
*/
if(buttons && Array.isArray(this.options.buttonTheme) && this.options.buttonTheme.length){
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
@ -475,7 +472,9 @@ class SimpleKeyboard {
(className && className.includes(buttonTheme.class)) ||
!className
) {
let filteredButtonArray = buttonTheme.buttons.split(" ").filter(item => item !== button);
let filteredButtonArray = buttonTheme.buttons
.split(" ")
.filter(item => item !== button);
/**
* If buttons left, return them, otherwise, remove button Theme
@ -486,7 +485,6 @@ class SimpleKeyboard {
this.options.buttonTheme.splice(index, 1);
buttonTheme = null;
}
}
return buttonTheme;
@ -537,7 +535,11 @@ class SimpleKeyboard {
let didInputMatch = inputPattern.test(inputVal);
if (this.options.debug) {
console.log(`inputPattern ("${inputPattern}"): ${didInputMatch ? "passed" : "did not pass!"}`);
console.log(
`inputPattern ("${inputPattern}"): ${
didInputMatch ? "passed" : "did not pass!"
}`
);
}
return didInputMatch;
@ -557,17 +559,16 @@ class SimpleKeyboard {
* Only first instance should insall the caret handling events
*/
this.caretPosition = null;
let simpleKeyboardInstances = window['SimpleKeyboardInstances'];
let simpleKeyboardInstances = window["SimpleKeyboardInstances"];
if (
(
simpleKeyboardInstances &&
Object.keys(simpleKeyboardInstances)[0] === this.utilities.camelCase(this.keyboardDOMClass)
) ||
(simpleKeyboardInstances &&
Object.keys(simpleKeyboardInstances)[0] ===
this.utilities.camelCase(this.keyboardDOMClass)) ||
!simpleKeyboardInstances
) {
if (this.options.debug) {
console.log(`Caret handling started (${this.keyboardDOMClass})`)
console.log(`Caret handling started (${this.keyboardDOMClass})`);
}
document.addEventListener("keyup", this.caretEventHandler);
@ -591,8 +592,7 @@ class SimpleKeyboard {
}
if (
(targetTagName === "textarea" ||
targetTagName === "input") &&
(targetTagName === "textarea" || targetTagName === "input") &&
!instance.options.disableCaretPositioning
) {
/**
@ -602,7 +602,12 @@ class SimpleKeyboard {
instance.caretPosition = event.target.selectionStart;
if (instance.options.debug) {
console.log("Caret at: ", event.target.selectionStart, event.target.tagName.toLowerCase(), `(${instance.keyboardDOMClass})`);
console.log(
"Caret at: ",
event.target.selectionStart,
event.target.tagName.toLowerCase(),
`(${instance.keyboardDOMClass})`
);
}
} else if (instance.options.disableCaretPositioning) {
/**
@ -618,7 +623,7 @@ class SimpleKeyboard {
*/
onInit() {
if (this.options.debug) {
console.log(`${this.keyboardDOMClass} Initialized`)
console.log(`${this.keyboardDOMClass} Initialized`);
}
/**
@ -626,16 +631,14 @@ class SimpleKeyboard {
*/
this.handleCaret();
if(typeof this.options.onInit === "function")
this.options.onInit();
if (typeof this.options.onInit === "function") this.options.onInit();
}
/**
* Executes the callback function every time simple-keyboard is rendered (e.g: when you change layouts).
*/
onRender() {
if(typeof this.options.onRender === "function")
this.options.onRender();
if (typeof this.options.onRender === "function") this.options.onRender();
}
/**
@ -650,11 +653,10 @@ class SimpleKeyboard {
* Register module
*/
registerModule = (name, initCallback) => {
if(!this.modules[name])
this.modules[name] = {};
if (!this.modules[name]) this.modules[name] = {};
initCallback(this.modules[name]);
}
};
/**
* Load modules
@ -666,14 +668,18 @@ class SimpleKeyboard {
/* istanbul ignore next */
if (module.constructor.name && module.constructor.name !== "Function") {
let classStr = `module-${this.utilities.camelCase(module.constructor.name)}`;
this.keyboardPluginClasses = this.keyboardPluginClasses + ` ${classStr}`;
let classStr = `module-${this.utilities.camelCase(
module.constructor.name
)}`;
this.keyboardPluginClasses =
this.keyboardPluginClasses + ` ${classStr}`;
}
module.init(this);
});
this.keyboardPluginClasses = this.keyboardPluginClasses + " modules-loaded";
this.keyboardPluginClasses =
this.keyboardPluginClasses + " modules-loaded";
this.render();
this.onModulesLoaded();
@ -684,18 +690,17 @@ class SimpleKeyboard {
* Get module prop
*/
getModuleProp = (name, prop) => {
if(!this.modules[name])
return false;
if (!this.modules[name]) return false;
return this.modules[name][prop];
}
};
/**
* getModulesList
*/
getModulesList = () => {
return Object.keys(this.modules);
}
};
/**
* Renders rows and buttons as per options
@ -708,7 +713,7 @@ class SimpleKeyboard {
let layoutClass = `hg-layout-${this.options.layoutName}`;
let layout = this.options.layout || KeyboardLayout.getDefaultLayout();
let useTouchEvents = this.options.useTouchEvents || false
let useTouchEvents = this.options.useTouchEvents || false;
/**
* Account for buttonTheme, if set
@ -730,8 +735,15 @@ class SimpleKeyboard {
// 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}`;
if (
!this.utilities.countInArray(
themeParsed.split(" "),
themeObj.class
)
) {
buttonThemesParsed[themeButton] = `${themeParsed} ${
themeObj.class
}`;
}
} else {
buttonThemesParsed[themeButton] = themeObj.class;
@ -739,7 +751,9 @@ class SimpleKeyboard {
});
}
} else {
console.warn(`buttonTheme row is missing the "buttons" or the "class". Please check the documentation.`)
console.warn(
`buttonTheme row is missing the "buttons" or the "class". Please check the documentation.`
);
}
});
}
@ -747,7 +761,9 @@ class SimpleKeyboard {
/**
* Adding themeClass, layoutClass to keyboardDOM
*/
this.keyboardDOM.className += ` ${this.options.theme} ${layoutClass} ${this.keyboardPluginClasses}`;
this.keyboardDOM.className += ` ${this.options.theme} ${layoutClass} ${
this.keyboardPluginClasses
}`;
/**
* Iterating through each row
@ -767,31 +783,37 @@ class SimpleKeyboard {
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);
let buttonDisplayName = this.utilities.getButtonDisplayName(
button,
this.options.display,
this.options.mergeDisplay
);
/**
* Creating button
*/
let buttonType = this.options.useButtonTag ? "button" : "div";
let buttonDOM = document.createElement(buttonType);
buttonDOM.className += `hg-button ${fctBtnClass}${buttonThemeClass ? " "+buttonThemeClass : ""}`;
buttonDOM.className += `hg-button ${fctBtnClass}${
buttonThemeClass ? " " + buttonThemeClass : ""
}`;
if (useTouchEvents) {
buttonDOM.ontouchstart = (e) => {
buttonDOM.ontouchstart = e => {
this.handleButtonClicked(button);
this.handleButtonMouseDown(button, e);
}
};
buttonDOM.ontouchend = e => this.handleButtonMouseUp();
buttonDOM.ontouchcancel = e => this.handleButtonMouseUp();
} else {
buttonDOM.onclick = () => {
this.isMouseHold = false;
this.handleButtonClicked(button);
}
buttonDOM.onmousedown = (e) => {
};
buttonDOM.onmousedown = e => {
if (this.options.preventMouseDownDefault) e.preventDefault();
this.handleButtonMouseDown(button, e);
}
};
}
/**
@ -814,15 +836,14 @@ class SimpleKeyboard {
/**
* Adding button label to button
*/
let buttonSpanDOM = document.createElement('span');
let buttonSpanDOM = document.createElement("span");
buttonSpanDOM.innerHTML = buttonDisplayName;
buttonDOM.appendChild(buttonSpanDOM);
/**
* Adding to buttonElements
*/
if(!this.buttonElements[button])
this.buttonElements[button] = [];
if (!this.buttonElements[button]) this.buttonElements[button] = [];
this.buttonElements[button].push(buttonDOM);
@ -830,7 +851,6 @@ class SimpleKeyboard {
* Appending button to row
*/
rowDOM.appendChild(buttonDOM);
});
/**

View File

@ -1,2 +1,2 @@
import SimpleKeyboard from './components/Keyboard';
import SimpleKeyboard from "./components/Keyboard";
export default SimpleKeyboard;

View File

@ -8,21 +8,21 @@ 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}'
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 { } |',
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}'
"{shift} Z X C V B N M < > ? {shift}",
".com @ {space}"
]
}
};
}
}

View File

@ -15,7 +15,9 @@ class PhysicalKeyboard {
* Bindings
*/
this.initKeyboardListener = this.initKeyboardListener.bind(this);
this.getSimpleKeyboardLayoutKey = this.getSimpleKeyboardLayoutKey.bind(this);
this.getSimpleKeyboardLayoutKey = this.getSimpleKeyboardLayoutKey.bind(
this
);
/**
* Initialize key listeners
@ -28,28 +30,36 @@ class PhysicalKeyboard {
*/
initKeyboardListener() {
// Adding button style on keydown
document.addEventListener("keydown", (event) => {
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}}`);
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";
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) => {
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}}`);
let buttonDOM =
instance.getButtonElement(buttonPressed) ||
instance.getButtonElement(`{${buttonPressed}}`);
if (buttonDOM && buttonDOM.removeAttribute) {
buttonDOM.removeAttribute("style");
@ -85,7 +95,9 @@ class PhysicalKeyboard {
*/
if (
output !== output.toUpperCase() ||
(event.code[0] === "F" && Number.isInteger(Number(event.code[1])) && event.code.length <= 3)
(event.code[0] === "F" &&
Number.isInteger(Number(event.code[1])) &&
event.code.length <= 3)
) {
output = output.toLowerCase();
}

View File

@ -31,9 +31,12 @@ class Utilities {
* @return {string} The classes to be added to the button
*/
getButtonClass(button) {
let buttonTypeClass = (button.includes("{") && button.includes("}") && button !== '{//}') ? "functionBtn" : "standardBtn";
let buttonTypeClass =
button.includes("{") && button.includes("}") && button !== "{//}"
? "functionBtn"
: "standardBtn";
let buttonWithoutBraces = button.replace("{", "").replace("}", "");
let buttonNormalized = '';
let buttonNormalized = "";
if (buttonTypeClass !== "standardBtn")
buttonNormalized = ` hg-button-${buttonWithoutBraces}`;
@ -46,20 +49,20 @@ class Utilities {
*/
getDefaultDiplay() {
return {
'{bksp}': 'backspace',
'{backspace}': 'backspace',
'{enter}': '< enter',
'{shift}': 'shift',
'{shiftleft}': 'shift',
'{shiftright}': 'shift',
'{alt}': 'alt',
'{s}': 'shift',
'{tab}': 'tab',
'{lock}': 'caps',
'{capslock}': 'caps',
'{accept}': 'Submit',
'{space}': ' ',
'{//}': ' ',
"{bksp}": "backspace",
"{backspace}": "backspace",
"{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",
@ -74,8 +77,8 @@ class Utilities {
"{f10}": "f10",
"{f11}": "f11",
"{f12}": "f12",
'{numpaddivide}': '/',
'{numlock}': 'lock',
"{numpaddivide}": "/",
"{numlock}": "lock",
"{arrowup}": "↑",
"{arrowleft}": "←",
"{arrowdown}": "↓",
@ -104,7 +107,7 @@ class Utilities {
"{numpad6}": "6",
"{numpad7}": "7",
"{numpad8}": "8",
"{numpad9}": "9",
"{numpad9}": "9"
};
}
/**
@ -124,7 +127,6 @@ class Utilities {
return display[button] || button;
}
/**
* Returns the updated input resulting from clicking a given button
*
@ -135,42 +137,50 @@ class Utilities {
* @param {boolean} moveCaret Whether to update simple-keyboard's cursor
*/
getUpdatedInput(button, input, options, caretPos, moveCaret) {
let output = input;
if((button === "{bksp}" || button === "{backspace}") && output.length > 0){
if (
(button === "{bksp}" || button === "{backspace}") &&
output.length > 0
) {
output = this.removeAt(output, caretPos, moveCaret);
} else if (button === "{space}")
output = this.addStringAt(output, " ", caretPos, moveCaret);
else if(button === "{tab}" && !(typeof options.tabCharOnTab === "boolean" && options.tabCharOnTab === false)){
else if (
button === "{tab}" &&
!(
typeof options.tabCharOnTab === "boolean" &&
options.tabCharOnTab === false
)
) {
output = this.addStringAt(output, "\t", caretPos, moveCaret);
} else if((button === "{enter}" || button === "{numpadenter}") && options.newLineOnEnter)
} else if (
(button === "{enter}" || button === "{numpadenter}") &&
options.newLineOnEnter
)
output = this.addStringAt(output, "\n", caretPos, moveCaret);
else if(button.includes("numpad") && Number.isInteger(Number(button[button.length - 2]))){
output = this.addStringAt(output, button[button.length - 2], caretPos, moveCaret);
}
else if(button === "{numpaddivide}")
output = this.addStringAt(output, '/', caretPos, moveCaret);
else if (
button.includes("numpad") &&
Number.isInteger(Number(button[button.length - 2]))
) {
output = this.addStringAt(
output,
button[button.length - 2],
caretPos,
moveCaret
);
} else if (button === "{numpaddivide}")
output = this.addStringAt(output, "/", caretPos, moveCaret);
else if (button === "{numpadmultiply}")
output = this.addStringAt(output, '*', caretPos, moveCaret);
output = this.addStringAt(output, "*", caretPos, moveCaret);
else if (button === "{numpadsubtract}")
output = this.addStringAt(output, '-', caretPos, moveCaret);
output = this.addStringAt(output, "-", caretPos, moveCaret);
else if (button === "{numpadadd}")
output = this.addStringAt(output, '+', caretPos, moveCaret);
output = this.addStringAt(output, "+", caretPos, moveCaret);
else if (button === "{numpaddecimal}")
output = this.addStringAt(output, '.', caretPos, moveCaret);
output = this.addStringAt(output, ".", caretPos, moveCaret);
else if (button === "{" || button === "}")
output = this.addStringAt(output, button, caretPos, moveCaret);
else if (!button.includes("{") && !button.includes("}"))
output = this.addStringAt(output, button, caretPos, moveCaret);
@ -184,7 +194,11 @@ class Utilities {
* @param {boolean} minus Whether the cursor should be moved to the left or not.
*/
updateCaretPos(length, minus) {
let newCaretPos = this.updateCaretPosAction(this.simpleKeyboardInstance, length, minus);
let newCaretPos = this.updateCaretPosAction(
this.simpleKeyboardInstance,
length,
minus
);
if (this.simpleKeyboardInstance.options.syncInstanceInputs) {
this.simpleKeyboardInstance.dispatch(instance => {
@ -209,7 +223,11 @@ class Utilities {
}
if (this.simpleKeyboardInstance.options.debug) {
console.log("Caret at:", instance.caretPosition, `(${instance.keyboardDOMClass})`);
console.log(
"Caret at:",
instance.caretPosition,
`(${instance.keyboardDOMClass})`
);
}
return instance.caretPosition;
@ -229,7 +247,9 @@ class Utilities {
if (!position && position !== 0) {
output = source + string;
} else {
output = [source.slice(0, position), string, source.slice(position)].join('');
output = [source.slice(0, position), string, source.slice(position)].join(
""
);
/**
* Avoid caret position change when maxLength is set
@ -237,7 +257,6 @@ class Utilities {
if (!this.isMaxLengthReached()) {
if (moveCaret) this.updateCaretPos(string.length);
}
}
return output;
@ -265,14 +284,14 @@ class Utilities {
* For more info: https://mathiasbynens.be/notes/javascript-unicode
*/
if (position && position >= 0) {
prevTwoChars = source.substring(position - 2, position)
prevTwoChars = source.substring(position - 2, position);
emojiMatched = prevTwoChars.match(emojiMatchedReg);
if (emojiMatched) {
output = source.substr(0, (position - 2)) + source.substr(position);
output = source.substr(0, position - 2) + source.substr(position);
if (moveCaret) this.updateCaretPos(2, true);
} else {
output = source.substr(0, (position - 1)) + source.substr(position);
output = source.substr(0, position - 1) + source.substr(position);
if (moveCaret) this.updateCaretPos(1, true);
}
} else {
@ -363,11 +382,10 @@ class Utilities {
.toLowerCase()
.trim()
.split(/[.\-_\s]/g)
.reduce(
(string, word) =>
.reduce((string, word) =>
word.length ? string + word[0].toUpperCase() + word.slice(1) : string
);
};
}
/**
* Counts the number of duplicates in a given array