### Quick Start Guide Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/README.md A guide to getting started with simple-keyboard, covering installation, basic setup, and common usage patterns with code examples. ```APIDOC ## Quick Start This guide provides instructions for installing and setting up `simple-keyboard`. ### Installation - **npm**: `npm install simple-keyboard` - **CDN**: Include the library via a script tag. ### Basic Setup 1. **HTML Structure**: Add an input element and a container for the keyboard. 2. **JavaScript Initialization**: Instantiate `SimpleKeyboard` with desired options. ### Common Use Cases - **Input Management**: Handling input from the virtual keyboard. - **Button Interaction**: Responding to key presses. - **Layout Management**: Switching between different keyboard layouts. Refer to the `quick-start.md` file for complete working examples and detailed explanations. ``` -------------------------------- ### Basic HTML Setup with Simple Keyboard Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md This example shows a complete HTML file that includes the Simple Keyboard CSS and JavaScript, and initializes a keyboard instance. It handles input changes and key presses. ```html
``` -------------------------------- ### Basic Keyboard Setup Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/configuration.md Instantiate a Simple Keyboard with default settings. ```javascript const keyboard = new SimpleKeyboard(); ``` -------------------------------- ### Complete SimpleKeyboard Setup with Physical Keyboard Integration Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/physical-keyboard.md Demonstrates initializing SimpleKeyboard with options for physical keyboard highlighting. When a physical key is pressed, the corresponding on-screen button highlights, and the character is typed. The highlight is removed on key release. This setup requires `physicalKeyboardHighlight`, `physicalKeyboardHighlightPress`, and related styling options. ```javascript const keyboard = new SimpleKeyboard({ layout: { default: ['a b c', 'd e f', '{shift} {bksp} {enter}'] }, physicalKeyboardHighlight: true, physicalKeyboardHighlightPress: true, physicalKeyboardHighlightBgColor: '#2196F3', physicalKeyboardHighlightTextColor: 'white', physicalKeyboardHighlightPreventDefault: true, debug: true }); // User interaction: // 1. User presses 'A' on physical keyboard // 2. console.log shows: "handleHighlightKeyDown: a" // 3. On-screen 'a' button highlights in blue // 4. 'a' is automatically typed // 5. User releases 'A' // 6. Highlight is removed // 7. console.log shows: "handleHighlightKeyUp: a" ``` -------------------------------- ### Install Local Simple-Keyboard in React Project Source: https://github.com/hodgef/simple-keyboard/wiki/Home Use this command to install a local version of simple-keyboard into your react-simple-keyboard project for debugging React-specific issues. Ensure you replace 'C:\path-to-simple-keyboard' with the actual path to your local simple-keyboard directory. ```bash npm install C:\path-to-simple-keyboard ``` -------------------------------- ### Initialize SimpleKeyboard with Options Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/configuration.md Pass configuration options when creating a new SimpleKeyboard instance. This example shows basic layout, theme, and display options. ```javascript const keyboard = new SimpleKeyboard({ layout: { /* ... */ }, theme: 'hg-theme-default', display: { /* ... */ }, // ... more options }); ``` -------------------------------- ### Example KeyboardButtonAttributes Usage Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/types.md This example demonstrates how to create an array of KeyboardButtonAttributes to apply custom data attributes and ARIA labels to specific buttons like backspace and shift. ```typescript const buttonAttributes: KeyboardButtonAttributes[] = [ { attribute: 'data-key', value: 'backspace', buttons: '{bksp}' }, { attribute: 'aria-label', value: 'Shift', buttons: '{shift}' } ]; ``` -------------------------------- ### Handle Initialization Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md The `onInit` callback is executed once the keyboard is fully initialized. Use it to set focus to an input field or perform other setup tasks. ```javascript const keyboard = new Simple Keyboard({ onInit: (instance) => { console.log('Keyboard ready'); // Set focus to input field document.getElementById('input').focus(); } }); ``` -------------------------------- ### Complete Callback Setup with Simple Keyboard Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/events-callbacks.md Demonstrates the full range of callbacks available during keyboard initialization, rendering, input changes, and button interactions. Use these to hook into the keyboard's lifecycle and user events. ```javascript const keyboard = new SimpleKeyboard({ // Lifecycle onInit: (instance) => { console.log('1. Keyboard initialized'); console.log('Buttons available:', Object.keys(instance.buttonElements)); }, onRender: (instance) => { console.log('2. Keyboard rendered'); console.log('Current layout:', instance.getOptions().layoutName); }, // Input changes onChange: (input) => { console.log('3. Input changed:', input); document.getElementById('output').textContent = input; }, onChangeAll: (inputs) => { console.log('3b. All inputs:', inputs); }, beforeInputUpdate: (instance) => { console.log('3a. [Before] Input about to change'); }, // Button interactions onKeyPress: (button) => { console.log('4. Button pressed:', button); }, onKeyReleased: (button) => { console.log('5. Button released:', button); } }); ``` -------------------------------- ### Install simple-keyboard with npm or yarn Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Use npm or yarn to add simple-keyboard to your project dependencies. ```bash npm install simple-keyboard # or yarn add simple-keyboard ``` -------------------------------- ### Import and Get Default Layout Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/keyboard-layout.md Demonstrates how to import and retrieve the default QWERTY keyboard layout from the simple-keyboard library. ```typescript import { getDefaultLayout } from 'simple-keyboard'; const defaultLayout = getDefaultLayout(); ``` -------------------------------- ### JavaScript Usage of onKeyPress Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/events-callbacks.md Example of how to implement the onKeyPress callback to log button presses and specific actions. ```javascript new SimpleKeyboard({ onKeyPress: (button, e) => { console.log('Button pressed:', button); if (button === '{enter}') { console.log('User pressed enter'); } } }); ``` -------------------------------- ### Basic JavaScript Setup for simple-keyboard Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Initialize simple-keyboard, import its CSS, and set up an onChange handler to update an input field. Ensure the caret position is managed on focus. ```javascript import SimpleKeyboard from 'simple-keyboard'; import 'simple-keyboard/build/index.css'; const keyboard = new SimpleKeyboard({ onChange: (input) => { document.getElementById('input').value = input; } }); document.getElementById('input').addEventListener('focus', (e) => { keyboard.setCaretPosition(e.target.selectionStart); }); ``` -------------------------------- ### Get Keyboard Options Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieves the current configuration options of the keyboard instance. ```typescript getOptions(): KeyboardOptions ``` -------------------------------- ### Enable Layout Candidates with Custom Mappings Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/candidate-box.md Configure the candidate box to display suggestions based on trigger strings. This example sets up mappings for vowels and specifies a page size of 3. ```javascript const keyboard = new SimpleKeyboard({ enableLayoutCandidates: true, layoutCandidates: { 'a': 'á à ä â ǎ ā', 'e': 'é è ë ê ě ē', 'i': 'í ì ï î ǐ ī', 'o': 'ó ò ö ô ǒ ō', 'u': 'ú ù ü û ǔ ū' }, layoutCandidatesPageSize: 3, onChange: (input) => { console.log('Input:', input); } }); ``` -------------------------------- ### SimpleKeyboard Class API Reference Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/README.md This section details the complete API for the SimpleKeyboard class, including all public methods, constructor, initialization, and usage examples. ```APIDOC ## SimpleKeyboard Class API This document outlines the public API of the `SimpleKeyboard` class. It covers the constructor, initialization process, and all available methods with their signatures and usage examples. ### Constructor and Initialization - **`new SimpleKeyboard(options)`**: Initializes a new instance of the SimpleKeyboard. - **`options`** (object) - Optional configuration object for the keyboard. ### Public Methods This section lists over 40 public methods available on the `SimpleKeyboard` instance. Each method includes its signature, parameters, and a brief description of its functionality. *Example Method Signature:* ```javascript myKeyboard.someMethod(param1: string, param2: number): boolean; ``` Refer to the `api-reference.md` file for the complete list of methods and detailed examples. ``` -------------------------------- ### PhysicalKeyboard Constructor Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/physical-keyboard.md The PhysicalKeyboard service is instantiated internally by SimpleKeyboard. It requires parameters for getting keyboard options and dispatching actions. ```typescript constructor(params: PhysicalKeyboardParams) ``` -------------------------------- ### Convert to Camel Case Example - JavaScript Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Demonstrates converting a hyphenated string to camelCase. ```javascript utilities.camelCase('my-keyboard'); // Returns 'myKeyboard' ``` -------------------------------- ### Example Keyboard Layout Row Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/keyboard-layout.md Illustrates a row string within a keyboard layout, where button names are separated by spaces. ```javascript { default: [ "` 1 2 3 4 5 6 7 8 9 0 - = {bksp}", // Row 1 "{tab} q w e r t y u i o p [ ] \", // Row 2 "{lock} a s d f g h j k l ; ' {enter}", // Row 3 "{shift} z x c v b n m , . / {shift}", // Row 4 ".com @ {space}" // Row 5 ] } ``` -------------------------------- ### Keyboard Layout Customization Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/README.md Guide to creating and managing custom keyboard layouts, including syntax, function buttons, and internationalization. ```APIDOC ## Keyboard Layout Customization This document explains the structure and syntax for defining custom keyboard layouts. ### Layout Structure - **Syntax**: Defines the format for rows, buttons, and special keys. - **Function Buttons**: Reference for over 40 special buttons (e.g., Shift, Backspace, Enter). ### Advanced Features - **Multiple Layouts**: Support for switching between different layouts. - **Internationalization**: Guidelines for creating language-specific layouts. Refer to the `keyboard-layout.md` file for detailed syntax, examples, and a list of all function buttons. ``` -------------------------------- ### Add String Example - JavaScript Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Demonstrates inserting a string into another string at a specific index. If no index is provided, the string is appended. ```javascript utilities.addStringAt('hello', 'X', 2); // Returns 'heXllo' utilities.addStringAt('hello', 'X'); // Returns 'helloX' ``` -------------------------------- ### Update SimpleKeyboard Options After Initialization Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/configuration.md Modify the configuration of an existing SimpleKeyboard instance using the `setOptions` method. This example updates the layout name and enables debugging. ```javascript keyboard.setOptions({ layoutName: 'shift', debug: true }); ``` -------------------------------- ### UtilitiesParams Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/types.md Defines the parameters required for initializing the Utilities service. These include functions to get keyboard options, caret position, and a dispatch function. ```APIDOC ## UtilitiesParams Parameters for Utilities service initialization. ```typescript interface UtilitiesParams { getOptions: () => KeyboardOptions; getCaretPosition: () => number | null; getCaretPositionEnd: () => number | null; dispatch: any; } ``` ``` -------------------------------- ### Basic Physical Keyboard Integration Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/physical-keyboard.md Enable basic highlighting of on-screen buttons when corresponding physical keys are pressed. No additional setup is required beyond enabling the option. ```javascript const keyboard = new SimpleKeyboard({ physicalKeyboardHighlight: true }); // Now when user presses physical keyboard keys, // the on-screen buttons are highlighted ``` -------------------------------- ### onKeyPress Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/events-callbacks.md Callback fired when a button is pressed (mouse down or touch start). It also fires for physical keyboard presses if `physicalKeyboardHighlightPress` is enabled. ```APIDOC ## onKeyPress(button, e) ### Description Fired when a button is pressed (mouse down or touch start). ### Parameters #### Path Parameters - **button** (string) - Required - Button layout name (e.g., `'a'`, `'{enter}'`) - **e** (MouseEvent) - Optional - Event object ### Request Example ```javascript new SimpleKeyboard({ onKeyPress: (button, e) => { console.log('Button pressed:', button); if (button === '{enter}') { console.log('User pressed enter'); } } }); ``` ### When Fired - On mouse down / touch start on a button - Also fires for physical keyboard presses if `physicalKeyboardHighlightPress` is enabled - Fires for all buttons, including functional buttons ``` -------------------------------- ### Get and Set Keyboard Input Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/INDEX.md Manage the input value of the keyboard. Use `getAllInputs` to retrieve all named inputs. ```javascript keyboard.getInput(); // Get current input keyboard.setInput('text'); // Set input keyboard.clearInput(); // Clear input keyboard.getAllInputs(); // Get all named inputs ``` -------------------------------- ### Set Button Attributes Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Configure custom attributes for specific buttons during keyboard initialization. This example sets 'data-action' and 'aria-label' for the '{bksp}' button. ```javascript const keyboard = new Simple Keyboard({ buttonAttributes: [ { attribute: 'data-action', value: 'delete', buttons: '{bksp}' }, { attribute: 'aria-label', value: 'Delete', buttons: '{bksp}' } ] }); ``` -------------------------------- ### Get Caret Position Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieves the current start position of the cursor in the input field. Returns null if the position is not set. ```typescript getCaretPosition(): number | null ``` -------------------------------- ### Right-to-Left (RTL) Layout Support Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/configuration.md Enable right-to-left text direction for layouts, suitable for languages that read from right to left. Includes an example layout. ```javascript const keyboard = new SimpleKeyboard({ rtl: true, layout: { default: ['ا ب ج د ه', 'و ز ح ط ي'] } }); ``` -------------------------------- ### Get Input Candidates Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieves candidate suggestions for a given input string based on the `layoutCandidates` configuration. Ensure `layoutCandidates` is set in the keyboard options before calling. ```typescript getInputCandidates( input: string ): { candidateKey: string; candidateValue: string } | Record ``` ```javascript keyboard.setOptions({ layoutCandidates: { 'a': 'á à ä â', 'e': 'é è ë ê' } }); const candidates = keyboard.getInputCandidates('a'); // Returns: { candidateKey: 'a', candidateValue: 'á à ä â' } ``` -------------------------------- ### Remove Characters After Position Example - JavaScript Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Example of removing characters from a string after a given index. ```javascript utilities.removeForwardsAt('hello', 2); // Returns 'helo' ``` -------------------------------- ### Remove Characters Before Position Example - JavaScript Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Example of removing characters from a string before a given index. ```javascript utilities.removeAt('hello', 2); // Returns 'hllo' ``` -------------------------------- ### Initialize Keyboard with Layouts Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Set up a new Simple Keyboard instance with custom default and 'numbers' layouts. The initial layout is set to 'default'. ```javascript const keyboard = new SimpleKeyboard({ layout: { default: ['a b c', 'd e f'], numbers: ['1 2 3', '4 5 6'] }, layoutName: 'default' }); ``` -------------------------------- ### onInit(instance) Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/events-callbacks.md Fired once when the keyboard is first rendered, indicating that the initialization is complete. It receives the keyboard instance as an argument. ```APIDOC ## onInit(instance) ### Description Fired once when the keyboard is first rendered (initialization complete). ### Parameters #### Path Parameters - **instance** (SimpleKeyboard) - Required - The keyboard instance ### Request Example ```javascript new SimpleKeyboard({ onInit: (instance) => { console.log('Keyboard initialized'); // Focus on input field, load data, etc. } }); ``` ### Response #### Success Response (200) - **instance** (SimpleKeyboard) - The keyboard instance ### Timing Called after first render and event listeners are attached. ``` -------------------------------- ### Get Current Input Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieves the current input value from the keyboard. ```APIDOC ## Get Current Input ### Description Retrieves the current input value from the keyboard. ### Method ```javascript keyboard.getInput() ``` ### Returns - `string`: The current input value. ``` -------------------------------- ### Performance Monitoring with Callbacks Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/events-callbacks.md Implement performance monitoring by tracking key presses and elapsed time using `onInit` and `onChange` callbacks. This allows for calculating metrics like keys per second. ```javascript const metrics = { keyPresses: 0, totalTime: 0, startTime: null }; new SimpleKeyboard({ onInit: (instance) => { metrics.startTime = Date.now(); console.log('Session started'); }, onKeyPress: (button) => { metrics.keyPresses++; }, onChange: (input) => { if (input.length % 10 === 0) { const elapsed = Date.now() - metrics.startTime; const kps = (metrics.keyPresses / elapsed) * 1000; console.log(`${metrics.keyPresses} keys in ${elapsed}ms (${kps.toFixed(2)} keys/sec)`); } } }); ``` -------------------------------- ### Get Button DOM Element Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieves the DOM element for a specific button. ```APIDOC ## Get Button DOM Element ### Description Retrieves the DOM element for a specific button. ### Method ```javascript keyboard.getButtonElement(buttonKey: string) ``` ### Parameters #### Path Parameters - **buttonKey** (string) - Required - The key of the button whose DOM element is to be retrieved. ### Returns - `HTMLElement | null`: The DOM element of the button, or null if not found. ``` -------------------------------- ### onModulesLoaded(instance) Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/events-callbacks.md Fired once all modules have been fully loaded and initialized. This callback receives the keyboard instance. ```APIDOC ## onModulesLoaded(instance) ### Description Fired once all modules are fully loaded and initialized. ### Parameters #### Path Parameters - **instance** (SimpleKeyboard) - Required - The keyboard instance ### Request Example ```javascript new SimpleKeyboard({ modules: [AutocorrectModule, InputMaskModule], onModulesLoaded: (instance) => { console.log('All modules loaded'); // Initialize module-specific features } }); ``` ### Response #### Success Response (200) - **instance** (SimpleKeyboard) - The keyboard instance ``` -------------------------------- ### Initialize SimpleKeyboard Instance Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Create a new SimpleKeyboard instance using a CSS selector, a DOM element, or an options object. Options can configure layout, themes, and display properties. ```javascript const keyboard = new SimpleKeyboard('.hg-theme-default', { layout: { default: ['a b c', 'd e f'] } }); ``` ```javascript const container = document.querySelector('.my-keyboard'); const keyboard = new SimpleKeyboard(container, { theme: 'hg-theme-dark' }); ``` ```javascript const keyboard = new SimpleKeyboard({ display: { '{bksp}': 'backspace', '{enter}': 'enter' } }); ``` -------------------------------- ### Get Caret Position Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieves the current caret position or the end position of a selection. ```APIDOC ## Get Caret Position ### Description Retrieves the current caret position or the end of a selected range. ### Method `keyboard.getCaretPosition(): number | null` `keyboard.getCaretPositionEnd(): number | null` ### Parameters None ### Response #### Success Response - **position** (number | null) - The current caret position, or null if not set. - **endPosition** (number | null) - The end of the caret selection, or null if not set. ### Request Example ```javascript const pos = keyboard.getCaretPosition(); const endPos = keyboard.getCaretPositionEnd(); ``` ``` -------------------------------- ### Keyboard Initialization Callback Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/configuration.md The onInit callback is executed once when the keyboard is first initialized and rendered. ```javascript new SimpleKeyboard({ onInit: (instance) => { console.log('Keyboard initialized'); } }); ``` -------------------------------- ### Get All Inputs Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieves all stored input values, including default and named inputs. ```APIDOC ## Get All Inputs ### Description Retrieves all stored input values, including default and named inputs. ### Method ```javascript keyboard.getAllInputs() ``` ### Returns - `object`: An object containing all input values, keyed by their names (e.g., `{ default: "...", input2: "..." }`). ``` -------------------------------- ### Events and Callbacks Reference Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/README.md Comprehensive documentation on all callback functions, their parameters, and how to handle keyboard events. ```APIDOC ## Events and Callbacks This section details all callback functions that can be used to interact with `simple-keyboard` events. ### Callback Functions - **`onChange(input: string)`**: Triggered when the keyboard input value changes. - **`onKeyPress(button: string)`**: Triggered when a virtual keyboard button is pressed. ### Event Lifecycle - **Execution Order**: Describes the sequence in which events and callbacks are fired. Refer to the `events-callbacks.md` file for a complete list of callbacks, their parameters, and practical usage examples. ``` -------------------------------- ### SimpleKeyboard Constructor Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Initializes a new instance of the SimpleKeyboard. It can be configured using a CSS selector, a DOM element, or an options object. ```APIDOC ## SimpleKeyboard Constructor Creates a new SimpleKeyboard instance. ### Parameters #### Path Parameters - **selectorOrOptions** (string | HTMLDivElement | KeyboardOptions) - Optional - If string: CSS class selector for keyboard container. If HTMLDivElement: the keyboard DOM element (must have a class). If KeyboardOptions: options object, keyboard will use `.simple-keyboard` selector. - **keyboardOptions** (KeyboardOptions) - Optional - Options object when first parameter is a string or HTMLDivElement. ### Request Example ```javascript // Using CSS selector const keyboard = new SimpleKeyboard('.hg-theme-default', { layout: { default: ['a b c', 'd e f'] } }); // Using DOM element const container = document.querySelector('.my-keyboard'); const keyboard = new SimpleKeyboard(container, { theme: 'hg-theme-dark' }); // Using options object only (uses .simple-keyboard selector) const keyboard = new SimpleKeyboard({ display: { '{bksp}': 'backspace', '{enter}': 'enter' } }); ``` ``` -------------------------------- ### Keyboard Initialization Callback (onInit) Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/events-callbacks.md Fired once when the keyboard is first rendered. Use this to perform actions after initialization, such as focusing an input field or loading data. ```typescript onInit?: (instance: SimpleKeyboard) => void ``` ```javascript new SimpleKeyboard({ onInit: (instance) => { console.log('Keyboard initialized'); // Focus on input field, load data, etc. } }); ``` -------------------------------- ### Get All Keyboard Inputs Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieve all defined input fields and their current values. This is useful for multi-input scenarios. ```javascript const allInputs = keyboard.getAllInputs(); // Returns: { default: "...", input2: "...", ... } ``` -------------------------------- ### Get Loaded Modules List Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieves an array containing the names of all modules currently loaded with the keyboard instance. ```typescript getModulesList(): string[] ``` -------------------------------- ### Create Keyboard Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/INDEX.md Instantiate a new Simple Keyboard object to initialize the keyboard interface. ```APIDOC ## Create Keyboard Instantiate a new Simple Keyboard object to initialize the keyboard interface. ### Method ```javascript new SimpleKeyboard(); ``` ``` -------------------------------- ### Keyboard Options Configuration Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/README.md Details all available configuration options for initializing and customizing the simple-keyboard, including default values and callback function references. ```APIDOC ## Keyboard Options The `SimpleKeyboard` constructor accepts an `options` object to customize its behavior and appearance. This section details all available configuration properties. ### Core Options - **`layout`** (object | string) - Defines the keyboard layout. Can be an object literal or a reference to a predefined layout. - **`theme`** (string) - Specifies the CSS theme to apply to the keyboard. - **`display`** (object) - Maps button names to their display text. - **`maxLength`** (number) - Maximum input length. - **`inputPattern`** (RegExp) - Regular expression to validate input. ### Callback Options - **`onChange`** (function) - Called when the keyboard input changes. - Parameters: `input` (string) - **`onKeyPress`** (function) - Called when a key is pressed. - Parameters: `button` (string) Refer to the `configuration.md` file for a comprehensive list of all options, default values, and advanced settings. ``` -------------------------------- ### Import SimpleKeyboard Main Export Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/INDEX.md Import the main SimpleKeyboard class from the library. This is the primary way to instantiate and use the keyboard. ```typescript import SimpleKeyboard from 'simple-keyboard'; ``` -------------------------------- ### Initialize with RTL Support Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Initializes the Simple Keyboard with support for Right-to-Left (RTL) languages. ```APIDOC ## RTL (Right-to-Left) Support ### Description Initializes the Simple Keyboard with the `rtl: true` option to enable proper rendering and input handling for Right-to-Left languages. ### Method `new SimpleKeyboard(options)` ### Parameters #### Options - **rtl** (boolean) - Required - Set to `true` to enable RTL support. - **layout** (object) - Required - Defines the keyboard layout, including RTL-specific characters. ### Request Example ```javascript const keyboard = new SimpleKeyboard({ rtl: true, layout: { default: ['ا ب ج د', 'ه و ز ح', '{bksp} {space} {enter}'] } }); ``` ``` -------------------------------- ### Basic HTML Structure for simple-keyboard Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Set up the necessary HTML elements for the input field and the keyboard container. ```html
``` -------------------------------- ### getCaretPosition Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Returns the current cursor start position. This method is useful for retrieving the current position of the cursor within the input field. ```APIDOC ## getCaretPosition() ### Description Returns the current cursor start position. ### Method ```typescript getCaretPosition(): number | null ``` ### Response #### Success Response (200) - **return value** (number | null) - The cursor position, or null if not set. ### Request Example ```javascript const cursorPosition = keyboard.getCaretPosition(); ``` ``` -------------------------------- ### registerModule(name, initCallback) Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Registers a new module with the keyboard instance, providing a name and an initialization callback. ```APIDOC ## registerModule(name, initCallback) ### Description Registers a module with the keyboard instance. ### Method ```typescript registerModule(name: string, initCallback: any): void ``` ### Parameters #### Path Parameters - **name** (string) - Required - Module name. - **initCallback** (function) - Required - Callback to initialize the module. ``` -------------------------------- ### KeyboardOptions Interface Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/types.md The `KeyboardOptions` interface outlines all available configuration properties for initializing and customizing the SimpleKeyboard instance. This includes layout, display, theming, event handlers, and various behavioral options. ```APIDOC ## KeyboardOptions ### Description Configuration object for SimpleKeyboard initialization and runtime options. ### Interface ```typescript interface KeyboardOptions { layout?: KeyboardLayoutObject; layoutName?: string; display?: { [button: string]: string }; mergeDisplay?: boolean; theme?: string; buttonTheme?: KeyboardButtonTheme[]; buttonAttributes?: KeyboardButtonAttributes[]; debug?: boolean; newLineOnEnter?: boolean; tabCharOnTab?: boolean; inputName?: string; maxLength?: any; syncInstanceInputs?: boolean; physicalKeyboardHighlight?: boolean; physicalKeyboardHighlightPress?: boolean; physicalKeyboardHighlightUseClick?: boolean; physicalKeyboardHighlightPressUsePointerEvents?: boolean; physicalKeyboardHighlightTextColor?: string; physicalKeyboardHighlightBgColor?: string; physicalKeyboardHighlightPreventDefault?: boolean; preventMouseDownDefault?: boolean; preventMouseUpDefault?: boolean; stopMouseDownPropagation?: boolean; stopMouseUpPropagation?: boolean; useButtonTag?: boolean; disableCaretPositioning?: boolean; inputPattern?: any; useTouchEvents?: boolean; autoUseTouchEvents?: boolean; useMouseEvents?: boolean; disableButtonHold?: boolean; rtl?: boolean; enableLayoutCandidates?: boolean; layoutCandidates?: { [key: string]: string }; excludeFromLayout?: { [key: string]: string[] }; layoutCandidatesPageSize?: number; layoutCandidatesCaseSensitiveMatch?: boolean; disableCandidateNormalization?: boolean; enableLayoutCandidatesKeyPress?: boolean; updateCaretOnSelectionChange?: boolean; clickOnMouseDown?: boolean; onRender?: (instance: SimpleKeyboard) => void; onInit?: (instance: SimpleKeyboard) => void; onChange?: (input: string, e?: MouseEvent) => any; onChangeAll?: (inputObj: KeyboardInput, e?: MouseEvent) => any; onKeyPress?: (button: string, e?: MouseEvent) => any; onKeyReleased?: (button: string, e?: MouseEvent) => any; beforeInputUpdate?: (instance: SimpleKeyboard) => void; [name: string]: any; } ``` ``` -------------------------------- ### Get Current Keyboard Input Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieve the current text value from the keyboard input field. This is useful for reading user input. ```javascript const currentInput = keyboard.getInput(); console.log(currentInput); ``` -------------------------------- ### Create Keyboard with Custom Display and Merged Display Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Initialize a keyboard with a custom layout and define custom display text for specific buttons. `mergeDisplay: true` ensures custom displays are used. ```javascript const keyboard = new Simple Keyboard({ layout: { custom: [ 'Hello World !', '{bksp} {space} {enter}' ] }, display: { 'Hello': 'HI', 'World': 'WORLD' }, mergeDisplay: true }); ``` -------------------------------- ### Get Module Property Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieves a specific property from a loaded module by its name. Returns the property value or false if the module or property is not found. ```typescript getModuleProp(name: string, prop: string): any ``` -------------------------------- ### Enable Physical Keyboard Integration Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/README.md Configure the keyboard to visually highlight physical key presses. Set `physicalKeyboardHighlight` to true to enable highlighting and `physicalKeyboardHighlightPress` to true to highlight on press. ```javascript new SimpleKeyboard({ physicalKeyboardHighlight: true, physicalKeyboardHighlightPress: true }); ``` -------------------------------- ### Get Caret End Position Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieves the current end position of the cursor (for text selection) in the input field. Returns null if not set. ```typescript getCaretPositionEnd(): number | null ``` -------------------------------- ### Access Global Keyboard Instances Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Provides access to all globally managed Simple Keyboard instances. ```APIDOC ## Access Global Instances ### Description All instances of Simple Keyboard are stored in a global object `window.SimpleKeyboardInstances`. This allows you to access and manage multiple keyboard instances from anywhere in your application. ### Method `window.SimpleKeyboardInstances` ### Parameters None ### Response #### Success Response - **instances** (object) - An object containing all keyboard instances, keyed by their assigned names. ### Request Example ```javascript // All keyboard instances are stored globally const instances = window.SimpleKeyboardInstances; // Access by class name const keyboard1 = instances.simpleKeyboard; const keyboard2 = instances.myKeyboard; // List all instances Object.keys(instances).forEach(key => { console.log('Instance:', key, instances[key]); }); ``` ``` -------------------------------- ### Get All Keyboard Inputs Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieve all named inputs as a key-value object. This is useful for accessing the state of multiple inputs managed by the keyboard instance. ```javascript const allInputs = keyboard.getAllInputs(); console.log(allInputs); // { default: "hello", email: "user@example.com" } ``` -------------------------------- ### Get Button Display Name Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Retrieves the display label for a given button. It can use custom display objects and merge them with default labels. ```typescript getButtonDisplayName( button: string, display?: object, mergeDisplay?: boolean ): string ``` ```javascript utilities.getButtonDisplayName('{bksp}', { '{bksp}': 'del' }); // Returns 'del' utilities.getButtonDisplayName('{enter}'); // Returns 'enter' (default) ``` -------------------------------- ### Get Default Display Labels Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Returns the default button display labels. This method maps button names to their default display text. ```typescript getDefaultDiplay(): object ``` -------------------------------- ### Load Keyboard Modules Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Integrate external modules like autocorrect by passing them in the `modules` array during keyboard initialization. Ensure the module is imported first. ```javascript import SimpleKeyboard from 'simple-keyboard'; import AutocorrectModule from 'simple-keyboard-autocorrect'; const keyboard = new SimpleKeyboard({ modules: [AutocorrectModule] }); ``` -------------------------------- ### onRender(instance) Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/events-callbacks.md Fired every time the keyboard is rendered, which includes layout changes. It provides the keyboard instance for potential UI updates. ```APIDOC ## onRender(instance) ### Description Fired every time the keyboard is rendered (including layout changes). ### Parameters #### Path Parameters - **instance** (SimpleKeyboard) - Required - The keyboard instance ### Request Example ```javascript new SimpleKeyboard({ onRender: (instance) => { console.log('Keyboard rendered'); // Update UI, adjust styling, etc. } }); ``` ### Response #### Success Response (200) - **instance** (SimpleKeyboard) - The keyboard instance ### When Called - After initialization (onInit also fires) - After `render()` is called - After `setOptions()` with layout changes - After modules are loaded ``` -------------------------------- ### Get Button Class Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Generates CSS class names for a button element based on its layout name. This is useful for applying styles to buttons. ```typescript getButtonClass(button: string): string ``` ```javascript // Returns 'hg-functionBtn hg-button-enter' utilities.getButtonClass('{enter}'); // Returns 'hg-standardBtn' utilities.getButtonClass('a'); ``` -------------------------------- ### Switch Layouts Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Allows switching between predefined keyboard layouts. ```APIDOC ## Switch Layouts ### Description Allows switching between predefined keyboard layouts. ### Method ```javascript keyboard.setOptions({ layoutName: string }) ``` ### Parameters #### Request Body - **layoutName** (string) - Required - The name of the layout to switch to. ``` -------------------------------- ### Dynamically Switch Keyboard Layouts Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/keyboard-layout.md Define multiple layouts and switch between them dynamically using `setOptions`. Event listeners are used to trigger layout changes. ```javascript const keyboard = new SimpleKeyboard({ layout: { default: ['a b c', 'd e f', '{shift} {space}'], uppercase: ['A B C', 'D E F', '{shift} {space}'], numbers: ['1 2 3', '4 5 6', '7 8 9', '0'] }, layoutName: 'default' }); // Switch layouts document.getElementById('shiftBtn').addEventListener('click', () => { const newLayout = keyboard.getOptions().layoutName === 'default' ? 'uppercase' : 'default'; keyboard.setOptions({ layoutName: newLayout }); }); // Number layout document.getElementById('numberBtn').addEventListener('click', () => { keyboard.setOptions({ layoutName: 'numbers' }); }); ``` -------------------------------- ### PhysicalKeyboardParams Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/types.md Specifies the parameters needed for initializing the PhysicalKeyboard service, including functions to retrieve keyboard options and a dispatch function. ```APIDOC ## PhysicalKeyboardParams Parameters for PhysicalKeyboard service initialization. ```typescript interface PhysicalKeyboardParams { getOptions: () => KeyboardOptions; dispatch: any; } ``` ``` -------------------------------- ### IME and Layout Candidate Configuration Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/configuration.md Configure support for Input Method Editors (IMEs) and custom layout candidates, including case sensitivity and pagination. ```javascript const keyboard = new SimpleKeyboard({ enableLayoutCandidates: true, layoutCandidates: { 'a': 'á à ä â α ā ǎ ǎ', 'e': 'é è ë ê ε ē ě' }, layoutCandidatesPageSize: 4, layoutCandidatesCaseSensitiveMatch: false }); ``` -------------------------------- ### Get Button DOM Element Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieve the DOM element for a specific button, such as '{enter}'. This allows direct manipulation of the button's appearance or behavior. ```javascript const enterBtn = keyboard.getButtonElement('{enter}'); if (enterBtn) { enterBtn.style.backgroundColor = 'green'; } ``` -------------------------------- ### setOptions(options) Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Updates keyboard options after initialization and triggers a re-render. Accepts a partial options object. ```APIDOC ## setOptions(options) Updates keyboard options after initialization and triggers a re-render. ### Parameters #### Path Parameters - **options** (Partial) - Optional - Object containing options to update. ### Request Example ```javascript keyboard.setOptions({ theme: 'hg-theme-dark', layoutName: 'shift', display: { '{bksp}': 'delete' } }); ``` ``` -------------------------------- ### Get Keyboard Input Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieve the current input string for a specific input name or the default input. Optionally skip synchronization if `syncInstanceInputs` is enabled. ```javascript const input = keyboard.getInput(); console.log(input); // "hello" ``` ```javascript const secondInput = keyboard.getInput('email'); ``` -------------------------------- ### File Organization Structure Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/README.md This tree displays the directory structure of the Simple Keyboard project, indicating the purpose of each file. ```tree output/ ├── README.md (This file) ├── INDEX.md (Master navigation) ├── api-reference.md (SimpleKeyboard API) ├── types.md (Type definitions) ├── configuration.md (Options reference) ├── utilities-service.md (Utilities API) ├── candidate-box.md (IME component) ├── physical-keyboard.md (Keyboard integration) ├── keyboard-layout.md (Layout system) ├── events-callbacks.md (Callbacks & events) └── quick-start.md (Getting started) ``` -------------------------------- ### Get Caret Position in Simple Keyboard Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieve the current caret position or the end of a selection using `getCaretPosition` and `getCaretPositionEnd`. These methods are essential for input tracking. ```javascript const pos = keyboard.getCaretPosition(); const endPos = keyboard.getCaretPositionEnd(); ``` -------------------------------- ### Access Module Properties Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Retrieve properties from loaded modules using `getModuleProp` or get a list of all loaded modules with `getModulesList`. This allows for dynamic module interaction. ```javascript const moduleProp = keyboard.getModuleProp('autocorrect', 'enabled'); const moduleList = keyboard.getModulesList(); ``` -------------------------------- ### SKWindow Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/types.md An extended Window interface that provides access to globally available SimpleKeyboard instances via `window.SimpleKeyboardInstances`. ```APIDOC ## SKWindow Extended Window interface for accessing SimpleKeyboard instances globally. ```typescript interface SKWindow extends Window { SimpleKeyboardInstances?: any; } ``` Access all keyboard instances via `window.SimpleKeyboardInstances`. ``` -------------------------------- ### Get Button Element Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieves the DOM element associated with a button. Returns a single element, an array if multiple buttons share a name, or undefined if not found. ```typescript getButtonElement( button: string ): KeyboardElement | KeyboardElement[] | undefined ``` ```javascript const enterBtn = keyboard.getButtonElement('{enter}'); enterBtn.style.backgroundColor = 'green'; const shiftBtns = keyboard.getButtonElement('{shift}'); // Returns array if multiple shift buttons exist ``` -------------------------------- ### syncInstanceInputs Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Synchronizes input across all SimpleKeyboard instances when `syncInstanceInputs` option is enabled. This ensures consistency if multiple keyboard instances are used. ```APIDOC ## syncInstanceInputs() ### Description Synchronizes input across all SimpleKeyboard instances when `syncInstanceInputs` option is enabled. ### Method ```typescript syncInstanceInputs(): void ``` ### Response #### Success Response (200) - **return value** (void) ### Request Example ```javascript keyboard.syncInstanceInputs(); ``` ``` -------------------------------- ### dispatch Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Executes a callback function on all SimpleKeyboard instances. This allows for batch operations or applying logic across all keyboard instances. ```APIDOC ## dispatch(callback) ### Description Executes a callback function on all SimpleKeyboard instances. ### Method ```typescript dispatch(callback: (instance: SimpleKeyboard, key?: string) => void): void ``` ### Parameters #### Path Parameters - **callback** (function) - Required - Function receiving each instance and its key. ### Request Example ```javascript keyboard.dispatch((instance, key) => { console.log(`Instance: ${key}`, instance.getInput()); }); ``` ``` -------------------------------- ### getButtonDisplayName(button, display?, mergeDisplay?) Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Gets the display label for a specific button, optionally merging custom display objects. Returns the determined display string. ```APIDOC ## getButtonDisplayName(button, display?, mergeDisplay?) ### Description Returns the display label for a button. ### Method ```typescript getButtonDisplayName( button: string, display?: object, mergeDisplay?: boolean ): string ``` ### Parameters #### Path Parameters - **button** (string) - Required - Button layout name - **display** (object) - Optional - Custom display object - **mergeDisplay** (boolean) - Optional - Default: false - Whether to merge with defaults ### Returns string — The display label for the button. ### Example ```javascript utilities.getButtonDisplayName('{bksp}', { '{bksp}': 'del' }); // Returns 'del' utilities.getButtonDisplayName('{enter}'); // Returns 'enter' (default) ``` ``` -------------------------------- ### Get Button Type Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Determines if a button is a function button or a standard button based on its layout name. Use this to apply different styling or behavior to function keys. ```typescript getButtonType(button: string): string ``` ```javascript // Returns 'functionBtn' utilities.getButtonType('{enter}'); // Returns 'standardBtn' utilities.getButtonType('a'); ``` -------------------------------- ### getOptions() Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Retrieves the current options object of the keyboard instance. ```APIDOC ## getOptions() ### Description Retrieves the current options object. ### Method ```typescript getOptions(): KeyboardOptions ``` ### Response #### Success Response (200) - **KeyboardOptions** (object) - The current configuration of the keyboard. ``` -------------------------------- ### Custom Theme and Display Options Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/configuration.md Configure a custom theme and override default button displays for specific keys. ```javascript const keyboard = new SimpleKeyboard({ theme: 'hg-theme-dark', display: { '{bksp}': 'delete', '{enter}': 'return', '{shift}': 'shift' } }); ``` -------------------------------- ### Get Updated Input Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/utilities-service.md Calculates the new input string after a button press, handling character insertion, backspace, and delete operations. It can also manage caret position updates. ```typescript getUpdatedInput( button: string, input: string, caretPos: number | undefined, caretPosEnd?: number, moveCaret?: boolean ): string ``` ```javascript // Add character let result = utilities.getUpdatedInput('a', 'hello', 5); // Returns 'helloa' // Backspace at position 2 result = utilities.getUpdatedInput('{bksp}', 'hello', 2); // Returns 'hllo' // Delete at position 2 result = utilities.getUpdatedInput('{delete}', 'hello', 2); // Returns 'helo' ``` -------------------------------- ### Default Configuration Options Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/INDEX.md These are the default configuration options for the Simple Keyboard. Many more options are available. ```javascript { layoutName: 'default', theme: 'hg-theme-default', inputName: 'default', debug: false, enableLayoutCandidates: true, excludeFromLayout: {}, preventMouseDownDefault: false, // ... many more } ``` -------------------------------- ### Multiple Inputs and Synchronization Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/configuration.md Manage multiple input fields by setting an initial input name and enabling synchronization. Switch inputs later using setOptions. ```javascript const keyboard = new SimpleKeyboard({ inputName: 'default', syncInstanceInputs: true }); // Later, switch to another input keyboard.setOptions({ inputName: 'email' }); ``` -------------------------------- ### Include simple-keyboard via CDN Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/quick-start.md Link the CSS and JavaScript files from a CDN to use simple-keyboard in a browser environment. ```html ``` -------------------------------- ### Physical Keyboard Integration Using Pointer Events Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/physical-keyboard.md Configure the keyboard to use pointer events (pointerdown/pointerup) for physical key press simulation. This offers better compatibility with stylus and multi-touch input methods. ```javascript const keyboard = new SimpleKeyboard({ physicalKeyboardHighlight: true, physicalKeyboardHighlightPress: true, physicalKeyboardHighlightPressUsePointerEvents: true }); // Uses pointerdown/pointerup events // Better support for stylus and multi-touch scenarios ``` -------------------------------- ### Dispatch Callback to Instances Source: https://github.com/hodgef/simple-keyboard/blob/master/_autodocs/api-reference.md Executes a callback function on all Simple Keyboard instances. The callback receives the instance and its key. ```typescript dispatch(callback: (instance: SimpleKeyboard, key?: string) => void): void ``` ```javascript keyboard.dispatch((instance, key) => { console.log(`Instance: ${key}`, instance.getInput()); }); ```