<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../../">
  <title data-ice="title">src/lib/components/Keyboard.js | simple-keyboard</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">
  <script src="script/prettify/prettify.js"></script>
  <script src="script/manual.js"></script>
<meta name="description" content="On-screen Javascript Virtual Keyboard"><meta property="twitter:card" content="summary"><meta property="twitter:title" content="simple-keyboard"><meta property="twitter:description" content="On-screen Javascript Virtual Keyboard"></head>
<body class="layout-container" data-ice="rootContainer">

<header>
  <a href="./">Home</a>
  
  <a href="identifiers.html">Reference</a>
  <a href="source.html">Source</a>
  
  <div class="search-box">
  <span>
    <img src="./image/search.png">
    <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span>
  </span>
    <ul class="search-result"></ul>
  </div>
<a style="position:relative; top:3px;" href="https://github.com/hodgef/simple-keyboard"><img width="20px" src="./image/github.png"></a></header>

<nav class="navigation" data-ice="nav"><div>
  <ul>
    
  <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#demo">demo</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/demo/App.js~App.html">App</a></span></span></li>
<li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#lib-components">lib/components</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/lib/components/Keyboard.js~SimpleKeyboard.html">SimpleKeyboard</a></span></span></li>
<li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#lib-services">lib/services</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/lib/services/KeyboardLayout.js~KeyboardLayout.html">KeyboardLayout</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/lib/services/PhysicalKeyboard.js~PhysicalKeyboard.html">PhysicalKeyboard</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/lib/services/Utilities.js~Utilities.html">Utilities</a></span></span></li>
<li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#lib-tests">lib/tests</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/lib/tests/TestUtility.js~TestUtility.html">TestUtility</a></span></span></li>
</ul>
</div>
</nav>

<div class="content" data-ice="content"><h1 data-ice="title">src/lib/components/Keyboard.js</h1>
<pre class="source-code line-number raw-source-code"><code class="prettyprint linenums" data-ice="content">import &apos;./Keyboard.css&apos;;

// Services
import PhysicalKeyboard from &apos;../services/PhysicalKeyboard&apos;;
import KeyboardLayout from &apos;../services/KeyboardLayout&apos;;
import Utilities from &apos;../services/Utilities&apos;;

/**
 * Root class for simple-keyboard
 * This class:
 * - Parses the options
 * - Renders the rows and buttons
 * - Handles button functionality
 */
class SimpleKeyboard {
  /**
   * 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.
   */
  constructor(...params){
    let keyboardDOMQuery = typeof params[0] === &quot;string&quot; ? params[0] : &apos;.simple-keyboard&apos;;
    let options = typeof params[0] === &quot;object&quot; ? params[0] : params[1];

    if(!options)
      options = {};

    /**
     * Initializing Utilities
     */
    this.utilities = new Utilities(this);

    /**
     * Processing options
     */
    this.keyboardDOM = document.querySelector(keyboardDOMQuery);

    /**
     * @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.: &#x201C;backspace&#x201D;).
     * @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 &#x201C;ENTER&#x201D; button will input a newline (\n) or not.
     * @property {boolean} tabCharOnTab Specifies whether clicking the &#x201C;TAB&#x201D; 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 element&#x2019;s maxlengthattribute.
     * @property {object} maxLength Restrains simple-keyboard&#x2019;s individual inputs to a certain length. This should be used in addition to the input element&#x2019;s 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.
     * @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.
     * @property {function(button: string):string} onKeyPress Executes the callback function on key press. Returns button layout name (i.e.: &#x201C;{shift}&#x201D;).
     * @property {function(input: string):string} onChange Executes the callback function on input change. Returns the current input&#x2019;s 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.
     */
    this.options = options;
    this.options.layoutName = this.options.layoutName || &quot;default&quot;;
    this.options.theme = this.options.theme || &quot;hg-theme-default&quot;;
    this.options.inputName = this.options.inputName || &quot;default&quot;;
    this.options.preventMouseDownDefault = this.options.preventMouseDownDefault === false ? false : true;

    /**
     * @type {object} Classes identifying loaded plugins
     */
    this.keyboardPluginClasses = &apos;&apos;;

    /**
     * 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);
    this.loadModules = this.loadModules.bind(this);
    this.handleButtonMouseUp = this.handleButtonMouseUp.bind(this);
    this.handleButtonMouseDown = this.handleButtonMouseDown.bind(this);
    this.handleButtonHold = this.handleButtonHold.bind(this);
    this.onModulesLoaded = this.onModulesLoaded.bind(this);

    /**
     * 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:&quot;myInputName&quot;`.
     */
    this.input = {};
    this.input[this.options.inputName] = &apos;&apos;;

    /**
     * @type {string} DOM class of the keyboard wrapper, normally &quot;simple-keyboard&quot; by default.
     */
    this.keyboardDOMClass = keyboardDOMQuery.split(&apos;.&apos;).join(&quot;&quot;);

    /**
     * @type {object} Contains the DOM elements of every rendered button, the key being the button&apos;s layout name (e.g.: &quot;{enter}&quot;).
     */
    this.buttonElements = {};

    /**
     * Rendering keyboard
     */
    if(this.keyboardDOM)
      this.render();
    else {
      console.warn(`&quot;${keyboardDOMQuery}&quot; was not found in the DOM.`);
      throw new Error(&quot;KEYBOARD_DOM_ERROR&quot;);
    }

    /**
     * Saving instance
     * This enables multiple simple-keyboard support with easier management
     */
    if(!window[&apos;SimpleKeyboardInstances&apos;])
      window[&apos;SimpleKeyboardInstances&apos;] = {};
      
    window[&apos;SimpleKeyboardInstances&apos;][this.utilities.camelCase(this.keyboardDOMClass)] = this;

    /**
     * Physical Keyboard support
     */
    this.physicalKeyboardInterface = new PhysicalKeyboard(this);

    /**
     * Modules
     */
    this.modules = {};
    this.loadModules();
  }

