824 lines
26 KiB
JavaScript
Raw Normal View History

2018-04-20 16:34:02 -04:00
import './Keyboard.css';
// Services
2018-09-23 23:37:46 -04:00
import PhysicalKeyboard from '../services/PhysicalKeyboard';
2018-04-20 16:34:02 -04:00
import KeyboardLayout from '../services/KeyboardLayout';
import Utilities from '../services/Utilities';
2018-10-24 18:18:24 -04:00
/**
* Root class for simple-keyboard
* This class:
* - Parses the options
* - Renders the rows and buttons
* - Handles button functionality
*/
2018-04-20 16:34:02 -04:00
class SimpleKeyboard {
2018-10-24 18:18:24 -04:00
/**
* Creates an instance of 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.
*/
2018-04-20 16:34:02 -04:00
constructor(...params){
2018-12-14 00:28:18 -05:00
let keyboardDOMQuery = typeof params[0] === "string" ? params[0] : ".simple-keyboard";
2018-04-20 16:34:02 -04:00
let options = typeof params[0] === "object" ? params[0] : params[1];
if(!options)
options = {};
2018-10-06 02:16:12 -04:00
/**
* Initializing Utilities
*/
this.utilities = new Utilities(this);
2018-04-20 16:34:02 -04:00
/**
* Processing options
*/
this.keyboardDOM = document.querySelector(keyboardDOMQuery);
2018-10-24 18:18:24 -04:00
/**
* @type {object}
* @property {object} layout Modify the keyboard layout.
* @property {string} layoutName Specifies which layout should be used.
* @property {object} display Replaces variable buttons (such as {bksp}) with a human-friendly name (e.g.: backspace).
* @property {boolean} mergeDisplay By default, when you set the display property, you replace the default one. This setting merges them instead.
* @property {string} theme A prop to add your own css classes to the keyboard wrapper. You can add multiple classes separated by a space.
* @property {Array} buttonTheme A prop to add your own css classes to one or several buttons.
* @property {boolean} debug Runs a console.log every time a key is pressed. Displays the buttons pressed and the current input.
* @property {boolean} newLineOnEnter Specifies whether clicking the ENTER button will input a newline (\n) or not.
* @property {boolean} tabCharOnTab Specifies whether clicking the TAB button will input a tab character (\t) or not.
* @property {string} inputName Allows you to use a single simple-keyboard instance for several inputs.
* @property {number} maxLength Restrains all of simple-keyboard inputs to a certain length. This should be used in addition to the input elements maxlengthattribute.
* @property {object} maxLength Restrains simple-keyboards individual inputs to a certain length. This should be used in addition to the input elements maxlengthattribute.
* @property {boolean} syncInstanceInputs When set to true, this option synchronizes the internal input of every simple-keyboard instance.
* @property {boolean} physicalKeyboardHighlight Enable highlighting of keys pressed on physical keyboard.
* @property {boolean} preventMouseDownDefault Calling preventDefault for the mousedown events keeps the focus on the input.
2018-10-24 18:18:24 -04:00
* @property {string} physicalKeyboardHighlightTextColor Define the text color that the physical keyboard highlighted key should have.
* @property {string} physicalKeyboardHighlightBgColor Define the background color that the physical keyboard highlighted key should have.
2018-10-24 18:18:24 -04:00
* @property {function(button: string):string} onKeyPress Executes the callback function on key press. Returns button layout name (i.e.: {shift}).
* @property {function(input: string):string} onChange Executes the callback function on input change. Returns the current inputs string.
* @property {function} onRender Executes the callback function every time simple-keyboard is rendered (e.g: when you change layouts).
* @property {function} onInit Executes the callback function once simple-keyboard is rendered for the first time (on initialization).
* @property {function(inputs: object):object} onChangeAll Executes the callback function on input change. Returns the input object with all defined inputs.
2018-12-14 00:28:18 -05:00
* @property {boolean} useButtonTag Render buttons as a button element instead of a div element.
* @property {boolean} disableCaretPositioning A prop to ensure characters are always be added/removed at the end of the string.
2018-10-24 18:18:24 -04:00
*/
2018-04-20 16:34:02 -04:00
this.options = options;
this.options.layoutName = this.options.layoutName || "default";
this.options.theme = this.options.theme || "hg-theme-default";
2018-04-30 10:35:51 -04:00
this.options.inputName = this.options.inputName || "default";
this.options.preventMouseDownDefault = this.options.preventMouseDownDefault || false;
2018-10-24 18:18:24 -04:00
2018-10-31 19:48:17 -04:00
/**
* @type {object} Classes identifying loaded plugins
*/
this.keyboardPluginClasses = '';
2018-10-30 23:28:23 -04:00
/**
* Bindings
*/
this.handleButtonClicked = this.handleButtonClicked.bind(this);
this.syncInstanceInputs = this.syncInstanceInputs.bind(this);
this.clearInput = this.clearInput.bind(this);
this.getInput = this.getInput.bind(this);
this.setInput = this.setInput.bind(this);
this.replaceInput = this.replaceInput.bind(this);
this.clear = this.clear.bind(this);
this.dispatch = this.dispatch.bind(this);
this.addButtonTheme = this.addButtonTheme.bind(this);
this.removeButtonTheme = this.removeButtonTheme.bind(this);
this.getButtonElement = this.getButtonElement.bind(this);
this.handleCaret = this.handleCaret.bind(this);
this.caretEventHandler = this.caretEventHandler.bind(this);
this.onInit = this.onInit.bind(this);
this.onRender = this.onRender.bind(this);
this.render = this.render.bind(this);
2018-10-31 17:57:33 -04:00
this.loadModules = this.loadModules.bind(this);
this.handleButtonMouseUp = this.handleButtonMouseUp.bind(this);
this.handleButtonMouseDown = this.handleButtonMouseDown.bind(this);
this.handleButtonHold = this.handleButtonHold.bind(this);
2018-11-01 00:16:11 -04:00
this.onModulesLoaded = this.onModulesLoaded.bind(this);
2018-10-30 23:28:23 -04:00
2018-10-24 18:18:24 -04:00
/**
* simple-keyboard uses a non-persistent internal input to keep track of the entered string (the variable `keyboard.input`).
* This removes any dependency to input DOM elements. You can type and directly display the value in a div element, for example.
* @example
* // To get entered input
* let input = keyboard.getInput();
*
* // To clear entered input.
* keyboard.clearInput();
*
* @type {object}
* @property {object} default Default SimpleKeyboard internal input.
* @property {object} myInputName Example input that can be set through `options.inputName:"myInputName"`.
*/
2018-04-30 10:35:51 -04:00
this.input = {};
this.input[this.options.inputName] = '';
2018-10-24 18:18:24 -04:00
/**
* @type {string} DOM class of the keyboard wrapper, normally "simple-keyboard" by default.
*/
2018-08-13 14:48:21 -04:00
this.keyboardDOMClass = keyboardDOMQuery.split('.').join("");
2018-10-24 18:18:24 -04:00
/**
* @type {object} Contains the DOM elements of every rendered button, the key being the button's layout name (e.g.: "{enter}").
*/
2018-10-06 02:17:54 -04:00
this.buttonElements = {};
2018-04-20 16:34:02 -04:00
/**
* Rendering keyboard
*/
if(this.keyboardDOM)
this.render();
2018-10-16 17:31:13 -04:00
else {
console.warn(`"${keyboardDOMQuery}" was not found in the DOM.`);
throw new Error("KEYBOARD_DOM_ERROR");
}
2018-09-23 23:36:01 -04:00
/**
* Saving instance
* This enables multiple simple-keyboard support with easier management
*/
if(!window['SimpleKeyboardInstances'])
window['SimpleKeyboardInstances'] = {};
2018-10-06 02:16:12 -04:00
window['SimpleKeyboardInstances'][this.utilities.camelCase(this.keyboardDOMClass)] = this;
2018-09-23 23:36:01 -04:00
2018-09-23 23:37:46 -04:00
/**
* Physical Keyboard support
*/
this.physicalKeyboardInterface = new PhysicalKeyboard(this);
2018-10-31 17:57:33 -04:00
/**
* Modules
*/
this.modules = {};
this.loadModules();
2018-04-20 16:34:02 -04:00
}
2018-10-31 17:57:33 -04:00
2018-10-24 18:18:24 -04:00
/**
* Handles clicks made to keyboard buttons
* @param {string} button The button's layout name.
*/
2018-10-30 23:28:23 -04:00
handleButtonClicked(button){
2018-04-20 16:34:02 -04:00
let debug = this.options.debug;
2018-10-06 02:26:22 -04:00
2018-04-20 16:34:02 -04:00
/**
* Ignoring placeholder buttons
*/
if(button === '{//}')
return false;
/**
* Calling onKeyPress
*/
if(typeof this.options.onKeyPress === "function")
this.options.onKeyPress(button);
2018-04-30 10:35:51 -04:00
if(!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
);
2018-04-20 16:34:02 -04:00
2018-04-30 10:35:51 -04:00
if(this.input[this.options.inputName] !== updatedInput){
2018-10-06 02:18:55 -04:00
/**
* 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] = this.utilities.getUpdatedInput(
button, this.input[this.options.inputName], this.options, this.caretPosition, true
);
2018-04-20 16:34:02 -04:00
if(debug)
console.log('Input changed:', this.input);
2018-09-23 23:36:01 -04:00
/**
2018-10-24 18:18:24 -04:00
* Enforce syncInstanceInputs, if set
2018-09-23 23:36:01 -04:00
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
2018-04-20 16:34:02 -04:00
/**
* Calling onChange
*/
if(typeof this.options.onChange === "function")
2018-04-30 10:35:51 -04:00
this.options.onChange(this.input[this.options.inputName]);
2018-04-20 16:34:02 -04:00
}
if(debug){
console.log("Key pressed:", button);
}
}
2018-10-31 17:57:33 -04:00
/**
* Handles button mousedown
*/
/* istanbul ignore next */
handleButtonMouseDown(button, e){
/**
* @type {boolean} Whether the mouse is being held onKeyPress
*/
this.isMouseHold = true;
2018-11-01 12:46:30 -04:00
if(this.holdInteractionTimeout)
clearTimeout(this.holdInteractionTimeout);
if(this.holdTimeout)
clearTimeout(this.holdTimeout);
2018-10-31 17:57:33 -04:00
/**
* @type {object} Time to wait until a key hold is detected
*/
this.holdTimeout = setTimeout(() => {
if(
this.isMouseHold &&
(
(!button.includes("{") && !button.includes("}")) ||
button === "{bksp}" ||
button === "{space}" ||
button === "{tab}"
)
){
if(this.options.debug)
console.log("Button held:", button);
this.handleButtonHold(button, e);
}
clearTimeout(this.holdTimeout);
}, 500);
}
/**
* Handles button mouseup
*/
handleButtonMouseUp(){
this.isMouseHold = false;
if(this.holdInteractionTimeout)
clearTimeout(this.holdInteractionTimeout);
}
/**
* Handles button hold
*/
/* istanbul ignore next */
handleButtonHold(button){
2018-11-03 01:39:41 -04:00
if(this.holdInteractionTimeout)
clearTimeout(this.holdInteractionTimeout);
2018-10-31 17:57:33 -04:00
/**
* @type {object} Timeout dictating the speed of key hold iterations
*/
this.holdInteractionTimeout = setTimeout(() => {
2018-11-03 01:39:41 -04:00
if(this.isMouseHold){
this.handleButtonClicked(button);
this.handleButtonHold(button);
} else {
clearTimeout(this.holdInteractionTimeout);
}
2018-10-31 17:57:33 -04:00
}, 100);
}
2018-10-24 18:18:24 -04:00
/**
* Send a command to all simple-keyboard instances (if you have several instances).
*/
2018-10-30 23:28:23 -04:00
syncInstanceInputs(){
2018-10-24 18:18:24 -04:00
this.dispatch((instance) => {
instance.replaceInput(this.input);
2018-09-23 23:36:01 -04:00
});
}
2018-10-24 18:18:24 -04:00
/**
* Clear the keyboards input.
2018-10-24 20:27:29 -04:00
* @param {string} [inputName] optional - the internal input to select
2018-10-24 18:18:24 -04:00
*/
2018-10-30 23:28:23 -04:00
clearInput(inputName){
2018-04-30 10:35:51 -04:00
inputName = inputName || this.options.inputName;
2018-11-19 09:25:27 -05:00
this.input[inputName] = '';
2018-09-23 23:36:01 -04:00
/**
2018-10-24 18:18:24 -04:00
* Enforce syncInstanceInputs, if set
2018-09-23 23:36:01 -04:00
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
2018-04-20 16:34:02 -04:00
}
2018-10-24 18:18:24 -04:00
/**
* Get the keyboards input (You can also get it from the onChange prop).
* @param {string} [inputName] optional - the internal input to select
*/
2018-10-30 23:28:23 -04:00
getInput(inputName){
2018-04-30 10:35:51 -04:00
inputName = inputName || this.options.inputName;
2018-09-23 23:36:01 -04:00
/**
2018-10-24 18:18:24 -04:00
* Enforce syncInstanceInputs, if set
2018-09-23 23:36:01 -04:00
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
2018-04-30 10:35:51 -04:00
return this.input[this.options.inputName];
2018-04-20 16:34:02 -04:00
}
2018-10-24 18:18:24 -04:00
/**
* Set the keyboards input.
* @param {string} input the input value
* @param {string} inputName optional - the internal input to select
*/
2018-10-30 23:28:23 -04:00
setInput(input, inputName){
2018-04-30 10:35:51 -04:00
inputName = inputName || this.options.inputName;
this.input[inputName] = input;
2018-09-23 23:36:01 -04:00
/**
2018-10-24 18:18:24 -04:00
* Enforce syncInstanceInputs, if set
2018-09-23 23:36:01 -04:00
*/
if(this.options.syncInstanceInputs)
this.syncInstanceInputs(this.input);
}
2018-10-24 18:18:24 -04:00
/**
* Replace the input object (`keyboard.input`)
* @param {object} inputObj The input object
*/
2018-10-30 23:28:23 -04:00
replaceInput(inputObj){
2018-09-23 23:36:01 -04:00
this.input = inputObj;
2018-04-20 16:34:02 -04:00
}
2018-10-24 18:18:24 -04:00
/**
* Set new option or modify existing ones after initialization.
* @param {object} option The option to set
*/
2018-04-20 16:34:02 -04:00
setOptions = option => {
option = option || {};
this.options = Object.assign(this.options, option);
this.render();
}
2018-10-24 18:18:24 -04:00
/**
* Remove all keyboard rows and reset keyboard values.
* Used interally between re-renders.
*/
2018-10-30 23:28:23 -04:00
clear(){
2018-04-20 16:34:02 -04:00
this.keyboardDOM.innerHTML = '';
2018-08-13 14:48:21 -04:00
this.keyboardDOM.className = this.keyboardDOMClass;
2018-10-06 02:22:02 -04:00
this.buttonElements = {};
2018-04-20 16:34:02 -04:00
}
2018-10-24 18:18:24 -04:00
/**
* Send a command to all simple-keyboard instances at once (if you have multiple instances).
* @param {function(instance: object, key: string)} callback Function to run on every instance
*/
2018-10-30 23:28:23 -04:00
dispatch(callback){
2018-09-23 23:36:01 -04:00
if(!window['SimpleKeyboardInstances']){
2018-10-16 17:31:13 -04:00
console.warn(`SimpleKeyboardInstances is not defined. Dispatch cannot be called.`);
throw new Error("INSTANCES_VAR_ERROR");
2018-09-23 23:36:01 -04:00
}
return Object.keys(window['SimpleKeyboardInstances']).forEach((key) => {
callback(window['SimpleKeyboardInstances'][key], key);
})
}
2018-10-24 18:18:24 -04:00
/**
* Adds/Modifies an entry to the `buttonTheme`. Basically a way to add a class to a button.
* @param {string} buttons List of buttons to select (separated by a space).
* @param {string} className Classes to give to the selected buttons (separated by space).
*/
2018-10-30 23:28:23 -04:00
addButtonTheme(buttons, className){
2018-10-06 02:26:00 -04:00
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();
}
2018-10-24 18:18:24 -04:00
/**
* Removes/Amends an entry to the `buttonTheme`. Basically a way to remove a class previously added to a button through buttonTheme or addButtonTheme.
* @param {string} buttons List of buttons to select (separated by a space).
* @param {string} className Classes to give to the selected buttons (separated by space).
*/
2018-10-30 23:28:23 -04:00
removeButtonTheme(buttons, className){
2018-10-06 02:26:00 -04:00
/**
* 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
){
2018-10-16 17:31:13 -04:00
let filteredButtonArray = buttonTheme.buttons.split(" ").filter(item => item !== button);
2018-10-06 02:26:00 -04:00
/**
* 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();
}
}
2018-10-06 02:17:54 -04:00
2018-10-24 18:18:24 -04:00
/**
* Get the DOM Element of a button. If there are several buttons with the same name, an array of the DOM Elements is returned.
* @param {string} button The button layout name to select
*/
2018-10-30 23:28:23 -04:00
getButtonElement(button){
2018-10-06 02:17:54 -04:00
let output;
let buttonArr = this.buttonElements[button];
if(buttonArr){
if(buttonArr.length > 1){
output = buttonArr;
} else {
output = buttonArr[0];
}
}
return output;
}
2018-10-24 18:18:24 -04:00
/**
* Retrieves the current cursor position within a input or textarea (if any)
*/
2018-10-30 23:28:23 -04:00
handleCaret(){
/**
* Only first instance should insall the caret handling events
*/
this.caretPosition = null;
let simpleKeyboardInstances = window['SimpleKeyboardInstances'];
if(
(
simpleKeyboardInstances &&
Object.keys(simpleKeyboardInstances)[0] === this.utilities.camelCase(this.keyboardDOMClass)
) ||
!simpleKeyboardInstances
){
2018-10-06 02:22:02 -04:00
if(this.options.debug){
console.log(`Caret handling started (${this.keyboardDOMClass})`)
2018-10-06 02:22:02 -04:00
}
2018-10-16 17:31:13 -04:00
document.addEventListener("keyup", this.caretEventHandler);
document.addEventListener("mouseup", this.caretEventHandler);
document.addEventListener("touchend", this.caretEventHandler);
}
}
2018-10-06 02:22:02 -04:00
2018-10-24 18:18:24 -04:00
/**
* Called by {@link handleCaret} when an event that warrants a cursor position update is triggered
*/
2018-10-30 23:28:23 -04:00
caretEventHandler(event){
2018-11-09 11:06:46 -05:00
let targetTagName;
if(event.target.tagName){
targetTagName = event.target.tagName.toLowerCase();
}
2018-10-06 02:22:02 -04:00
this.dispatch(instance => {
if(instance.isMouseHold){
instance.isMouseHold = false;
}
if(
(targetTagName === "textarea" ||
targetTagName === "input") &&
!instance.options.disableCaretPositioning
){
/**
* Tracks current cursor position
* As keys are pressed, text will be added/removed at that position within the input.
*/
instance.caretPosition = event.target.selectionStart;
2018-10-06 02:22:02 -04:00
if(instance.options.debug){
console.log("Caret at: ", event.target.selectionStart, event.target.tagName.toLowerCase(), `(${instance.keyboardDOMClass})`);
}
} else if(instance.options.disableCaretPositioning){
/**
* If we toggled off disableCaretPositioning, we must ensure caretPosition doesn't persist once reactivated.
*/
instance.caretPosition = null;
}
});
2018-10-06 02:22:02 -04:00
}
2018-10-24 18:18:24 -04:00
/**
* Executes the callback function once simple-keyboard is rendered for the first time (on initialization).
*/
2018-10-30 23:28:23 -04:00
onInit(){
2018-10-06 02:23:38 -04:00
if(this.options.debug){
console.log(`${this.keyboardDOMClass} Initialized`)
2018-10-06 02:23:38 -04:00
}
/**
* Caret handling
*/
this.handleCaret();
if(typeof this.options.onInit === "function")
this.options.onInit();
}
2018-10-24 18:18:24 -04:00
/**
* Executes the callback function every time simple-keyboard is rendered (e.g: when you change layouts).
*/
2018-10-30 23:28:23 -04:00
onRender(){
2018-10-06 02:24:04 -04:00
if(typeof this.options.onRender === "function")
this.options.onRender();
}
2018-11-01 00:16:11 -04:00
/**
* Executes the callback function once all modules have been loaded
*/
onModulesLoaded(){
if(typeof this.options.onModulesLoaded === "function")
this.options.onModulesLoaded();
}
2018-10-30 23:28:23 -04:00
/**
* Register module
*/
registerModule = (name, initCallback) => {
2018-10-31 17:57:33 -04:00
if(!this.modules[name])
this.modules[name] = {};
2018-10-30 23:28:23 -04:00
initCallback(this.modules[name]);
}
2018-10-31 17:57:33 -04:00
/**
* Load modules
*/
loadModules(){
if(Array.isArray(this.options.modules)){
this.options.modules.forEach(Module => {
let module = new Module();
/* istanbul ignore next */
if(module.constructor.name && module.constructor.name !== "Function"){
2018-10-31 19:48:17 -04:00
let classStr = `module-${this.utilities.camelCase(module.constructor.name)}`;
this.keyboardPluginClasses = this.keyboardPluginClasses + ` ${classStr}`;
2018-10-31 17:57:33 -04:00
}
module.init(this);
});
2018-11-01 00:16:11 -04:00
2018-12-14 00:28:18 -05:00
this.keyboardPluginClasses = this.keyboardPluginClasses + " modules-loaded";
2018-11-01 00:16:11 -04:00
this.render();
this.onModulesLoaded();
2018-10-31 17:57:33 -04:00
}
}
2018-10-30 23:28:23 -04:00
/**
* Get module prop
*/
getModuleProp = (name, prop) => {
if(!this.modules[name])
return false;
return this.modules[name][prop];
}
/**
* getModulesList
*/
getModulesList = () => {
return Object.keys(this.modules);
}
2018-10-24 18:18:24 -04:00
/**
* Renders rows and buttons as per options
*/
2018-10-30 23:28:23 -04:00
render(){
2018-04-20 16:34:02 -04:00
/**
* Clear keyboard
*/
this.clear();
let layoutClass = `hg-layout-${this.options.layoutName}`;
2018-10-16 17:31:13 -04:00
let layout = this.options.layout || KeyboardLayout.getDefaultLayout();
let useTouchEvents = this.options.useTouchEvents || false
2018-04-20 16:34:02 -04:00
/**
* Account for buttonTheme, if set
*/
let buttonThemesParsed = {};
if(Array.isArray(this.options.buttonTheme)){
this.options.buttonTheme.forEach(themeObj => {
if(themeObj.buttons && themeObj.class){
2018-10-16 17:31:13 -04:00
let themeButtons;
if(typeof themeObj.buttons === "string"){
2018-12-14 00:28:18 -05:00
themeButtons = themeObj.buttons.split(" ");
2018-10-16 17:31:13 -04:00
}
2018-10-16 17:31:13 -04:00
if(themeButtons){
themeButtons.forEach(themeButton => {
let themeParsed = buttonThemesParsed[themeButton];
// If the button has already been added
2018-10-16 17:31:13 -04:00
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;
2018-10-16 17:31:13 -04:00
}
});
}
} else {
console.warn(`buttonTheme row is missing the "buttons" or the "class". Please check the documentation.`)
}
});
}
2018-04-20 16:34:02 -04:00
/**
* Adding themeClass, layoutClass to keyboardDOM
*/
2018-10-31 19:48:17 -04:00
this.keyboardDOM.className += ` ${this.options.theme} ${layoutClass} ${this.keyboardPluginClasses}`;
2018-04-20 16:34:02 -04:00
/**
* Iterating through each row
*/
2018-10-06 02:25:04 -04:00
layout[this.options.layoutName].forEach((row, rIndex) => {
2018-12-14 00:28:18 -05:00
let rowArray = row.split(" ");
2018-04-20 16:34:02 -04:00
/**
* Creating empty row
*/
2018-12-14 00:28:18 -05:00
let rowDOM = document.createElement("div");
2018-04-20 16:34:02 -04:00
rowDOM.className += "hg-row";
/**
* Iterating through each button in row
*/
2018-10-06 02:25:04 -04:00
rowArray.forEach((button, bIndex) => {
2018-10-06 02:16:12 -04:00
let fctBtnClass = this.utilities.getButtonClass(button);
let buttonThemeClass = buttonThemesParsed[button];
2018-10-06 02:16:12 -04:00
let buttonDisplayName = this.utilities.getButtonDisplayName(button, this.options.display, this.options.mergeDisplay);
2018-04-20 16:34:02 -04:00
/**
* Creating button
*/
2018-12-14 00:28:18 -05:00
let buttonType = this.options.useButtonTag ? "button" : "div";
let buttonDOM = document.createElement(buttonType);
buttonDOM.className += `hg-button ${fctBtnClass}${buttonThemeClass ? " "+buttonThemeClass : ""}`;
if (useTouchEvents) {
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) => {
if (this.options.preventMouseDownDefault) e.preventDefault();
this.handleButtonMouseDown(button, e);
}
2018-11-03 01:39:41 -04:00
}
2018-10-06 02:25:04 -04:00
/**
* 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);
2018-10-16 17:31:13 -04:00
/**
* Adding display label
*/
buttonDOM.setAttribute("data-displayLabel", buttonDisplayName);
2018-04-20 16:34:02 -04:00
/**
* Adding button label to button
*/
2018-12-14 00:28:18 -05:00
let buttonSpanDOM = document.createElement('span');
2018-04-20 16:34:02 -04:00
buttonSpanDOM.innerHTML = buttonDisplayName;
buttonDOM.appendChild(buttonSpanDOM);
/**
2018-10-06 02:17:54 -04:00
* Adding to buttonElements
2018-04-20 16:34:02 -04:00
*/
2018-10-06 02:17:54 -04:00
if(!this.buttonElements[button])
this.buttonElements[button] = [];
this.buttonElements[button].push(buttonDOM);
2018-04-20 16:34:02 -04:00
/**
2018-10-06 02:25:04 -04:00
* Appending button to row
2018-04-20 16:34:02 -04:00
*/
2018-10-06 02:25:04 -04:00
rowDOM.appendChild(buttonDOM);
2018-04-20 16:34:02 -04:00
});
/**
* Appending row to keyboard
*/
this.keyboardDOM.appendChild(rowDOM);
});
2018-10-06 02:24:04 -04:00
/**
* Calling onRender
*/
this.onRender();
if(!this.initialized){
2018-10-24 18:18:24 -04:00
/**
* Ensures that onInit is only called once per instantiation
*/
2018-10-06 02:24:04 -04:00
this.initialized = true;
2018-11-19 09:29:49 -05:00
/**
* Handling mouseup
*/
if (!useTouchEvents) {
document.onmouseup = () => this.handleButtonMouseUp();
}
2018-10-06 02:24:04 -04:00
/**
* Calling onInit
*/
this.onInit();
}
2018-04-20 16:34:02 -04:00
}
}
export default SimpleKeyboard;