From 3c5b94abf866605a3285874ff8afe0d5a143a937 Mon Sep 17 00:00:00 2001
From: Francisco Hodge <hello@franciscohodge.com>
Date: Tue, 16 Oct 2018 17:31:13 -0400
Subject: [PATCH] 2.6.0 cleanup

---
 src/lib/components/Keyboard.js       | 71 ++++++++++++++++------------
 src/lib/services/KeyboardLayout.js   | 49 +++++++------------
 src/lib/services/PhysicalKeyboard.js |  5 --
 src/lib/services/Utilities.js        | 56 +++-------------------
 4 files changed, 65 insertions(+), 116 deletions(-)

diff --git a/src/lib/components/Keyboard.js b/src/lib/components/Keyboard.js
index ac2728cc..e5fb3902 100644
--- a/src/lib/components/Keyboard.js
+++ b/src/lib/components/Keyboard.js
@@ -37,8 +37,10 @@ class SimpleKeyboard {
      */
     if(this.keyboardDOM)
       this.render();
-    else
-      console.error(`"${keyboardDOMQuery}" was not found in the DOM.`);
+    else {
+      console.warn(`"${keyboardDOMQuery}" was not found in the DOM.`);
+      throw new Error("KEYBOARD_DOM_ERROR");
+    }
 
     /**
      * Saving instance
@@ -165,8 +167,8 @@ class SimpleKeyboard {
 
   dispatch = (callback) => {
     if(!window['SimpleKeyboardInstances']){
-      console.error("SimpleKeyboardInstances is not defined. Dispatch cannot be called.")
-      return false;
+      console.warn(`SimpleKeyboardInstances is not defined. Dispatch cannot be called.`);
+      throw new Error("INSTANCES_VAR_ERROR");
     }
     
     return Object.keys(window['SimpleKeyboardInstances']).forEach((key) => {
@@ -245,11 +247,7 @@ class SimpleKeyboard {
             (className && className.includes(buttonTheme.class)) ||
             !className
           ){
-            let filteredButtonArray;
-
-            if(buttonArray.includes(button)){
-              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
@@ -291,24 +289,24 @@ class SimpleKeyboard {
       console.log("Caret handling started");
     }
 
-    let handler = (event) => {
-      let targetTagName = event.target.tagName.toLowerCase();
+    document.addEventListener("keyup", this.caretEventHandler);
+    document.addEventListener("mouseup", this.caretEventHandler);
+    document.addEventListener("touchend", this.caretEventHandler);
+  }
 
-      if(
-        targetTagName === "textarea" ||
-        targetTagName === "input"
-      ){
-        this.caretPosition = event.target.selectionStart;
+  caretEventHandler = (event) => {
+    let targetTagName = event.target.tagName.toLowerCase();
 
-        if(this.options.debug){
-          console.log('Caret at: ', event.target.selectionStart, event.target.tagName.toLowerCase());
-        }     
-      }
-    };
+    if(
+      targetTagName === "textarea" ||
+      targetTagName === "input"
+    ){
+      this.caretPosition = event.target.selectionStart;
 
-    document.addEventListener("keyup", handler);
-    document.addEventListener("mouseup", handler);
-    document.addEventListener("touchend", handler);
+      if(this.options.debug){
+        console.log('Caret at: ', event.target.selectionStart, event.target.tagName.toLowerCase());
+      }     
+    }
   }
 
   onInit = () => {
@@ -337,7 +335,7 @@ class SimpleKeyboard {
     this.clear();
 
     let layoutClass = this.options.layout ? "hg-layout-custom" : `hg-layout-${this.options.layoutName}`;
-    let layout = this.options.layout || KeyboardLayout.getLayout(this.options.layoutName);
+    let layout = this.options.layout || KeyboardLayout.getDefaultLayout();
 
     /**
      * Account for buttonTheme, if set
@@ -346,17 +344,25 @@ class SimpleKeyboard {
     if(Array.isArray(this.options.buttonTheme)){
       this.options.buttonTheme.forEach(themeObj => {
         if(themeObj.buttons && themeObj.class){
-          let themeButtons = themeObj.buttons.split(' ');
+          let themeButtons;
 
-          if(Array.isArray(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)
-                buttonThemesParsed[themeButton] = `${themeParsed} ${themeObj.class}`;
-              else
+              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 {
@@ -409,6 +415,11 @@ class SimpleKeyboard {
         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
          */
diff --git a/src/lib/services/KeyboardLayout.js b/src/lib/services/KeyboardLayout.js
index c7e1e8dd..11191f52 100644
--- a/src/lib/services/KeyboardLayout.js
+++ b/src/lib/services/KeyboardLayout.js
@@ -1,37 +1,22 @@
 class KeyboardLayout {
-
-  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");
-    }
+  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}'
+      ]
+    } 
   }
-
 }
 
 export default KeyboardLayout;
\ No newline at end of file
diff --git a/src/lib/services/PhysicalKeyboard.js b/src/lib/services/PhysicalKeyboard.js
index 74af41a5..85c59290 100644
--- a/src/lib/services/PhysicalKeyboard.js
+++ b/src/lib/services/PhysicalKeyboard.js
@@ -2,11 +2,6 @@ class PhysicalKeyboard {
   constructor(simpleKeyboardInstance){
     this.simpleKeyboardInstance = simpleKeyboardInstance;
 
-    if(!window['SimpleKeyboardPhysicalKeyboardInit'])
-      window['SimpleKeyboardPhysicalKeyboardInit'] = true;
-    else
-      return false;
-
     this.initKeyboardListener();
   }
 
diff --git a/src/lib/services/Utilities.js b/src/lib/services/Utilities.js
index d9a87a60..fc5ff360 100644
--- a/src/lib/services/Utilities.js
+++ b/src/lib/services/Utilities.js
@@ -3,56 +3,13 @@ class Utilities {
     this.simpleKeyboardInstance = simpleKeyboardInstance;
   }
 
-  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 if(string === ".com")
-      output = 'com';
-    else
-      output = '';
-
-    return output ? ` hg-button-${output}` : '';
-  }
-
   getButtonClass = button => {
     let buttonTypeClass = (button.includes("{") && button.includes("}") && button !== '{//}') ? "functionBtn" : "standardBtn";
     let buttonWithoutBraces = button.replace("{", "").replace("}", "");
+    let buttonNormalized = '';
 
-    let buttonNormalized =
-      buttonTypeClass === "standardBtn" ?
-        this.normalizeString(buttonWithoutBraces) : ` hg-button-${buttonWithoutBraces}`;
+    if(buttonTypeClass !== "standardBtn")
+      buttonNormalized = ` hg-button-${buttonWithoutBraces}`;
 
     return `hg-${buttonTypeClass}${buttonNormalized}`;
   }
@@ -161,9 +118,6 @@ class Utilities {
     else if(button === "{numpadadd}")
       output = this.addStringAt(output, '+', caretPos);
 
-    else if(button === "{numpadadd}")
-      output = this.addStringAt(output, '+', caretPos);
-
     else if(button === "{numpaddecimal}")
       output = this.addStringAt(output, '.', caretPos);
 
@@ -305,6 +259,10 @@ class Utilities {
     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;
\ No newline at end of file