  /**
   * Handles clicks made to keyboard buttons
   * @param  {string} button The button&apos;s layout name.
   */
  handleButtonClicked(button){
    let debug = this.options.debug;

    /**
     * Ignoring placeholder buttons
     */
    if(button === &apos;{//}&apos;)
      return false;

    /**
     * Calling onKeyPress
     */
    if(typeof this.options.onKeyPress === &quot;function&quot;)
      this.options.onKeyPress(button);
    
    if(!this.input[this.options.inputName])
      this.input[this.options.inputName] = &apos;&apos;;

    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 &amp;&amp; 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
      );

      if(debug)
        console.log(&apos;Input changed:&apos;, this.input);

      /**
       * Enforce syncInstanceInputs, if set
       */
      if(this.options.syncInstanceInputs)
        this.syncInstanceInputs(this.input);

      /**
       * Calling onChange
       */
      if(typeof this.options.onChange === &quot;function&quot;)
        this.options.onChange(this.input[this.options.inputName]);
    }
    
    if(debug){
      console.log(&quot;Key pressed:&quot;, button);
    }
  }

  /**
   * Handles button mousedown
   */
  /* istanbul ignore next */
  handleButtonMouseDown(button, e){
    /**
     * @type {boolean} Whether the mouse is being held onKeyPress
     */
    this.isMouseHold = true;

    if(this.holdInteractionTimeout)
      clearTimeout(this.holdInteractionTimeout);

    if(this.holdTimeout)
      clearTimeout(this.holdTimeout);

    /**
     * @type {object} Time to wait until a key hold is detected
     */
    this.holdTimeout = setTimeout(() =&gt; {
      if(
        this.isMouseHold  &amp;&amp;
        (
          (!button.includes(&quot;{&quot;) &amp;&amp; !button.includes(&quot;}&quot;)) ||
          button === &quot;{bksp}&quot; ||
          button === &quot;{space}&quot; ||
          button === &quot;{tab}&quot;
        )
      ){
        if(this.options.debug)
          console.log(&quot;Button held:&quot;, 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){
    if(this.holdInteractionTimeout)
      clearTimeout(this.holdInteractionTimeout);

    /**
     * @type {object} Timeout dictating the speed of key hold iterations
     */
    this.holdInteractionTimeout = setTimeout(() =&gt; {
      if(this.isMouseHold){
        this.handleButtonClicked(button);
        this.handleButtonHold(button);
      } else {
        clearTimeout(this.holdInteractionTimeout);
      }
    }, 100);
  }

  /**
   * Send a command to all simple-keyboard instances (if you have several instances).
   */
  syncInstanceInputs(){
    this.dispatch((instance) =&gt; {
      instance.replaceInput(this.input);
    });
  }
  
  /**
   * Clear the keyboard&#x2019;s input.
   * @param {string} [inputName] optional - the internal input to select
   */
  clearInput(inputName){
    inputName = inputName || this.options.inputName;
    this.input[inputName] = &apos;&apos;;

    /**
     * Enforce syncInstanceInputs, if set
     */
    if(this.options.syncInstanceInputs)
      this.syncInstanceInputs(this.input);
  }

  /**
   * Get the keyboard&#x2019;s input (You can also get it from the onChange prop).
   * @param  {string} [inputName] optional - the internal input to select
   */
  getInput(inputName){
    inputName = inputName || this.options.inputName;

    /**
     * Enforce syncInstanceInputs, if set
     */
    if(this.options.syncInstanceInputs)
      this.syncInstanceInputs(this.input);

    return this.input[this.options.inputName];
  }

  /**
   * Set the keyboard&#x2019;s input.
   * @param  {string} input the input value
   * @param  {string} inputName optional - the internal input to select
   */
  setInput(input, inputName){
    inputName = inputName || this.options.inputName;
    this.input[inputName] = input;

    /**
     * Enforce syncInstanceInputs, if set
     */
    if(this.options.syncInstanceInputs)
      this.syncInstanceInputs(this.input);
  }
  
  /**
   * Replace the input object (`keyboard.input`)
   * @param  {object} inputObj The input object
   */
  replaceInput(inputObj){
    this.input = inputObj;
  }

  /**
   * Set new option or modify existing ones after initialization. 
   * @param  {object} option The option to set
   */
  setOptions = option =&gt; {
    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 = &apos;&apos;;
    this.keyboardDOM.className = this.keyboardDOMClass;
    this.buttonElements = {};
  }

  /**
   * 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
   */
  dispatch(callback){
    if(!window[&apos;SimpleKeyboardInstances&apos;]){
      console.warn(`SimpleKeyboardInstances is not defined. Dispatch cannot be called.`);
      throw new Error(&quot;INSTANCES_VAR_ERROR&quot;);
    }
    
    return Object.keys(window[&apos;SimpleKeyboardInstances&apos;]).forEach((key) =&gt; {
      callback(window[&apos;SimpleKeyboardInstances&apos;][key], key);
    })
  }

  /**
   * 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).
   */
  addButtonTheme(buttons, className){
    if(!className || !buttons)
      return false;

    buttons.split(&quot; &quot;).forEach(button =&gt; {
      className.split(&quot; &quot;).forEach(classNameItem =&gt; {
        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 =&gt; {

          if(buttonTheme.class.split(&quot; &quot;).includes(classNameItem)){
            classNameFound = true;
            
            let buttonThemeArray = buttonTheme.buttons.split(&quot; &quot;);
            if(!buttonThemeArray.includes(button)){
              classNameFound = true;
              buttonThemeArray.push(button);
              buttonTheme.buttons = buttonThemeArray.join(&quot; &quot;);
            }
          }
          return buttonTheme;
        });

        /**
         * If class is not defined, we create a new entry
         */
        if(!classNameFound){
          this.options.buttonTheme.push({
            class: classNameItem,
            buttons: buttons
          });
        }

      });
    });

    this.render();
  }

  /**
   * 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).
   */
  removeButtonTheme(buttons, className){
    /**
     * When called with empty parameters, remove all button themes
     */
    if(!buttons &amp;&amp; !className){
      this.options.buttonTheme = [];
      this.render();
      return false;
    }

    /**
     * If buttons are passed and buttonTheme has items
     */
    if(buttons &amp;&amp; Array.isArray(this.options.buttonTheme) &amp;&amp; this.options.buttonTheme.length){
      let buttonArray = buttons.split(&quot; &quot;);
      buttonArray.forEach((button, key) =&gt; {
        this.options.buttonTheme.map((buttonTheme, index) =&gt; {

          /**
           * If className is set, we affect the buttons only for that class
           * Otherwise, we afect all classes
           */
          if(
            (className &amp;&amp; className.includes(buttonTheme.class)) ||
            !className
          ){
            let filteredButtonArray = buttonTheme.buttons.split(&quot; &quot;).filter(item =&gt; item !== button);

            /**
             * If buttons left, return them, otherwise, remove button Theme
             */
            if(filteredButtonArray.length){
              buttonTheme.buttons = filteredButtonArray.join(&quot; &quot;);
            } else {
              this.options.buttonTheme.splice(index, 1);
              buttonTheme = null;
            }
 
          }

          return buttonTheme;
        });
      });

      this.render();
    }
  }

  /**
   * 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
   */
  getButtonElement(button){
    let output;

    let buttonArr = this.buttonElements[button];
    if(buttonArr){
      if(buttonArr.length &gt; 1){
        output = buttonArr;
      } else {
        output = buttonArr[0];
      }
    }

    return output;
  }

  /**
   * Retrieves the current cursor position within a input or textarea (if any)
   */
  handleCaret(){
    /**
     * Only first instance should insall the caret handling events
     */
    this.caretPosition = null;
    let simpleKeyboardInstances = window[&apos;SimpleKeyboardInstances&apos;];

    if(
      (
        simpleKeyboardInstances &amp;&amp;
        Object.keys(simpleKeyboardInstances)[0] === this.utilities.camelCase(this.keyboardDOMClass)
      ) ||
      !simpleKeyboardInstances
    ){
    if(this.options.debug){
        console.log(`Caret handling started (${this.keyboardDOMClass})`)
    }

    document.addEventListener(&quot;keyup&quot;, this.caretEventHandler);
    document.addEventListener(&quot;mouseup&quot;, this.caretEventHandler);
    document.addEventListener(&quot;touchend&quot;, this.caretEventHandler);
  }
  }

  /**
   * Called by {@link handleCaret} when an event that warrants a cursor position update is triggered
   */
  caretEventHandler(event){
    let targetTagName;
    if(event.target.tagName){
      targetTagName = event.target.tagName.toLowerCase();
    }

    this.dispatch(instance =&gt; {
      if(instance.isMouseHold){
        instance.isMouseHold = false;
    }

    if(
      (targetTagName === &quot;textarea&quot; ||
      targetTagName === &quot;input&quot;) &amp;&amp;
        !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;

        if(instance.options.debug){
          console.log(&apos;Caret at: &apos;, event.target.selectionStart, event.target.tagName.toLowerCase(), `(${instance.keyboardDOMClass})`);
      }     
    }
    });
  }

  /**
   * Executes the callback function once simple-keyboard is rendered for the first time (on initialization).
   */
  onInit(){
    if(this.options.debug){
      console.log(`${this.keyboardDOMClass} Initialized`)
    }

    /**
     * Caret handling
     */
    this.handleCaret();

    if(typeof this.options.onInit === &quot;function&quot;)
      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 === &quot;function&quot;)
      this.options.onRender();
  }

 /**
  * Executes the callback function once all modules have been loaded
  */
  onModulesLoaded(){
    if(typeof this.options.onModulesLoaded === &quot;function&quot;)
      this.options.onModulesLoaded();
  }

  /**
   * Register module
   */
  registerModule = (name, initCallback) =&gt; {
    if(!this.modules[name])
      this.modules[name] = {};

    initCallback(this.modules[name]);
  }

  /**
   * Load modules
   */
  loadModules(){
    if(Array.isArray(this.options.modules)){
      this.options.modules.forEach(Module =&gt; {
        let module = new Module();

        /* istanbul ignore next */
        if(module.constructor.name &amp;&amp; module.constructor.name !== &quot;Function&quot;){
          let classStr = `module-${this.utilities.camelCase(module.constructor.name)}`;
          this.keyboardPluginClasses = this.keyboardPluginClasses + ` ${classStr}`;
        }

        module.init(this);
      });

      this.keyboardPluginClasses = this.keyboardPluginClasses + &apos; modules-loaded&apos;;

      this.render();
      this.onModulesLoaded();
    }
  }

  /**
   * Get module prop
   */
  getModuleProp = (name, prop) =&gt; {
    if(!this.modules[name])
      return false;
    
    return this.modules[name][prop];
  }

  /**
   * getModulesList
   */
  getModulesList = () =&gt; {
    return Object.keys(this.modules);
  }

  /**
   * Renders rows and buttons as per options
   */
  render(){
    /**
     * Clear keyboard
     */
    this.clear();

    let layoutClass = this.options.layout ? &quot;hg-layout-custom&quot; : `hg-layout-${this.options.layoutName}`;
    let layout = this.options.layout || KeyboardLayout.getDefaultLayout();
    let useTouchEvents = this.options.useTouchEvents || false

    /**
     * Account for buttonTheme, if set
     */
    let buttonThemesParsed = {};
    if(Array.isArray(this.options.buttonTheme)){
      this.options.buttonTheme.forEach(themeObj =&gt; {
        if(themeObj.buttons &amp;&amp; themeObj.class){
          let themeButtons;

          if(typeof themeObj.buttons === &quot;string&quot;){
            themeButtons = themeObj.buttons.split(&apos; &apos;);
          }

          if(themeButtons){
            themeButtons.forEach(themeButton =&gt; {
              let themeParsed = buttonThemesParsed[themeButton];

              // If the button has already been added
              if(themeParsed){
                // Making sure we don&apos;t add duplicate classes, even when buttonTheme has duplicates
                if(!this.utilities.countInArray(themeParsed.split(&quot; &quot;), themeObj.class)){
                  buttonThemesParsed[themeButton] = `${themeParsed} ${themeObj.class}`;
                }
              } else {
                buttonThemesParsed[themeButton] = themeObj.class;
              }
            });
          }
        } else {
          console.warn(`buttonTheme row is missing the &quot;buttons&quot; or the &quot;class&quot;. Please check the documentation.`)
        }
      });
    }

    /**
     * Adding themeClass, layoutClass to keyboardDOM
     */
    this.keyboardDOM.className += ` ${this.options.theme} ${layoutClass} ${this.keyboardPluginClasses}`;

    /**
     * Iterating through each row
     */
    layout[this.options.layoutName].forEach((row, rIndex) =&gt; {
      let rowArray = row.split(&apos; &apos;);

      /**
       * Creating empty row
       */
      var rowDOM = document.createElement(&apos;div&apos;);
      rowDOM.className += &quot;hg-row&quot;;

      /**
       * Iterating through each button in row
       */
      rowArray.forEach((button, bIndex) =&gt; {
        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(&apos;div&apos;);
        buttonDOM.className += `hg-button ${fctBtnClass}${buttonThemeClass ? &quot; &quot;+buttonThemeClass : &quot;&quot;}`;
        
        if (useTouchEvents) {
          buttonDOM.ontouchstart = (e) =&gt; {
            this.handleButtonClicked(button);
            this.handleButtonMouseDown(button, e);
          }
          buttonDOM.ontouchend = e =&gt; this.handleButtonMouseUp();
          buttonDOM.ontouchcancel = e =&gt; this.handleButtonMouseUp();
        } else {
          buttonDOM.onclick = () =&gt; {
            this.isMouseHold = false;
            this.handleButtonClicked(button);
          }
          buttonDOM.onmousedown = (e) =&gt; {
            if (this.options.preventMouseDownDefault) e.preventDefault();
            this.handleButtonMouseDown(button, e);
          }
        }
        
        /**
         * Adding identifier
         */
        buttonDOM.setAttribute(&quot;data-skBtn&quot;, button);

        /**
         * Adding unique id
         * Since there&apos;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(&quot;data-skBtnUID&quot;, buttonUID);

        /**
         * Adding display label
         */
        buttonDOM.setAttribute(&quot;data-displayLabel&quot;, buttonDisplayName);

        /**
         * Adding button label to button
         */
        var buttonSpanDOM = document.createElement(&apos;span&apos;);
        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){
      /**
       * Ensures that onInit is only called once per instantiation
       */
      this.initialized = true;

      /**
       * Handling mouseup
       */
      if (!useTouchEvents) {
        document.onmouseup = () =&gt; this.handleButtonMouseUp();
      }

      /**
       * Calling onInit
       */
      this.onInit();
    }
  }
}

export default SimpleKeyboard;
</code></pre>

</div>

<footer class="footer">
  Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(1.1.0)</span><img src="./image/esdoc-logo-mini-black.png"></a>
</footer>

<script src="script/search_index.js"></script>
<script src="script/search.js"></script>
<script src="script/pretty-print.js"></script>
<script src="script/inherited-summary.js"></script>
<script src="script/test-summary.js"></script>
<script src="script/inner-link.js"></script>
<script src="script/patch-for-local.js"></script>
</body>
</html>