mirror of
https://github.com/hodgef/simple-keyboard.git
synced 2026-07-14 00:00:06 +08:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d88be11a42 | ||
|
|
e2ee5a4158 | ||
|
|
4b162eaec7 | ||
|
|
715a9c4a90 | ||
|
|
df32ed440e | ||
|
|
12fe2cca75 | ||
|
|
dddd45a220 | ||
|
|
857942811c | ||
|
|
832ecbaa2c | ||
|
|
ad5284ceb3 | ||
|
|
9a47421260 | ||
|
|
d27b94c6d9 | ||
|
|
e1cfcdd673 | ||
|
|
3c3a049b3f | ||
|
|
a8c5ffd401 | ||
|
|
d06baf7222 | ||
|
|
afbdddb008 | ||
|
|
41b1ae2941 | ||
|
|
e7411c6845 | ||
|
|
4f1111b49e | ||
|
|
a47a855912 |
@@ -1,2 +0,0 @@
|
||||
build/*
|
||||
/**/*.d.ts
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 6,
|
||||
"sourceType": "module",
|
||||
"ecmaFeatures": {
|
||||
"modules": true,
|
||||
"experimentalObjectRestSpread": true
|
||||
}
|
||||
},
|
||||
"plugins": ["@typescript-eslint"],
|
||||
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
|
||||
"rules": {
|
||||
"comma-dangle": 0,
|
||||
"no-unused-vars": "warn",
|
||||
"no-unexpected-multiline": "warn",
|
||||
"prefer-const": "warn",
|
||||
"@typescript-eslint/no-empty-function": "off",
|
||||
"@typescript-eslint/explicit-module-boundary-types": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-var-requires": "off"
|
||||
},
|
||||
"settings": {},
|
||||
"env": {
|
||||
"browser": true,
|
||||
"node": true,
|
||||
"jasmine": true,
|
||||
"jest": true,
|
||||
"es6": true
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
custom: https://hge.to/thanks
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help improve simple-keyboard
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: hodgef
|
||||
|
||||
---
|
||||
|
||||
**Simple-keyboard version**
|
||||
As some bugs have been addressed in later versions, please ensure you are running the latest.
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is. Providing a [sandbox example](https://codesandbox.io/s/vanilla) or code depicting the issue is important, as this will help us reproduce the issue.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea you'd like to see in simple-keyboard
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -1,10 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: daily
|
||||
time: "04:00"
|
||||
timezone: America/Montreal
|
||||
open-pull-requests-limit: 10
|
||||
versioning-strategy: increase
|
||||
@@ -1,4 +0,0 @@
|
||||
# About .github
|
||||
|
||||
This directory handles special features to be used on simple-keyboard's Github repository.
|
||||
It is not needed for simple-keyboard to run and can be safely removed.
|
||||
@@ -1,7 +0,0 @@
|
||||
## Description
|
||||
|
||||
A few sentences describing the overall goals of the pull request's commits.
|
||||
|
||||
## Checks
|
||||
|
||||
- [ ] Tests ( `npm run test -- --coverage` ) Coverage at `./coverage/lcov-report/index.html` should be 100%
|
||||
@@ -1,19 +0,0 @@
|
||||
# Number of days of inactivity before an issue becomes stale
|
||||
daysUntilStale: 5
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 2
|
||||
# Issues with these labels will never be considered stale
|
||||
exemptLabels:
|
||||
- pinned
|
||||
- security
|
||||
- "💥 Bug"
|
||||
- "⚡️ Enhancement"
|
||||
# Label to use when marking an issue as stale
|
||||
staleLabel: Stale
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed if no further activity occurs. Thank you
|
||||
for your contributions.
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
closeComment: false
|
||||
@@ -1,48 +0,0 @@
|
||||
name: Build
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
paths-ignore:
|
||||
- README.md
|
||||
- .gitignore
|
||||
- .github/**
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
os: [ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Use Node.js ${{ matrix.node_version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node_version }}
|
||||
- name: npm install, build, and test
|
||||
run: |
|
||||
npm install
|
||||
npm run coverage
|
||||
- uses: codecov/codecov-action@v1.0.2
|
||||
with:
|
||||
token: ${{secrets.CODECOV_TOKEN}}
|
||||
env:
|
||||
CI: true
|
||||
|
||||
- name: Discord notification
|
||||
if: success()
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
|
||||
uses: Ilshidur/action-discord@master
|
||||
with:
|
||||
args: "simple-keyboard - CI Build Passed"
|
||||
|
||||
- name: Discord notification
|
||||
if: failure()
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
|
||||
uses: Ilshidur/action-discord@master
|
||||
with:
|
||||
args: "simple-keyboard - CI Build Failed"
|
||||
@@ -1,15 +0,0 @@
|
||||
name: Mirroring
|
||||
|
||||
on: [push, delete]
|
||||
|
||||
jobs:
|
||||
mirroring:
|
||||
runs-on: ubuntu-18.04
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: pixta-dev/repository-mirroring-action@v1
|
||||
with:
|
||||
target_repo_url:
|
||||
git@gitlab.com:hodgef/simple-keyboard.git
|
||||
ssh_private_key:
|
||||
${{ secrets.GL_KEY }}
|
||||
@@ -1,49 +0,0 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
paths-ignore:
|
||||
- README.md
|
||||
- .gitignore
|
||||
- .github/**
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12
|
||||
- run: npm install
|
||||
- run: npm run test -- --coverage --watchAll=false
|
||||
|
||||
- name: Setup GIT
|
||||
run: |
|
||||
git reset --hard
|
||||
git config --local --list
|
||||
git checkout master
|
||||
git config user.email "$GH_EMAIL"
|
||||
git config user.name "Francisco Hodge"
|
||||
env:
|
||||
GH_EMAIL: ${{secrets.GH_EMAIL}}
|
||||
|
||||
- name: Bump version
|
||||
run: |
|
||||
git reset --hard
|
||||
npm version patch
|
||||
npm run build
|
||||
git add . || true
|
||||
git commit -m "Build update" || true
|
||||
git push "https://$GITHUB_ACTOR:$GITHUB_TOKEN@github.com/$GITHUB_REPOSITORY"
|
||||
env:
|
||||
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||
|
||||
- name: npm publish
|
||||
run: |
|
||||
npm config set //registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN
|
||||
npm run trypublish
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.NODE_AUTH_TOKEN}}
|
||||
@@ -1,23 +0,0 @@
|
||||
name: Build PR (Standard)
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ matrix.os }}
|
||||
if: ${{ github.actor != 'dependabot[bot]' && !contains(github.event.pull_request.labels.*.name, 'dependencies') }}
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
os: [ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Use Node.js ${{ matrix.node_version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node_version }}
|
||||
- name: npm install, build, and test
|
||||
run: |
|
||||
npm install
|
||||
npm run coverage
|
||||
env:
|
||||
CI: true
|
||||
@@ -1,38 +0,0 @@
|
||||
name: Build PR (Dependabot)
|
||||
|
||||
on:
|
||||
pull_request_target
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ matrix.os }}
|
||||
if: contains(github.event.pull_request.labels.*.name, 'dependencies')
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
os: [ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Use Node.js ${{ matrix.node_version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node_version }}
|
||||
- name: npm install, build, and test
|
||||
run: |
|
||||
npm install
|
||||
npm run coverage
|
||||
env:
|
||||
CI: true
|
||||
- name: Merge PR
|
||||
if: success()
|
||||
uses: "pascalgn/automerge-action@v0.14.2"
|
||||
env:
|
||||
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
|
||||
MERGE_LABELS: "dependencies"
|
||||
- name: Reject PR
|
||||
if: failure()
|
||||
uses: peter-evans/close-pull@v1
|
||||
with:
|
||||
pull-request-number: ${{github.event.number}}
|
||||
comment: PR closed due to failing tests
|
||||
delete-branch: true
|
||||
+5
-4
@@ -1,9 +1,11 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
# See https://help.github.com/ignore-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# production
|
||||
/build
|
||||
/demo
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
@@ -14,7 +16,6 @@
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.vscode
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
|
||||
-11
@@ -2,21 +2,14 @@
|
||||
/node_modules
|
||||
|
||||
# testing
|
||||
/tests
|
||||
/coverage
|
||||
|
||||
# docs
|
||||
/docs
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
/.github
|
||||
/demo
|
||||
.esdoc.json
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
@@ -30,7 +23,3 @@ config
|
||||
.travis.yml
|
||||
CHANGELOG.md
|
||||
README.md
|
||||
.eslintignore
|
||||
.eslintrc.json
|
||||
webpack.config.js
|
||||
babel.config.js
|
||||
@@ -0,0 +1,5 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "node"
|
||||
script:
|
||||
- npm run test
|
||||
@@ -1,76 +0,0 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at opensource@hodgef.com. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see
|
||||
https://www.contributor-covenant.org/faq
|
||||
@@ -1,15 +0,0 @@
|
||||
# Contributing
|
||||
|
||||
When contributing to this repository, please first discuss the change you wish to make via issue,
|
||||
email, or any other method with the owners of this repository before working on a change.
|
||||
|
||||
Please note we have a code of conduct, please follow it in all your interactions with the project.
|
||||
|
||||
## Pull Request Guidelines
|
||||
|
||||
1. Please ensure your proposal will not radically change current functionality or bring along breaking changes.
|
||||
2. PRs only consisting of typo fixes (or other automated contributions), will not be accepted.
|
||||
3. Do not add any dependencies to the project.
|
||||
4. Document your changes thoroughly.
|
||||
5. Ensure coverage is complete (`npm run coverage` should show 100% coverage) and that none of the tests fail.
|
||||
6. Be reactive to any comments, reviews or change requests entered in your pull request.
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Francisco Hodge and project contributors.
|
||||
Copyright (c) 2018 Francisco Hodge
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,82 +1,193 @@
|
||||
<p>
|
||||
<a href="https://simple-keyboard.com/demo">
|
||||
<img alt="simple-keyboard: Javascript Virtual Keyboard" src="https://i.imgur.com/PrpbdIu.png">
|
||||
</a>
|
||||
|
||||
<a href="https://www.npmjs.com/package/simple-keyboard">
|
||||
<img src="https://badgen.net/npm/v/simple-keyboard?color=blue" alt="npm version">
|
||||
</a>
|
||||
# simple-keyboard
|
||||
|
||||
<a href="https://github.com/hodgef/simple-keyboard/actions">
|
||||
<img alt="Build Status" src="https://github.com/hodgef/simple-keyboard/workflows/Build/badge.svg?color=green" />
|
||||
</a>
|
||||
|
||||
<a href="https://github.com/hodgef/simple-keyboard/actions">
|
||||
<img alt="Publish Status" src="https://github.com/hodgef/simple-keyboard/workflows/Publish/badge.svg?color=green" />
|
||||
</a>
|
||||
|
||||
<a href="https://david-dm.org/hodgef/simple-keyboard">
|
||||
<img src="https://badgen.net/david/dep/hodgef/simple-keyboard" alt="coverage">
|
||||
</a>
|
||||
</p>
|
||||
[](https://www.npmjs.com/package/simple-keyboard)
|
||||
[](https://www.npmjs.com/package/simple-keyboard)
|
||||
[](https://www.npmjs.com/package/simple-keyboard)
|
||||
[](https://www.npmjs.com/package/simple-keyboard)
|
||||
|
||||
<blockquote>Virtual Keyboard for Javascript. Compatible with your JS, React, Angular or Vue projects.</blockquote>
|
||||
[](https://npmjs.com/package/simple-keyboard)
|
||||
|
||||
## 🚀 Demo
|
||||
> An easily customisable and responsive on-screen virtual keyboard for React.js projects.
|
||||
|
||||
[Demo Showcase (Vanilla, Angular, React, Vue)](https://simple-keyboard.com/demo)
|
||||
<img src="src/demo/images/keyboard.PNG" align="center" width="100%">
|
||||
|
||||
## 📦 Installation & Usage
|
||||
## Installation
|
||||
|
||||
You can use simple-keyboard as a `<script>` tag from a CDN, or install it from npm.
|
||||
`npm install simple-keyboard --save`
|
||||
|
||||
Check out the [Getting Started](https://simple-keyboard.com/getting-started) docs to begin.
|
||||
## Usage
|
||||
|
||||
## 📖 Documentation
|
||||
````js
|
||||
import React, {Component} from 'react';
|
||||
import Keyboard from 'simple-keyboard';
|
||||
import 'simple-keyboard/build/css/index.css';
|
||||
|
||||
Check out the [simple-keyboard documentation](https://simple-keyboard.com/documentation) site.
|
||||
class App extends Component {
|
||||
|
||||
Feel free to browse the [Questions & Answers (FAQ)](https://simple-keyboard.com/qa-use-cases/) page for common use-cases.
|
||||
onChange = (input) => {
|
||||
console.log("Input changed", input);
|
||||
}
|
||||
|
||||
### To run demo on your own computer
|
||||
onKeyPress = (button) => {
|
||||
console.log("Button pressed", button);
|
||||
}
|
||||
|
||||
- Clone this repository
|
||||
- `npm install`
|
||||
- `npm start`
|
||||
- Visit [http://localhost:3000/](http://localhost:3000/)
|
||||
render(){
|
||||
return (
|
||||
<Keyboard
|
||||
onChange={input =>
|
||||
this.onChange(input)}
|
||||
onKeyPress={button =>
|
||||
this.onKeyPress(button)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
### Other versions
|
||||
export default App;
|
||||
````
|
||||
|
||||
- [React.js](https://github.com/hodgef/react-simple-keyboard)
|
||||
- [Angular](https://simple-keyboard.com/demo)
|
||||
- [Vue.js](https://simple-keyboard.com/demo)
|
||||
> Need a more extensive example? [Click here](https://github.com/hodgef/simple-keyboard/blob/master/src/demo/App.js).
|
||||
|
||||
### Questions? Join the chat
|
||||
## Options
|
||||
|
||||
<a href="https://discordapp.com/invite/SJexsCG" title="Join our Discord chat" target="_blank"><img src="https://discordapp.com/api/guilds/498978399801573396/widget.png?style=banner2" align="center"></a>
|
||||
You can customize the Keyboard by passing options (props) to it.
|
||||
Here are the available options (the code examples are the defaults):
|
||||
|
||||
## ✳️ Modules
|
||||
### layout
|
||||
|
||||
You can extend simple-keyboard's functionality with [modules](https://hodgef.com/simple-keyboard/modules/). Such as:
|
||||
> Modify the keyboard layout
|
||||
|
||||
- [Autocorrect](https://hodgef.com/simple-keyboard/modules/autocorrect/)
|
||||
- [Input Mask](https://hodgef.com/simple-keyboard/modules/input-mask/)
|
||||
- [Key Navigation](https://hodgef.com/simple-keyboard/modules/key-navigation/)
|
||||
- [Swipe Keyboard](https://hodgef.com/simple-keyboard/modules/swipe-keyboard/)
|
||||
```js
|
||||
layout={{
|
||||
'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}'
|
||||
]
|
||||
}}
|
||||
```
|
||||
|
||||
Want to create your own module? Check out the [Modules page](https://hodgef.com/simple-keyboard/modules/) for instructions.
|
||||
### layoutName
|
||||
|
||||
## 🎯 Compatibility
|
||||
> Specifies which layout should be used.
|
||||
|
||||
- Internet Explorer 11
|
||||
- Edge (Spartan) 16+
|
||||
- Edge (Anaheim/Edge Chromium) 79+
|
||||
- Chrome 49+
|
||||
- Safari 9+
|
||||
- Firefox 57+
|
||||
- iOS 9+
|
||||
```js
|
||||
layoutName={"default"}
|
||||
```
|
||||
|
||||
## ✅ Contributing
|
||||
### display
|
||||
|
||||
PRs and issues are always welcome. Feel free to submit any issues you have at:
|
||||
> Replaces variable buttons (such as `{bksp}`) with a human-friendly name (e.g.: "delete").
|
||||
|
||||
```js
|
||||
display={{
|
||||
'{bksp}': 'delete',
|
||||
'{enter}': '< enter',
|
||||
'{shift}': 'shift',
|
||||
'{s}': 'shift',
|
||||
'{tab}': 'tab',
|
||||
'{lock}': 'caps',
|
||||
'{accept}': 'Submit',
|
||||
'{space}': ' ',
|
||||
'{//}': ' '
|
||||
}}
|
||||
```
|
||||
|
||||
### theme
|
||||
|
||||
> A prop to add your own css classes. You can add multiple classes separated by a space.
|
||||
|
||||
```js
|
||||
theme={"hg-theme-default"}
|
||||
```
|
||||
|
||||
### debug
|
||||
|
||||
> Runs a console.log every time a key is pressed. Displays the buttons pressed and the current input.
|
||||
|
||||
```js
|
||||
debug={false}
|
||||
```
|
||||
|
||||
### newLineOnEnter
|
||||
|
||||
> Specifies whether clicking the "ENTER" button will input a newline (`\n`) or not.
|
||||
|
||||
```js
|
||||
newLineOnEnter={true}
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
simple-keybord has a few methods you can use to further control it's behavior.
|
||||
To access these functions, you need a `ref` of the simple-keyboard component, like so:
|
||||
|
||||
```js
|
||||
<Keyboard
|
||||
ref={r => this.keyboard = r}
|
||||
[...]
|
||||
/>
|
||||
|
||||
// Then, on componentDidMount ..
|
||||
this.keyboard.methodName(params);
|
||||
```
|
||||
|
||||
### clearInput
|
||||
|
||||
> Clear the keyboard's input.
|
||||
|
||||
```js
|
||||
this.keyboard.clearInput();
|
||||
```
|
||||
|
||||
### getInput
|
||||
|
||||
> Get the keyboard's input (You can also get it from the _onChange_ prop).
|
||||
|
||||
```js
|
||||
let input = this.keyboard.getInput();
|
||||
```
|
||||
|
||||
### setInput
|
||||
|
||||
> Set the keyboard's input. Useful if you want the keybord to initialize with a default value, for example.
|
||||
|
||||
```js
|
||||
this.keyboard.setInput("Hello World!");
|
||||
```
|
||||
|
||||
It returns a promise, so if you want to run something after it's applied, call it as so:
|
||||
|
||||
```js
|
||||
let inputSetPromise = this.keyboard.setInput("Hello World!");
|
||||
|
||||
inputSetPromise.then((result) => {
|
||||
console.log("Input set");
|
||||
});
|
||||
```
|
||||
|
||||
## Demo
|
||||
|
||||
<img src="src/demo/images/demo.gif" align="center" width="600">
|
||||
|
||||
To run demo on your own computer:
|
||||
|
||||
* Clone this repository
|
||||
* `npm install`
|
||||
* `npm start`
|
||||
* Visit [http://localhost:3000/](http://localhost:3000/)
|
||||
|
||||
## Note
|
||||
|
||||
This is a work in progress. Feel free to submit any issues you have at:
|
||||
[https://github.com/hodgef/simple-keyboard/issues](https://github.com/hodgef/simple-keyboard/issues)
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
module.exports = {
|
||||
presets: [
|
||||
["@babel/env", {
|
||||
corejs:"3",
|
||||
useBuiltIns: 'usage',
|
||||
"targets": {
|
||||
"browsers": [
|
||||
"edge >= 16",
|
||||
"safari >= 9",
|
||||
"firefox >= 57",
|
||||
"ie >= 11",
|
||||
"ios >= 9",
|
||||
"chrome >= 49"
|
||||
]
|
||||
},
|
||||
}]
|
||||
],
|
||||
plugins: [
|
||||
["@babel/plugin-proposal-class-properties"],
|
||||
["@babel/plugin-transform-typescript"]
|
||||
]
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
/*!
|
||||
*
|
||||
* simple-keyboard v3.2.32
|
||||
* https://github.com/hodgef/simple-keyboard
|
||||
*
|
||||
* Copyright (c) Francisco Hodge (https://github.com/hodgef) and project contributors.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
*/.hg-theme-default{background-color:#ececec;border-radius:5px;box-sizing:border-box;font-family:HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;overflow:hidden;padding:5px;touch-action:manipulation;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:100%}.hg-theme-default .hg-button span{pointer-events:none}.hg-theme-default button.hg-button{border-width:0;font-size:inherit;outline:0}.hg-theme-default .hg-button{display:inline-block;flex-grow:1}.hg-theme-default .hg-row{display:flex}.hg-theme-default .hg-row:not(:last-child){margin-bottom:5px}.hg-theme-default .hg-row .hg-button:not(:last-child){margin-right:5px}.hg-theme-default .hg-row .hg-button-container{margin-right:5px}.hg-theme-default .hg-row>div:last-child{margin-right:0}.hg-theme-default .hg-row .hg-button-container{display:flex}.hg-theme-default .hg-button{-webkit-tap-highlight-color:rgba(0,0,0,0);align-items:center;background:#fff;border-bottom:1px solid #b5b5b5;border-radius:5px;box-shadow:0 0 3px -1px rgba(0,0,0,.3);box-sizing:border-box;cursor:pointer;display:flex;height:40px;justify-content:center;padding:5px}.hg-theme-default .hg-button.hg-standardBtn{width:20px}.hg-theme-default .hg-button.hg-activeButton{background:#efefef}.hg-theme-default.hg-layout-numeric .hg-button{align-items:center;display:flex;height:60px;justify-content:center;width:33.3%}.hg-theme-default .hg-button.hg-button-numpadadd,.hg-theme-default .hg-button.hg-button-numpadenter{height:85px}.hg-theme-default .hg-button.hg-button-numpad0{width:105px}.hg-theme-default .hg-button.hg-button-com{max-width:85px}.hg-theme-default .hg-button.hg-standardBtn.hg-button-at{max-width:45px}.hg-theme-default .hg-button.hg-selectedButton{background:rgba(5,25,70,.53);color:#fff}.hg-theme-default .hg-button.hg-standardBtn[data-skbtn=".com"]{max-width:82px}.hg-theme-default .hg-button.hg-standardBtn[data-skbtn="@"]{max-width:60px}.hg-candidate-box{background:#ececec;border-bottom:2px solid #b5b5b5;border-radius:5px;display:inline-flex;margin-top:-10px;max-width:272px;position:absolute;transform:translateY(-100%);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}ul.hg-candidate-box-list{display:flex;flex:1;list-style:none;margin:0;padding:0}li.hg-candidate-box-list-item{align-items:center;display:flex;height:40px;justify-content:center;width:40px}li.hg-candidate-box-list-item:hover{background:rgba(0,0,0,.03);cursor:pointer}li.hg-candidate-box-list-item:active{background:rgba(0,0,0,.1)}.hg-candidate-box-prev:before{content:"◄"}.hg-candidate-box-next:before{content:"►"}.hg-candidate-box-next,.hg-candidate-box-prev{align-items:center;background:#d0d0d0;color:#969696;cursor:pointer;display:flex;padding:0 10px}.hg-candidate-box-next{border-bottom-right-radius:5px;border-top-right-radius:5px}.hg-candidate-box-prev{border-bottom-left-radius:5px;border-top-left-radius:5px}.hg-candidate-box-btn-active{color:#444}
|
||||
File diff suppressed because one or more lines are too long
-14
@@ -1,14 +0,0 @@
|
||||
import "./css/CandidateBox.css";
|
||||
import Utilities from "../services/Utilities";
|
||||
import { CandidateBoxParams, CandidateBoxRenderParams, CandidateBoxShowParams } from "./../interfaces";
|
||||
declare class CandidateBox {
|
||||
utilities: Utilities;
|
||||
candidateBoxElement: HTMLDivElement;
|
||||
pageIndex: number;
|
||||
pageSize: number;
|
||||
constructor({ utilities }: CandidateBoxParams);
|
||||
destroy(): void;
|
||||
show({ candidateValue, targetElement, onSelect, }: CandidateBoxShowParams): void;
|
||||
renderPage({ candidateListPages, targetElement, pageIndex, nbPages, onItemSelected, }: CandidateBoxRenderParams): void;
|
||||
}
|
||||
export default CandidateBox;
|
||||
Vendored
-283
@@ -1,283 +0,0 @@
|
||||
import "./css/Keyboard.css";
|
||||
import PhysicalKeyboard from "../services/PhysicalKeyboard";
|
||||
import { KeyboardOptions, KeyboardInput, KeyboardButtonElements, KeyboardHandlerEvent, KeyboardElement, KeyboardParams } from "../interfaces";
|
||||
import CandidateBox from "./CandidateBox";
|
||||
/**
|
||||
* Root class for simple-keyboard.
|
||||
* This class:
|
||||
* - Parses the options
|
||||
* - Renders the rows and buttons
|
||||
* - Handles button functionality
|
||||
*/
|
||||
declare class SimpleKeyboard {
|
||||
input: KeyboardInput;
|
||||
options: KeyboardOptions;
|
||||
utilities: any;
|
||||
caretPosition: number | null;
|
||||
caretPositionEnd: number | null;
|
||||
keyboardDOM: KeyboardElement;
|
||||
keyboardPluginClasses: string;
|
||||
keyboardDOMClass: string;
|
||||
buttonElements: KeyboardButtonElements;
|
||||
currentInstanceName: string;
|
||||
allKeyboardInstances: {
|
||||
[key: string]: SimpleKeyboard;
|
||||
};
|
||||
keyboardInstanceNames: string[];
|
||||
isFirstKeyboardInstance: boolean;
|
||||
physicalKeyboard: PhysicalKeyboard;
|
||||
modules: {
|
||||
[key: string]: any;
|
||||
};
|
||||
activeButtonClass: string;
|
||||
holdInteractionTimeout: number;
|
||||
holdTimeout: number;
|
||||
isMouseHold: boolean;
|
||||
initialized: boolean;
|
||||
candidateBox: CandidateBox | null;
|
||||
keyboardRowsDOM: KeyboardElement;
|
||||
defaultName: string;
|
||||
activeInputElement: HTMLInputElement | HTMLTextAreaElement | null;
|
||||
/**
|
||||
* 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: KeyboardParams);
|
||||
/**
|
||||
* parseParams
|
||||
*/
|
||||
handleParams: (params: KeyboardParams) => {
|
||||
keyboardDOMClass: string;
|
||||
keyboardDOM: KeyboardElement;
|
||||
options: Partial<KeyboardOptions | undefined>;
|
||||
};
|
||||
/**
|
||||
* Getters
|
||||
*/
|
||||
getOptions: () => KeyboardOptions;
|
||||
getCaretPosition: () => number | null;
|
||||
getCaretPositionEnd: () => number | null;
|
||||
/**
|
||||
* Changes the internal caret position
|
||||
* @param {number} position The caret's start position
|
||||
* @param {number} positionEnd The caret's end position
|
||||
*/
|
||||
setCaretPosition(position: number | null, endPosition?: number | null): void;
|
||||
/**
|
||||
* Retrieve the candidates for a given input
|
||||
* @param input The input string to check
|
||||
*/
|
||||
getInputCandidates(input: string): {
|
||||
candidateKey: string;
|
||||
candidateValue: string;
|
||||
} | Record<string, never>;
|
||||
/**
|
||||
* Shows a suggestion box with a list of candidate words
|
||||
* @param candidates The chosen candidates string as defined in the layoutCandidates option
|
||||
* @param targetElement The element next to which the candidates box will be shown
|
||||
*/
|
||||
showCandidatesBox(candidateKey: string, candidateValue: string, targetElement: KeyboardElement): void;
|
||||
/**
|
||||
* Handles clicks made to keyboard buttons
|
||||
* @param {string} button The button's layout name.
|
||||
*/
|
||||
handleButtonClicked(button: string, e?: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Handles button mousedown
|
||||
*/
|
||||
handleButtonMouseDown(button: string, e: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Handles button mouseup
|
||||
*/
|
||||
handleButtonMouseUp(button?: string, e?: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Handles container mousedown
|
||||
*/
|
||||
handleKeyboardContainerMouseDown(e: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Handles button hold
|
||||
*/
|
||||
handleButtonHold(button: string): void;
|
||||
/**
|
||||
* Send a command to all simple-keyboard instances (if you have several instances).
|
||||
*/
|
||||
syncInstanceInputs(): void;
|
||||
/**
|
||||
* Clear the keyboard’s input.
|
||||
* @param {string} [inputName] optional - the internal input to select
|
||||
*/
|
||||
clearInput(inputName?: string): void;
|
||||
/**
|
||||
* Get the keyboard’s input (You can also get it from the onChange prop).
|
||||
* @param {string} [inputName] optional - the internal input to select
|
||||
*/
|
||||
getInput(inputName?: string, skipSync?: boolean): string;
|
||||
/**
|
||||
* Get all simple-keyboard inputs
|
||||
*/
|
||||
getAllInputs(): KeyboardInput;
|
||||
/**
|
||||
* Set the keyboard’s input.
|
||||
* @param {string} input the input value
|
||||
* @param {string} inputName optional - the internal input to select
|
||||
*/
|
||||
setInput(input: string, inputName?: string, skipSync?: boolean): void;
|
||||
/**
|
||||
* Replace the input object (`keyboard.input`)
|
||||
* @param {object} inputObj The input object
|
||||
*/
|
||||
replaceInput(inputObj: KeyboardInput): void;
|
||||
/**
|
||||
* Set new option or modify existing ones after initialization.
|
||||
* @param {object} options The options to set
|
||||
*/
|
||||
setOptions(options?: {}): void;
|
||||
/**
|
||||
* Detecting changes to non-function options
|
||||
* This allows us to ascertain whether a button re-render is needed
|
||||
*/
|
||||
changedOptions(newOptions: Partial<KeyboardOptions>): string[];
|
||||
/**
|
||||
* Executing actions depending on changed options
|
||||
* @param {object} options The options to set
|
||||
*/
|
||||
onSetOptions(changedOptions?: string[]): void;
|
||||
/**
|
||||
* Remove all keyboard rows and reset keyboard values.
|
||||
* Used internally between re-renders.
|
||||
*/
|
||||
resetRows(): void;
|
||||
/**
|
||||
* 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: (instance: SimpleKeyboard, key?: string) => void): void;
|
||||
/**
|
||||
* 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: string, className: string): void;
|
||||
/**
|
||||
* 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: string, className: string): void;
|
||||
/**
|
||||
* 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: string): KeyboardElement | KeyboardElement[] | undefined;
|
||||
/**
|
||||
* This handles the "inputPattern" option
|
||||
* by checking if the provided inputPattern passes
|
||||
*/
|
||||
inputPatternIsValid(inputVal: string): boolean;
|
||||
/**
|
||||
* Handles simple-keyboard event listeners
|
||||
*/
|
||||
setEventListeners(): void;
|
||||
/**
|
||||
* Event Handler: KeyUp
|
||||
*/
|
||||
handleKeyUp(event: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Event Handler: KeyDown
|
||||
*/
|
||||
handleKeyDown(event: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Event Handler: MouseUp
|
||||
*/
|
||||
handleMouseUp(event: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Event Handler: TouchEnd
|
||||
*/
|
||||
handleTouchEnd(event: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Event Handler: Select
|
||||
*/
|
||||
handleSelect(event: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Event Handler: SelectionChange
|
||||
*/
|
||||
handleSelectionChange(event: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Called by {@link setEventListeners} when an event that warrants a cursor position update is triggered
|
||||
*/
|
||||
caretEventHandler(event: KeyboardHandlerEvent): void;
|
||||
/**
|
||||
* Execute an operation on each button
|
||||
*/
|
||||
recurseButtons(fn: any): void;
|
||||
/**
|
||||
* Destroy keyboard listeners and DOM elements
|
||||
*/
|
||||
destroy(): void;
|
||||
/**
|
||||
* Process buttonTheme option
|
||||
*/
|
||||
getButtonThemeClasses(button: string): string[];
|
||||
/**
|
||||
* Process buttonAttributes option
|
||||
*/
|
||||
setDOMButtonAttributes(button: string, callback: any): void;
|
||||
onTouchDeviceDetected(): void;
|
||||
/**
|
||||
* Disabling contextual window for hg-button
|
||||
*/
|
||||
disableContextualWindow(): void;
|
||||
/**
|
||||
* Process autoTouchEvents option
|
||||
*/
|
||||
processAutoTouchEvents(): void;
|
||||
/**
|
||||
* Executes the callback function once simple-keyboard is rendered for the first time (on initialization).
|
||||
*/
|
||||
onInit(): void;
|
||||
/**
|
||||
* Executes the callback function before a simple-keyboard render.
|
||||
*/
|
||||
beforeFirstRender(): void;
|
||||
/**
|
||||
* Executes the callback function before a simple-keyboard render.
|
||||
*/
|
||||
beforeRender(): void;
|
||||
/**
|
||||
* Executes the callback function every time simple-keyboard is rendered (e.g: when you change layouts).
|
||||
*/
|
||||
onRender(): void;
|
||||
/**
|
||||
* Executes the callback function once all modules have been loaded
|
||||
*/
|
||||
onModulesLoaded(): void;
|
||||
/**
|
||||
* Register module
|
||||
*/
|
||||
registerModule: (name: string, initCallback: any) => void;
|
||||
/**
|
||||
* Load modules
|
||||
*/
|
||||
loadModules(): void;
|
||||
/**
|
||||
* Get module prop
|
||||
*/
|
||||
getModuleProp(name: string, prop: string): any;
|
||||
/**
|
||||
* getModulesList
|
||||
*/
|
||||
getModulesList(): string[];
|
||||
/**
|
||||
* Parse Row DOM containers
|
||||
*/
|
||||
parseRowDOMContainers(rowDOM: HTMLDivElement, rowIndex: number, containerStartIndexes: number[], containerEndIndexes: number[]): HTMLDivElement;
|
||||
/**
|
||||
* getKeyboardClassString
|
||||
*/
|
||||
getKeyboardClassString: (...baseDOMClasses: any[]) => string;
|
||||
/**
|
||||
* Renders rows and buttons as per options
|
||||
*/
|
||||
render(): void;
|
||||
}
|
||||
export default SimpleKeyboard;
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
import "./polyfills";
|
||||
import SimpleKeyboard from "./components/Keyboard";
|
||||
export default SimpleKeyboard;
|
||||
Vendored
-216
@@ -1,216 +0,0 @@
|
||||
import SimpleKeyboard from "./components/Keyboard";
|
||||
import Utilities from "./services/Utilities";
|
||||
export interface KeyboardLayoutObject {
|
||||
[key: string]: string[];
|
||||
}
|
||||
export declare type KeyboardButtonTheme = {
|
||||
class: string;
|
||||
buttons: string;
|
||||
} | null;
|
||||
export interface KeyboardButtonAttributes {
|
||||
attribute: string;
|
||||
value: string;
|
||||
buttons: string;
|
||||
}
|
||||
export interface KeyboardInput {
|
||||
[key: string]: string;
|
||||
}
|
||||
export declare type KeyboardParams = [KeyboardOptions] | [string | HTMLDivElement, KeyboardOptions];
|
||||
export declare type CandidateBoxParams = {
|
||||
utilities: Utilities;
|
||||
};
|
||||
export declare type CandidateBoxShowParams = {
|
||||
candidateValue: string;
|
||||
targetElement: KeyboardElement;
|
||||
onSelect: (selectedCandidate: string, e: MouseEvent) => void;
|
||||
};
|
||||
export declare type CandidateBoxRenderParams = {
|
||||
candidateListPages: string[][];
|
||||
targetElement: KeyboardElement;
|
||||
pageIndex: number;
|
||||
nbPages: number;
|
||||
onItemSelected: (selectedCandidate: string, e: MouseEvent) => void;
|
||||
};
|
||||
export declare type KeyboardElement = HTMLDivElement | HTMLButtonElement;
|
||||
export declare type KeyboardHandlerEvent = any;
|
||||
export interface KeyboardButtonElements {
|
||||
[key: string]: KeyboardElement[];
|
||||
}
|
||||
export interface UtilitiesParams {
|
||||
getOptions: () => KeyboardOptions;
|
||||
getCaretPosition: () => number | null;
|
||||
getCaretPositionEnd: () => number | null;
|
||||
dispatch: any;
|
||||
}
|
||||
export interface PhysicalKeyboardParams {
|
||||
getOptions: () => KeyboardOptions;
|
||||
dispatch: any;
|
||||
}
|
||||
export interface KeyboardOptions {
|
||||
/**
|
||||
* Modify the keyboard layout.
|
||||
*/
|
||||
layout?: KeyboardLayoutObject;
|
||||
/**
|
||||
* Specifies which layout should be used.
|
||||
*/
|
||||
layoutName?: string;
|
||||
/**
|
||||
* Replaces variable buttons (such as `{bksp}`) with a human-friendly name (e.g.: `backspace`).
|
||||
*/
|
||||
display?: {
|
||||
[button: string]: string;
|
||||
};
|
||||
/**
|
||||
* By default, when you set the display property, you replace the default one. This setting merges them instead.
|
||||
*/
|
||||
mergeDisplay?: boolean;
|
||||
/**
|
||||
* A prop to add your own css classes to the keyboard wrapper. You can add multiple classes separated by a space.
|
||||
*/
|
||||
theme?: string;
|
||||
/**
|
||||
* A prop to add your own css classes to one or several buttons.
|
||||
*/
|
||||
buttonTheme?: KeyboardButtonTheme[];
|
||||
/**
|
||||
* A prop to add your own attributes to one or several buttons.
|
||||
*/
|
||||
buttonAttributes?: KeyboardButtonAttributes[];
|
||||
/**
|
||||
* Runs a `console.log` every time a key is pressed. Displays the buttons pressed and the current input.
|
||||
*/
|
||||
debug?: boolean;
|
||||
/**
|
||||
* Specifies whether clicking the "ENTER" button will input a newline (`\n`) or not.
|
||||
*/
|
||||
newLineOnEnter?: boolean;
|
||||
/**
|
||||
* Specifies whether clicking the "TAB" button will input a tab character (`\t`) or not.
|
||||
*/
|
||||
tabCharOnTab?: boolean;
|
||||
/**
|
||||
* Allows you to use a single simple-keyboard instance for several inputs.
|
||||
*/
|
||||
inputName?: string;
|
||||
/**
|
||||
* `number`: Restrains all of simple-keyboard inputs to a certain length. This should be used in addition to the input element’s maxlengthattribute.
|
||||
*
|
||||
* `{ [inputName: string]: number }`: Restrains simple-keyboard’s individual inputs to a certain length. This should be used in addition to the input element’s maxlengthattribute.
|
||||
*/
|
||||
maxLength?: any;
|
||||
/**
|
||||
* When set to true, this option synchronizes the internal input of every simple-keyboard instance.
|
||||
*/
|
||||
syncInstanceInputs?: boolean;
|
||||
/**
|
||||
* Enable highlighting of keys pressed on physical keyboard.
|
||||
*/
|
||||
physicalKeyboardHighlight?: boolean;
|
||||
/**
|
||||
* Calls handler for a button highlighted by physicalKeyboardHighlight
|
||||
* In other words, this calls keyboard.handleButtonClicked(buttonName) on the highlighted button
|
||||
*/
|
||||
physicalKeyboardHighlightPress?: boolean;
|
||||
/**
|
||||
* Trigger click on a button's element when using physicalKeyboardHighlightPress
|
||||
* In other words, this calls button.click() on the highlighted button
|
||||
*/
|
||||
physicalKeyboardHighlightPressUseClick?: boolean;
|
||||
/**
|
||||
* Define the text color that the physical keyboard highlighted key should have.
|
||||
*/
|
||||
physicalKeyboardHighlightTextColor?: string;
|
||||
/**
|
||||
* Define the background color that the physical keyboard highlighted key should have.
|
||||
*/
|
||||
physicalKeyboardHighlightBgColor?: string;
|
||||
/**
|
||||
* Calling preventDefault for the mousedown events keeps the focus on the input.
|
||||
*/
|
||||
preventMouseDownDefault?: boolean;
|
||||
/**
|
||||
* Calling preventDefault for the mouseup events.
|
||||
*/
|
||||
preventMouseUpDefault?: boolean;
|
||||
/**
|
||||
* Stops pointer down events on simple-keyboard buttons from bubbling to parent elements.
|
||||
*/
|
||||
stopMouseDownPropagation?: boolean;
|
||||
/**
|
||||
* Stops pointer up events on simple-keyboard buttons from bubbling to parent elements.
|
||||
*/
|
||||
stopMouseUpPropagation?: boolean;
|
||||
/**
|
||||
* Render buttons as a button element instead of a div element.
|
||||
*/
|
||||
useButtonTag?: boolean;
|
||||
/**
|
||||
* A prop to ensure characters are always be added/removed at the end of the string.
|
||||
*/
|
||||
disableCaretPositioning?: boolean;
|
||||
/**
|
||||
* Restrains input(s) change to the defined regular expression pattern.
|
||||
*/
|
||||
inputPattern?: any;
|
||||
/**
|
||||
* Instructs simple-keyboard to use touch events instead of click events.
|
||||
*/
|
||||
useTouchEvents?: boolean;
|
||||
/**
|
||||
* Enable useTouchEvents automatically when touch device is detected.
|
||||
*/
|
||||
autoUseTouchEvents?: boolean;
|
||||
/**
|
||||
* Opt out of PointerEvents handling, falling back to the prior mouse event logic.
|
||||
*/
|
||||
useMouseEvents?: boolean;
|
||||
/**
|
||||
* Disable button hold action.
|
||||
*/
|
||||
disableButtonHold?: boolean;
|
||||
/**
|
||||
* Adds unicode right-to-left control characters to input return values.
|
||||
*/
|
||||
rtl?: boolean;
|
||||
/**
|
||||
* Enable input method editor candidate list support.
|
||||
*/
|
||||
enableLayoutCandidates?: boolean;
|
||||
/**
|
||||
* Character suggestions to be shown on certain key presses
|
||||
*/
|
||||
layoutCandidates?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/**
|
||||
* Exclude buttons from layout
|
||||
*/
|
||||
excludeFromLayout?: {
|
||||
[key: string]: string[];
|
||||
};
|
||||
/**
|
||||
* Determine size of layout candidate list
|
||||
*/
|
||||
layoutCandidatesPageSize?: number;
|
||||
/**
|
||||
* Executes the callback function every time simple-keyboard is rendered (e.g: when you change layouts).
|
||||
*/
|
||||
onRender?: (instance?: SimpleKeyboard) => void;
|
||||
/**
|
||||
* Executes the callback function once simple-keyboard is rendered for the first time (on initialization).
|
||||
*/
|
||||
onInit?: (instance?: SimpleKeyboard) => void;
|
||||
/**
|
||||
* Retrieves the current input
|
||||
*/
|
||||
onChange?: (input: string, e?: MouseEvent) => any;
|
||||
/**
|
||||
* Retrieves all inputs
|
||||
*/
|
||||
onChangeAll?: (inputObj: KeyboardInput, e?: MouseEvent) => any;
|
||||
/**
|
||||
* Module options can have any format
|
||||
*/
|
||||
[name: string]: any;
|
||||
}
|
||||
Vendored
-4
@@ -1,4 +0,0 @@
|
||||
export declare const getDefaultLayout: () => {
|
||||
default: string[];
|
||||
shift: string[];
|
||||
};
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
import { KeyboardOptions, PhysicalKeyboardParams } from "../interfaces";
|
||||
/**
|
||||
* Physical Keyboard Service
|
||||
*/
|
||||
declare class PhysicalKeyboard {
|
||||
getOptions: () => KeyboardOptions;
|
||||
dispatch: any;
|
||||
/**
|
||||
* Creates an instance of the PhysicalKeyboard service
|
||||
*/
|
||||
constructor({ dispatch, getOptions }: PhysicalKeyboardParams);
|
||||
handleHighlightKeyDown(event: KeyboardEvent): void;
|
||||
handleHighlightKeyUp(event: KeyboardEvent): void;
|
||||
/**
|
||||
* Transforms a KeyboardEvent's "key.code" string into a simple-keyboard layout format
|
||||
* @param {object} event The KeyboardEvent
|
||||
*/
|
||||
getSimpleKeyboardLayoutKey(event: KeyboardEvent): string;
|
||||
/**
|
||||
* Retrieve key from keyCode
|
||||
*/
|
||||
keyCodeToKey(keyCode: number): string | undefined;
|
||||
}
|
||||
export default PhysicalKeyboard;
|
||||
Vendored
-193
@@ -1,193 +0,0 @@
|
||||
import { KeyboardInput } from "./../interfaces";
|
||||
import { KeyboardOptions, UtilitiesParams } from "../interfaces";
|
||||
/**
|
||||
* Utility Service
|
||||
*/
|
||||
declare class Utilities {
|
||||
getOptions: () => KeyboardOptions;
|
||||
getCaretPosition: () => number | null;
|
||||
getCaretPositionEnd: () => number | null;
|
||||
dispatch: any;
|
||||
maxLengthReached: boolean;
|
||||
/**
|
||||
* Creates an instance of the Utility service
|
||||
*/
|
||||
constructor({ getOptions, getCaretPosition, getCaretPositionEnd, dispatch, }: UtilitiesParams);
|
||||
/**
|
||||
* Retrieve button type
|
||||
*
|
||||
* @param {string} button The button's layout name
|
||||
* @return {string} The button type
|
||||
*/
|
||||
getButtonType(button: string): string;
|
||||
/**
|
||||
* Adds default classes to a given button
|
||||
*
|
||||
* @param {string} button The button's layout name
|
||||
* @return {string} The classes to be added to the button
|
||||
*/
|
||||
getButtonClass(button: string): string;
|
||||
/**
|
||||
* Default button display labels
|
||||
*/
|
||||
getDefaultDiplay(): {
|
||||
"{bksp}": string;
|
||||
"{backspace}": string;
|
||||
"{enter}": string;
|
||||
"{shift}": string;
|
||||
"{shiftleft}": string;
|
||||
"{shiftright}": string;
|
||||
"{alt}": string;
|
||||
"{s}": string;
|
||||
"{tab}": string;
|
||||
"{lock}": string;
|
||||
"{capslock}": string;
|
||||
"{accept}": string;
|
||||
"{space}": string;
|
||||
"{//}": string;
|
||||
"{esc}": string;
|
||||
"{escape}": string;
|
||||
"{f1}": string;
|
||||
"{f2}": string;
|
||||
"{f3}": string;
|
||||
"{f4}": string;
|
||||
"{f5}": string;
|
||||
"{f6}": string;
|
||||
"{f7}": string;
|
||||
"{f8}": string;
|
||||
"{f9}": string;
|
||||
"{f10}": string;
|
||||
"{f11}": string;
|
||||
"{f12}": string;
|
||||
"{numpaddivide}": string;
|
||||
"{numlock}": string;
|
||||
"{arrowup}": string;
|
||||
"{arrowleft}": string;
|
||||
"{arrowdown}": string;
|
||||
"{arrowright}": string;
|
||||
"{prtscr}": string;
|
||||
"{scrolllock}": string;
|
||||
"{pause}": string;
|
||||
"{insert}": string;
|
||||
"{home}": string;
|
||||
"{pageup}": string;
|
||||
"{delete}": string;
|
||||
"{forwarddelete}": string;
|
||||
"{end}": string;
|
||||
"{pagedown}": string;
|
||||
"{numpadmultiply}": string;
|
||||
"{numpadsubtract}": string;
|
||||
"{numpadadd}": string;
|
||||
"{numpadenter}": string;
|
||||
"{period}": string;
|
||||
"{numpaddecimal}": string;
|
||||
"{numpad0}": string;
|
||||
"{numpad1}": string;
|
||||
"{numpad2}": string;
|
||||
"{numpad3}": string;
|
||||
"{numpad4}": string;
|
||||
"{numpad5}": string;
|
||||
"{numpad6}": string;
|
||||
"{numpad7}": string;
|
||||
"{numpad8}": string;
|
||||
"{numpad9}": string;
|
||||
};
|
||||
/**
|
||||
* Returns the display (label) name for a given button
|
||||
*
|
||||
* @param {string} button The button's layout name
|
||||
* @param {object} display The provided display option
|
||||
* @param {boolean} mergeDisplay Whether the provided param value should be merged with the default one.
|
||||
*/
|
||||
getButtonDisplayName(button: string, display: KeyboardOptions["display"], mergeDisplay: boolean): string;
|
||||
/**
|
||||
* Returns the updated input resulting from clicking a given button
|
||||
*
|
||||
* @param {string} button The button's layout name
|
||||
* @param {string} input The input string
|
||||
* @param {number} caretPos The cursor's current position
|
||||
* @param {number} caretPosEnd The cursor's current end position
|
||||
* @param {boolean} moveCaret Whether to update simple-keyboard's cursor
|
||||
*/
|
||||
getUpdatedInput(button: string, input: string, caretPos: number, caretPosEnd?: number, moveCaret?: boolean): string;
|
||||
/**
|
||||
* Moves the cursor position by a given amount
|
||||
*
|
||||
* @param {number} length Represents by how many characters the input should be moved
|
||||
* @param {boolean} minus Whether the cursor should be moved to the left or not.
|
||||
*/
|
||||
updateCaretPos(length: number, minus?: boolean): void;
|
||||
/**
|
||||
* Action method of updateCaretPos
|
||||
*
|
||||
* @param {number} length Represents by how many characters the input should be moved
|
||||
* @param {boolean} minus Whether the cursor should be moved to the left or not.
|
||||
*/
|
||||
updateCaretPosAction(length: number, minus?: boolean): number | null;
|
||||
/**
|
||||
* Adds a string to the input at a given position
|
||||
*
|
||||
* @param {string} source The source input
|
||||
* @param {string} str The string to add
|
||||
* @param {number} position The (cursor) position where the string should be added
|
||||
* @param {boolean} moveCaret Whether to update simple-keyboard's cursor
|
||||
*/
|
||||
addStringAt(source: string, str: string, position?: number, positionEnd?: number, moveCaret?: boolean): string;
|
||||
/**
|
||||
* Check whether the button is a standard button
|
||||
*/
|
||||
isStandardButton: (button: string) => boolean | "";
|
||||
/**
|
||||
* Removes an amount of characters before a given position
|
||||
*
|
||||
* @param {string} source The source input
|
||||
* @param {number} position The (cursor) position from where the characters should be removed
|
||||
* @param {boolean} moveCaret Whether to update simple-keyboard's cursor
|
||||
*/
|
||||
removeAt(source: string, position?: number, positionEnd?: number, moveCaret?: boolean): string;
|
||||
/**
|
||||
* Removes an amount of characters after a given position
|
||||
*
|
||||
* @param {string} source The source input
|
||||
* @param {number} position The (cursor) position from where the characters should be removed
|
||||
*/
|
||||
removeForwardsAt(source: string, position?: number, positionEnd?: number, moveCaret?: boolean): string;
|
||||
/**
|
||||
* Determines whether the maxLength has been reached. This function is called when the maxLength option it set.
|
||||
*
|
||||
* @param {object} inputObj
|
||||
* @param {string} updatedInput
|
||||
*/
|
||||
handleMaxLength(inputObj: KeyboardInput, updatedInput: string): boolean | undefined;
|
||||
/**
|
||||
* Gets the current value of maxLengthReached
|
||||
*/
|
||||
isMaxLengthReached(): boolean;
|
||||
/**
|
||||
* Determines whether a touch device is being used
|
||||
*/
|
||||
isTouchDevice(): number | true;
|
||||
/**
|
||||
* Determines whether pointer events are supported
|
||||
*/
|
||||
pointerEventsSupported(): boolean;
|
||||
/**
|
||||
* Bind all methods in a given class
|
||||
*/
|
||||
static bindMethods(myClass: any, instance: any): void;
|
||||
/**
|
||||
* Transforms an arbitrary string to camelCase
|
||||
*
|
||||
* @param {string} str The string to transform.
|
||||
*/
|
||||
camelCase(str: string): string;
|
||||
/**
|
||||
* Split array into chunks
|
||||
*/
|
||||
chunkArray<T>(arr: T[], size: number): T[][];
|
||||
/**
|
||||
* Reusable empty function
|
||||
*/
|
||||
static noop: () => void;
|
||||
}
|
||||
export default Utilities;
|
||||
@@ -0,0 +1,90 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const paths = require('./paths');
|
||||
|
||||
// Make sure that including paths.js after env.js will read .env variables.
|
||||
delete require.cache[require.resolve('./paths')];
|
||||
|
||||
const NODE_ENV = process.env.NODE_ENV;
|
||||
if (!NODE_ENV) {
|
||||
throw new Error(
|
||||
'The NODE_ENV environment variable is required but was not specified.'
|
||||
);
|
||||
}
|
||||
|
||||
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
|
||||
var dotenvFiles = [
|
||||
`${paths.dotenv}.${NODE_ENV}.local`,
|
||||
`${paths.dotenv}.${NODE_ENV}`,
|
||||
// Don't include `.env.local` for `test` environment
|
||||
// since normally you expect tests to produce the same
|
||||
// results for everyone
|
||||
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
|
||||
paths.dotenv,
|
||||
].filter(Boolean);
|
||||
|
||||
// Load environment variables from .env* files. Suppress warnings using silent
|
||||
// if this file is missing. dotenv will never modify any environment variables
|
||||
// that have already been set.
|
||||
// https://github.com/motdotla/dotenv
|
||||
dotenvFiles.forEach(dotenvFile => {
|
||||
if (fs.existsSync(dotenvFile)) {
|
||||
require('dotenv').config({
|
||||
path: dotenvFile,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// We support resolving modules according to `NODE_PATH`.
|
||||
// This lets you use absolute paths in imports inside large monorepos:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/253.
|
||||
// It works similar to `NODE_PATH` in Node itself:
|
||||
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
|
||||
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
|
||||
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
|
||||
// We also resolve them to make sure all tools using them work consistently.
|
||||
const appDirectory = fs.realpathSync(process.cwd());
|
||||
process.env.NODE_PATH = (process.env.NODE_PATH || '')
|
||||
.split(path.delimiter)
|
||||
.filter(folder => folder && !path.isAbsolute(folder))
|
||||
.map(folder => path.resolve(appDirectory, folder))
|
||||
.join(path.delimiter);
|
||||
|
||||
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
|
||||
// injected into the application via DefinePlugin in Webpack configuration.
|
||||
const REACT_APP = /^REACT_APP_/i;
|
||||
|
||||
function getClientEnvironment(publicUrl) {
|
||||
const raw = Object.keys(process.env)
|
||||
.filter(key => REACT_APP.test(key))
|
||||
.reduce(
|
||||
(env, key) => {
|
||||
env[key] = process.env[key];
|
||||
return env;
|
||||
},
|
||||
{
|
||||
// Useful for determining whether we’re running in production mode.
|
||||
// Most importantly, it switches React into the correct mode.
|
||||
NODE_ENV: process.env.NODE_ENV || 'development',
|
||||
// Useful for resolving the correct path to static assets in `public`.
|
||||
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
|
||||
// This should only be used as an escape hatch. Normally you would put
|
||||
// images into the `src` and `import` them in code to get their paths.
|
||||
PUBLIC_URL: publicUrl,
|
||||
}
|
||||
);
|
||||
// Stringify all values so we can feed into Webpack DefinePlugin
|
||||
const stringified = {
|
||||
'process.env': Object.keys(raw).reduce((env, key) => {
|
||||
env[key] = JSON.stringify(raw[key]);
|
||||
return env;
|
||||
}, {}),
|
||||
};
|
||||
|
||||
return { raw, stringified };
|
||||
}
|
||||
|
||||
module.exports = getClientEnvironment;
|
||||
@@ -0,0 +1,14 @@
|
||||
'use strict';
|
||||
|
||||
// This is a custom Jest transformer turning style imports into empty objects.
|
||||
// http://facebook.github.io/jest/docs/tutorial-webpack.html
|
||||
|
||||
module.exports = {
|
||||
process() {
|
||||
return 'module.exports = {};';
|
||||
},
|
||||
getCacheKey() {
|
||||
// The output is always the same.
|
||||
return 'cssTransform';
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
|
||||
// This is a custom Jest transformer turning file imports into filenames.
|
||||
// http://facebook.github.io/jest/docs/tutorial-webpack.html
|
||||
|
||||
module.exports = {
|
||||
process(src, filename) {
|
||||
return `module.exports = ${JSON.stringify(path.basename(filename))};`;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const url = require('url');
|
||||
|
||||
// Make sure any symlinks in the project folder are resolved:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/637
|
||||
const appDirectory = fs.realpathSync(process.cwd());
|
||||
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
|
||||
|
||||
const envPublicUrl = process.env.PUBLIC_URL;
|
||||
|
||||
function ensureSlash(path, needsSlash) {
|
||||
const hasSlash = path.endsWith('/');
|
||||
if (hasSlash && !needsSlash) {
|
||||
return path.substr(path, path.length - 1);
|
||||
} else if (!hasSlash && needsSlash) {
|
||||
return `${path}/`;
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
const getPublicUrl = appPackageJson =>
|
||||
envPublicUrl || require(appPackageJson).homepage;
|
||||
|
||||
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
|
||||
// "public path" at which the app is served.
|
||||
// Webpack needs to know it to put the right <script> hrefs into HTML even in
|
||||
// single-page apps that may serve index.html for nested URLs like /todos/42.
|
||||
// We can't use a relative path in HTML because we don't want to load something
|
||||
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
|
||||
function getServedPath(appPackageJson) {
|
||||
const publicUrl = getPublicUrl(appPackageJson);
|
||||
const servedUrl =
|
||||
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
|
||||
return ensureSlash(servedUrl, true);
|
||||
}
|
||||
|
||||
// config after eject: we're in ./config/
|
||||
module.exports = {
|
||||
dotenv: resolveApp('.env'),
|
||||
appBuild: resolveApp('build'),
|
||||
appDemoBuild: resolveApp('demo'),
|
||||
appPublic: resolveApp('public'),
|
||||
appHtml: resolveApp('public/index.html'),
|
||||
appIndexJs: resolveApp('src/demo/index.js'), // CRL: Updated for demo purposes
|
||||
appPackageJson: resolveApp('package.json'),
|
||||
appSrc: resolveApp('src'),
|
||||
yarnLockFile: resolveApp('yarn.lock'),
|
||||
testsSetup: resolveApp('src/setupTests.js'),
|
||||
appNodeModules: resolveApp('node_modules'),
|
||||
publicUrl: getPublicUrl(resolveApp('package.json')),
|
||||
servedPath: getServedPath(resolveApp('package.json')),
|
||||
|
||||
// CRL: New paths for demo build
|
||||
appDemoIndexJs: resolveApp('src/demo/index.js'),
|
||||
appDemoSrc: resolveApp('src/demo'),
|
||||
|
||||
// CRL: New paths for library
|
||||
appLibIndexJs: resolveApp('src/lib/index.js'),
|
||||
appLibSrc: resolveApp('src/lib'),
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
if (typeof Promise === 'undefined') {
|
||||
// Rejection tracking prevents a common issue where React gets into an
|
||||
// inconsistent state due to an error, but it gets swallowed by a Promise,
|
||||
// and the user has no idea what causes React's erratic future behavior.
|
||||
require('promise/lib/rejection-tracking').enable();
|
||||
window.Promise = require('promise/lib/es6-extensions.js');
|
||||
}
|
||||
|
||||
// fetch() polyfill for making API calls.
|
||||
require('whatwg-fetch');
|
||||
|
||||
// Object.assign() is commonly used with React.
|
||||
// It will use the native implementation if it's present and isn't buggy.
|
||||
Object.assign = require('object-assign');
|
||||
|
||||
// In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet.
|
||||
// We don't polyfill it in the browser--this is user's responsibility.
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
require('raf').polyfill(global);
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
|
||||
|
||||
const autoprefixer = require('autoprefixer');
|
||||
const path = require('path');
|
||||
const webpack = require('webpack');
|
||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
const CopyWebpackPlugin = require('copy-webpack-plugin');
|
||||
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
|
||||
const ExtractTextPlugin = require('extract-text-webpack-plugin');
|
||||
const eslintFormatter = require('react-dev-utils/eslintFormatter');
|
||||
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
|
||||
const paths = require('./paths');
|
||||
const getClientEnvironment = require('./env');
|
||||
|
||||
// Webpack uses `publicPath` to determine where the app is being served from.
|
||||
// It requires a trailing slash, or the file assets will get an incorrect path.
|
||||
const publicPath = paths.servedPath;
|
||||
// Some apps do not use client-side routing with pushState.
|
||||
// For these, "homepage" can be set to "." to enable relative asset paths.
|
||||
const shouldUseRelativeAssetPaths = publicPath === './';
|
||||
// Source maps are resource heavy and can cause out of memory issue for large source files.
|
||||
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
|
||||
// `publicUrl` is just like `publicPath`, but we will provide it to our app
|
||||
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
|
||||
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
|
||||
const publicUrl = '.';
|
||||
// Get environment variables to inject into our app.
|
||||
const env = getClientEnvironment(publicUrl);
|
||||
|
||||
// Assert this just to be safe.
|
||||
// Development builds of React are slow and not intended for production.
|
||||
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
|
||||
throw new Error('Production builds must have NODE_ENV=production.');
|
||||
}
|
||||
|
||||
// Note: defined here because it will be used more than once.
|
||||
const cssFilename = 'css/index.css';
|
||||
|
||||
// ExtractTextPlugin expects the build output to be flat.
|
||||
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
|
||||
// However, our output is structured with css, js and media folders.
|
||||
// To have this structure working with relative paths, we have to use custom options.
|
||||
const extractTextPluginOptions = shouldUseRelativeAssetPaths
|
||||
? // Making sure that the publicPath goes back to to build folder.
|
||||
{ publicPath: Array(cssFilename.split('/').length).join('../') }
|
||||
: {};
|
||||
|
||||
// This is the production configuration.
|
||||
// It compiles slowly and is focused on producing a fast and minimal bundle.
|
||||
// The development configuration is different and lives in a separate file.
|
||||
module.exports = {
|
||||
// Don't attempt to continue if there are any errors.
|
||||
bail: true,
|
||||
// We generate sourcemaps in production. This is slow but gives good results.
|
||||
// You can exclude the *.map files from the build during deployment.
|
||||
devtool: shouldUseSourceMap ? 'source-map' : false,
|
||||
// In production, we only want to load the app code.
|
||||
entry: [paths.appDemoIndexJs], // CRL: library index file instead of app index
|
||||
output: {
|
||||
// CRL: Updated whole block with library specific info
|
||||
path: paths.appDemoBuild,
|
||||
filename: 'index.js',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
resolve: {
|
||||
// This allows you to set a fallback for where Webpack should look for modules.
|
||||
// We placed these paths second because we want `node_modules` to "win"
|
||||
// if there are any conflicts. This matches Node resolution mechanism.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/253
|
||||
modules: ['node_modules', paths.appNodeModules].concat(
|
||||
// It is guaranteed to exist because we tweak it in `env.js`
|
||||
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
|
||||
),
|
||||
// These are the reasonable defaults supported by the Node ecosystem.
|
||||
// We also include JSX as a common component filename extension to support
|
||||
// some tools, although we do not recommend using it, see:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/290
|
||||
// `web` extension prefixes have been added for better support
|
||||
// for React Native Web.
|
||||
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
|
||||
alias: {
|
||||
// Support React Native Web
|
||||
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
|
||||
'react-native': 'react-native-web'
|
||||
},
|
||||
plugins: [
|
||||
// Prevents users from importing files from outside of src/ (or node_modules/).
|
||||
// This often causes confusion because we only process files within src/ with babel.
|
||||
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
|
||||
// please link the files into your node_modules/ and let module-resolution kick in.
|
||||
// Make sure your source files are compiled, as they will not be processed in any way.
|
||||
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])
|
||||
]
|
||||
},
|
||||
module: {
|
||||
strictExportPresence: true,
|
||||
rules: [
|
||||
// TODO: Disable require.ensure as it's not a standard language feature.
|
||||
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
|
||||
// { parser: { requireEnsure: false } },
|
||||
|
||||
// First, run the linter.
|
||||
// It's important to do this before Babel processes the JS.
|
||||
{
|
||||
test: /\.(js|jsx|mjs)$/,
|
||||
enforce: 'pre',
|
||||
use: [
|
||||
{
|
||||
options: {
|
||||
formatter: eslintFormatter,
|
||||
eslintPath: require.resolve('eslint')
|
||||
},
|
||||
loader: require.resolve('eslint-loader')
|
||||
}
|
||||
],
|
||||
include: paths.appDemoSrc // CRL: updated with library src folder
|
||||
},
|
||||
{
|
||||
// "oneOf" will traverse all following loaders until one will
|
||||
// match the requirements. When no loader matches it will fall
|
||||
// back to the "file" loader at the end of the loader list.
|
||||
oneOf: [
|
||||
// "url" loader works just like "file" loader but it also embeds
|
||||
// assets smaller than specified size as data URLs to avoid requests.
|
||||
{
|
||||
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
|
||||
loader: require.resolve('url-loader'),
|
||||
options: {
|
||||
limit: 10000,
|
||||
name: 'media/[name].[ext]'
|
||||
}
|
||||
},
|
||||
// Process JS with Babel.
|
||||
{
|
||||
test: /\.(js|jsx|mjs)$/,
|
||||
include: [paths.appLibSrc, paths.appDemoSrc], // CRL: updated with library src folder
|
||||
loader: require.resolve('babel-loader'),
|
||||
options: {
|
||||
compact: true
|
||||
}
|
||||
},
|
||||
// The notation here is somewhat confusing.
|
||||
// "postcss" loader applies autoprefixer to our CSS.
|
||||
// "css" loader resolves paths in CSS and adds assets as dependencies.
|
||||
// "style" loader normally turns CSS into JS modules injecting <style>,
|
||||
// but unlike in development configuration, we do something different.
|
||||
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
|
||||
// (second argument), then grabs the result CSS and puts it into a
|
||||
// separate file in our build process. This way we actually ship
|
||||
// a single CSS file in production instead of JS code injecting <style>
|
||||
// tags. If you use code splitting, however, any async bundles will still
|
||||
// use the "style" loader inside the async code so CSS from them won't be
|
||||
// in the main CSS file.
|
||||
{
|
||||
test: /\.css$/,
|
||||
loader: ExtractTextPlugin.extract(
|
||||
Object.assign(
|
||||
{
|
||||
fallback: {
|
||||
loader: require.resolve('style-loader'),
|
||||
options: {
|
||||
hmr: false
|
||||
}
|
||||
},
|
||||
use: [
|
||||
{
|
||||
loader: require.resolve('css-loader'),
|
||||
options: {
|
||||
importLoaders: 1,
|
||||
minimize: true,
|
||||
sourceMap: shouldUseSourceMap
|
||||
}
|
||||
},
|
||||
{
|
||||
loader: require.resolve('postcss-loader'),
|
||||
options: {
|
||||
// Necessary for external CSS imports to work
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2677
|
||||
ident: 'postcss',
|
||||
plugins: () => [
|
||||
require('postcss-flexbugs-fixes'),
|
||||
autoprefixer({
|
||||
browsers: [
|
||||
'>1%',
|
||||
'last 4 versions',
|
||||
'Firefox ESR',
|
||||
'not ie < 9' // React doesn't support IE8 anyway
|
||||
],
|
||||
flexbox: 'no-2009'
|
||||
})
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
extractTextPluginOptions
|
||||
)
|
||||
)
|
||||
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
|
||||
},
|
||||
// "file" loader makes sure assets end up in the `build` folder.
|
||||
// When you `import` an asset, you get its filename.
|
||||
// This loader doesn't use a "test" so it will catch all modules
|
||||
// that fall through the other loaders.
|
||||
{
|
||||
loader: require.resolve('file-loader'),
|
||||
// Exclude `js` files to keep "css" loader working as it injects
|
||||
// it's runtime that would otherwise processed through "file" loader.
|
||||
// Also exclude `html` and `json` extensions so they get processed
|
||||
// by webpacks internal loaders.
|
||||
exclude: [/\.js$/, /\.html$/, /\.json$/],
|
||||
options: {
|
||||
name: 'media/[name].[ext]'
|
||||
}
|
||||
}
|
||||
// ** STOP ** Are you adding a new loader?
|
||||
// Make sure to add the new loader(s) before the "file" loader.
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
plugins: [
|
||||
// Makes some environment variables available to the JS code, for example:
|
||||
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
|
||||
// It is absolutely essential that NODE_ENV was set to production here.
|
||||
// Otherwise React will be compiled in the very slow development mode.
|
||||
new InterpolateHtmlPlugin(env.raw),
|
||||
// Generates an `index.html` file with the <script> injected.
|
||||
new HtmlWebpackPlugin({
|
||||
inject: true,
|
||||
template: paths.appHtml
|
||||
}),
|
||||
// Add module names to factory functions so they appear in browser profiler.
|
||||
new webpack.NamedModulesPlugin(),
|
||||
new webpack.DefinePlugin(env.stringified),
|
||||
// Minify the code.
|
||||
new webpack.optimize.UglifyJsPlugin({
|
||||
compress: false,
|
||||
mangle: {
|
||||
safari10: true
|
||||
},
|
||||
output: {
|
||||
comments: false,
|
||||
// Turned on because emoji and regex is not minified properly using default
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2488
|
||||
ascii_only: true
|
||||
},
|
||||
sourceMap: shouldUseSourceMap
|
||||
}),
|
||||
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
|
||||
new ExtractTextPlugin({
|
||||
filename: cssFilename
|
||||
}),
|
||||
// Moment.js is an extremely popular library that bundles large locale files
|
||||
// by default due to how Webpack interprets its code. This is a practical
|
||||
// solution that requires the user to opt into importing specific locales.
|
||||
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
|
||||
// You can remove this if you don't use Moment.js:
|
||||
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
|
||||
new CopyWebpackPlugin([
|
||||
{ from: `${paths.appPublic}/favicon.ico`, to: paths.appDemoBuild },
|
||||
{ from: `${paths.appPublic}/manifest.json`, to: paths.appDemoBuild }
|
||||
])
|
||||
],
|
||||
// CRL: added externals block for library
|
||||
// externals: {
|
||||
// 'react': 'react',
|
||||
// 'react-dom': 'react-dom'
|
||||
// },
|
||||
// Some libraries import Node modules but don't use them in the browser.
|
||||
// Tell Webpack to provide empty mocks for them so importing them works.
|
||||
node: {
|
||||
dgram: 'empty',
|
||||
fs: 'empty',
|
||||
net: 'empty',
|
||||
tls: 'empty',
|
||||
child_process: 'empty'
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,259 @@
|
||||
'use strict';
|
||||
|
||||
const autoprefixer = require('autoprefixer');
|
||||
const path = require('path');
|
||||
const webpack = require('webpack');
|
||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
|
||||
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
|
||||
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
|
||||
const eslintFormatter = require('react-dev-utils/eslintFormatter');
|
||||
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
|
||||
const getClientEnvironment = require('./env');
|
||||
const paths = require('./paths');
|
||||
|
||||
// Webpack uses `publicPath` to determine where the app is being served from.
|
||||
// In development, we always serve from the root. This makes config easier.
|
||||
const publicPath = '/';
|
||||
// `publicUrl` is just like `publicPath`, but we will provide it to our app
|
||||
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
|
||||
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
|
||||
const publicUrl = '';
|
||||
// Get environment variables to inject into our app.
|
||||
const env = getClientEnvironment(publicUrl);
|
||||
|
||||
// This is the development configuration.
|
||||
// It is focused on developer experience and fast rebuilds.
|
||||
// The production configuration is different and lives in a separate file.
|
||||
module.exports = {
|
||||
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
|
||||
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
|
||||
devtool: 'cheap-module-source-map',
|
||||
// These are the "entry points" to our application.
|
||||
// This means they will be the "root" imports that are included in JS bundle.
|
||||
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
|
||||
entry: [
|
||||
// Include an alternative client for WebpackDevServer. A client's job is to
|
||||
// connect to WebpackDevServer by a socket and get notified about changes.
|
||||
// When you save a file, the client will either apply hot updates (in case
|
||||
// of CSS changes), or refresh the page (in case of JS changes). When you
|
||||
// make a syntax error, this client will display a syntax error overlay.
|
||||
// Note: instead of the default WebpackDevServer client, we use a custom one
|
||||
// to bring better experience for Create React App users. You can replace
|
||||
// the line below with these two lines if you prefer the stock client:
|
||||
// require.resolve('webpack-dev-server/client') + '?/',
|
||||
// require.resolve('webpack/hot/dev-server'),
|
||||
require.resolve('react-dev-utils/webpackHotDevClient'),
|
||||
// Finally, this is your app's code:
|
||||
paths.appIndexJs,
|
||||
// We include the app code last so that if there is a runtime error during
|
||||
// initialization, it doesn't blow up the WebpackDevServer client, and
|
||||
// changing JS code would still trigger a refresh.
|
||||
],
|
||||
output: {
|
||||
// Add /* filename */ comments to generated require()s in the output.
|
||||
pathinfo: true,
|
||||
// This does not produce a real file. It's just the virtual path that is
|
||||
// served by WebpackDevServer in development. This is the JS bundle
|
||||
// containing code from all our entry points, and the Webpack runtime.
|
||||
filename: 'static/js/bundle.js',
|
||||
// There are also additional JS chunk files if you use code splitting.
|
||||
chunkFilename: 'static/js/[name].chunk.js',
|
||||
// This is the URL that app is served from. We use "/" in development.
|
||||
publicPath: publicPath,
|
||||
// Point sourcemap entries to original disk location (format as URL on Windows)
|
||||
devtoolModuleFilenameTemplate: info =>
|
||||
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
|
||||
},
|
||||
resolve: {
|
||||
// This allows you to set a fallback for where Webpack should look for modules.
|
||||
// We placed these paths second because we want `node_modules` to "win"
|
||||
// if there are any conflicts. This matches Node resolution mechanism.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/253
|
||||
modules: ['node_modules', paths.appNodeModules].concat(
|
||||
// It is guaranteed to exist because we tweak it in `env.js`
|
||||
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
|
||||
),
|
||||
// These are the reasonable defaults supported by the Node ecosystem.
|
||||
// We also include JSX as a common component filename extension to support
|
||||
// some tools, although we do not recommend using it, see:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/290
|
||||
// `web` extension prefixes have been added for better support
|
||||
// for React Native Web.
|
||||
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
|
||||
alias: {
|
||||
|
||||
// Support React Native Web
|
||||
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
|
||||
'react-native': 'react-native-web',
|
||||
},
|
||||
plugins: [
|
||||
// Prevents users from importing files from outside of src/ (or node_modules/).
|
||||
// This often causes confusion because we only process files within src/ with babel.
|
||||
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
|
||||
// please link the files into your node_modules/ and let module-resolution kick in.
|
||||
// Make sure your source files are compiled, as they will not be processed in any way.
|
||||
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
|
||||
],
|
||||
},
|
||||
module: {
|
||||
strictExportPresence: true,
|
||||
rules: [
|
||||
// TODO: Disable require.ensure as it's not a standard language feature.
|
||||
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
|
||||
// { parser: { requireEnsure: false } },
|
||||
|
||||
// First, run the linter.
|
||||
// It's important to do this before Babel processes the JS.
|
||||
{
|
||||
test: /\.(js|jsx|mjs)$/,
|
||||
enforce: 'pre',
|
||||
use: [
|
||||
{
|
||||
options: {
|
||||
formatter: eslintFormatter,
|
||||
eslintPath: require.resolve('eslint'),
|
||||
|
||||
},
|
||||
loader: require.resolve('eslint-loader'),
|
||||
},
|
||||
],
|
||||
include: paths.appSrc,
|
||||
},
|
||||
{
|
||||
// "oneOf" will traverse all following loaders until one will
|
||||
// match the requirements. When no loader matches it will fall
|
||||
// back to the "file" loader at the end of the loader list.
|
||||
oneOf: [
|
||||
// "url" loader works like "file" loader except that it embeds assets
|
||||
// smaller than specified limit in bytes as data URLs to avoid requests.
|
||||
// A missing `test` is equivalent to a match.
|
||||
{
|
||||
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
|
||||
loader: require.resolve('url-loader'),
|
||||
options: {
|
||||
limit: 10000,
|
||||
name: 'static/media/[name].[hash:8].[ext]',
|
||||
},
|
||||
},
|
||||
// Process JS with Babel.
|
||||
{
|
||||
test: /\.(js|jsx|mjs)$/,
|
||||
include: paths.appSrc,
|
||||
loader: require.resolve('babel-loader'),
|
||||
options: {
|
||||
// This is a feature of `babel-loader` for webpack (not Babel itself).
|
||||
// It enables caching results in ./node_modules/.cache/babel-loader/
|
||||
// directory for faster rebuilds.
|
||||
cacheDirectory: true,
|
||||
},
|
||||
},
|
||||
// "postcss" loader applies autoprefixer to our CSS.
|
||||
// "css" loader resolves paths in CSS and adds assets as dependencies.
|
||||
// "style" loader turns CSS into JS modules that inject <style> tags.
|
||||
// In production, we use a plugin to extract that CSS to a file, but
|
||||
// in development "style" loader enables hot editing of CSS.
|
||||
{
|
||||
test: /\.css$/,
|
||||
use: [
|
||||
require.resolve('style-loader'),
|
||||
{
|
||||
loader: require.resolve('css-loader'),
|
||||
options: {
|
||||
importLoaders: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
loader: require.resolve('postcss-loader'),
|
||||
options: {
|
||||
// Necessary for external CSS imports to work
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2677
|
||||
ident: 'postcss',
|
||||
plugins: () => [
|
||||
require('postcss-flexbugs-fixes'),
|
||||
autoprefixer({
|
||||
browsers: [
|
||||
'>1%',
|
||||
'last 4 versions',
|
||||
'Firefox ESR',
|
||||
'not ie < 9', // React doesn't support IE8 anyway
|
||||
],
|
||||
flexbox: 'no-2009',
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
// "file" loader makes sure those assets get served by WebpackDevServer.
|
||||
// When you `import` an asset, you get its (virtual) filename.
|
||||
// In production, they would get copied to the `build` folder.
|
||||
// This loader doesn't use a "test" so it will catch all modules
|
||||
// that fall through the other loaders.
|
||||
{
|
||||
// Exclude `js` files to keep "css" loader working as it injects
|
||||
// it's runtime that would otherwise processed through "file" loader.
|
||||
// Also exclude `html` and `json` extensions so they get processed
|
||||
// by webpacks internal loaders.
|
||||
exclude: [/\.js$/, /\.html$/, /\.json$/],
|
||||
loader: require.resolve('file-loader'),
|
||||
options: {
|
||||
name: 'static/media/[name].[hash:8].[ext]',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
// ** STOP ** Are you adding a new loader?
|
||||
// Make sure to add the new loader(s) before the "file" loader.
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
// Makes some environment variables available in index.html.
|
||||
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
|
||||
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
// In development, this will be an empty string.
|
||||
new InterpolateHtmlPlugin(env.raw),
|
||||
// Generates an `index.html` file with the <script> injected.
|
||||
new HtmlWebpackPlugin({
|
||||
inject: true,
|
||||
template: paths.appHtml,
|
||||
}),
|
||||
// Add module names to factory functions so they appear in browser profiler.
|
||||
new webpack.NamedModulesPlugin(),
|
||||
// Makes some environment variables available to the JS code, for example:
|
||||
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
|
||||
new webpack.DefinePlugin(env.stringified),
|
||||
// This is necessary to emit hot updates (currently CSS only):
|
||||
new webpack.HotModuleReplacementPlugin(),
|
||||
// Watcher doesn't work well if you mistype casing in a path so we use
|
||||
// a plugin that prints an error when you attempt to do this.
|
||||
// See https://github.com/facebookincubator/create-react-app/issues/240
|
||||
new CaseSensitivePathsPlugin(),
|
||||
// If you require a missing module and then `npm install` it, you still have
|
||||
// to restart the development server for Webpack to discover it. This plugin
|
||||
// makes the discovery automatic so you don't have to restart.
|
||||
// See https://github.com/facebookincubator/create-react-app/issues/186
|
||||
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
|
||||
// Moment.js is an extremely popular library that bundles large locale files
|
||||
// by default due to how Webpack interprets its code. This is a practical
|
||||
// solution that requires the user to opt into importing specific locales.
|
||||
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
|
||||
// You can remove this if you don't use Moment.js:
|
||||
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
|
||||
],
|
||||
// Some libraries import Node modules but don't use them in the browser.
|
||||
// Tell Webpack to provide empty mocks for them so importing them works.
|
||||
node: {
|
||||
dgram: 'empty',
|
||||
fs: 'empty',
|
||||
net: 'empty',
|
||||
tls: 'empty',
|
||||
child_process: 'empty',
|
||||
},
|
||||
// Turn off performance hints during development because we don't do any
|
||||
// splitting or minification in interest of speed. These warnings become
|
||||
// cumbersome.
|
||||
performance: {
|
||||
hints: false,
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
'use strict';
|
||||
|
||||
const autoprefixer = require('autoprefixer');
|
||||
const path = require('path');
|
||||
const webpack = require('webpack');
|
||||
const ExtractTextPlugin = require('extract-text-webpack-plugin');
|
||||
const eslintFormatter = require('react-dev-utils/eslintFormatter');
|
||||
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
|
||||
const paths = require('./paths');
|
||||
const getClientEnvironment = require('./env');
|
||||
|
||||
// Webpack uses `publicPath` to determine where the app is being served from.
|
||||
// It requires a trailing slash, or the file assets will get an incorrect path.
|
||||
const publicPath = paths.servedPath;
|
||||
// Some apps do not use client-side routing with pushState.
|
||||
// For these, "homepage" can be set to "." to enable relative asset paths.
|
||||
const shouldUseRelativeAssetPaths = publicPath === './';
|
||||
// Source maps are resource heavy and can cause out of memory issue for large source files.
|
||||
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
|
||||
// `publicUrl` is just like `publicPath`, but we will provide it to our app
|
||||
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
|
||||
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
|
||||
const publicUrl = publicPath.slice(0, -1);
|
||||
// Get environment variables to inject into our app.
|
||||
const env = getClientEnvironment(publicUrl);
|
||||
|
||||
// Assert this just to be safe.
|
||||
// Development builds of React are slow and not intended for production.
|
||||
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
|
||||
throw new Error('Production builds must have NODE_ENV=production.');
|
||||
}
|
||||
|
||||
// Note: defined here because it will be used more than once.
|
||||
const cssFilename = 'css/index.css';
|
||||
|
||||
// ExtractTextPlugin expects the build output to be flat.
|
||||
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
|
||||
// However, our output is structured with css, js and media folders.
|
||||
// To have this structure working with relative paths, we have to use custom options.
|
||||
const extractTextPluginOptions = shouldUseRelativeAssetPaths
|
||||
? // Making sure that the publicPath goes back to to build folder.
|
||||
{ publicPath: Array(cssFilename.split('/').length).join('../') }
|
||||
: {};
|
||||
|
||||
// This is the production configuration.
|
||||
// It compiles slowly and is focused on producing a fast and minimal bundle.
|
||||
// The development configuration is different and lives in a separate file.
|
||||
module.exports = {
|
||||
// Don't attempt to continue if there are any errors.
|
||||
bail: true,
|
||||
// We generate sourcemaps in production. This is slow but gives good results.
|
||||
// You can exclude the *.map files from the build during deployment.
|
||||
devtool: shouldUseSourceMap ? 'source-map' : false,
|
||||
// In production, we only want to load the app code.
|
||||
entry: [paths.appLibIndexJs], // CRL: library index file instead of app index
|
||||
output: {
|
||||
// CRL: Updated whole block with library specific info
|
||||
path: paths.appBuild,
|
||||
filename: 'index.js',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
resolve: {
|
||||
// This allows you to set a fallback for where Webpack should look for modules.
|
||||
// We placed these paths second because we want `node_modules` to "win"
|
||||
// if there are any conflicts. This matches Node resolution mechanism.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/253
|
||||
modules: ['node_modules', paths.appNodeModules].concat(
|
||||
// It is guaranteed to exist because we tweak it in `env.js`
|
||||
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
|
||||
),
|
||||
// These are the reasonable defaults supported by the Node ecosystem.
|
||||
// We also include JSX as a common component filename extension to support
|
||||
// some tools, although we do not recommend using it, see:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/290
|
||||
// `web` extension prefixes have been added for better support
|
||||
// for React Native Web.
|
||||
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
|
||||
alias: {
|
||||
|
||||
// Support React Native Web
|
||||
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
|
||||
'react-native': 'react-native-web',
|
||||
},
|
||||
plugins: [
|
||||
// Prevents users from importing files from outside of src/ (or node_modules/).
|
||||
// This often causes confusion because we only process files within src/ with babel.
|
||||
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
|
||||
// please link the files into your node_modules/ and let module-resolution kick in.
|
||||
// Make sure your source files are compiled, as they will not be processed in any way.
|
||||
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
|
||||
],
|
||||
},
|
||||
module: {
|
||||
strictExportPresence: true,
|
||||
rules: [
|
||||
// TODO: Disable require.ensure as it's not a standard language feature.
|
||||
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
|
||||
// { parser: { requireEnsure: false } },
|
||||
|
||||
// First, run the linter.
|
||||
// It's important to do this before Babel processes the JS.
|
||||
{
|
||||
test: /\.(js|jsx|mjs)$/,
|
||||
enforce: 'pre',
|
||||
use: [
|
||||
{
|
||||
options: {
|
||||
formatter: eslintFormatter,
|
||||
eslintPath: require.resolve('eslint'),
|
||||
|
||||
},
|
||||
loader: require.resolve('eslint-loader'),
|
||||
},
|
||||
],
|
||||
include: paths.appLibSrc, // CRL: updated with library src folder
|
||||
},
|
||||
{
|
||||
// "oneOf" will traverse all following loaders until one will
|
||||
// match the requirements. When no loader matches it will fall
|
||||
// back to the "file" loader at the end of the loader list.
|
||||
oneOf: [
|
||||
// "url" loader works just like "file" loader but it also embeds
|
||||
// assets smaller than specified size as data URLs to avoid requests.
|
||||
{
|
||||
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
|
||||
loader: require.resolve('url-loader'),
|
||||
options: {
|
||||
limit: 10000,
|
||||
name: 'media/[name].[ext]',
|
||||
},
|
||||
},
|
||||
// Process JS with Babel.
|
||||
{
|
||||
test: /\.(js|jsx|mjs)$/,
|
||||
include: paths.appLibSrc, // CRL: updated with library src folder
|
||||
loader: require.resolve('babel-loader'),
|
||||
options: {
|
||||
|
||||
compact: true,
|
||||
},
|
||||
},
|
||||
// The notation here is somewhat confusing.
|
||||
// "postcss" loader applies autoprefixer to our CSS.
|
||||
// "css" loader resolves paths in CSS and adds assets as dependencies.
|
||||
// "style" loader normally turns CSS into JS modules injecting <style>,
|
||||
// but unlike in development configuration, we do something different.
|
||||
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
|
||||
// (second argument), then grabs the result CSS and puts it into a
|
||||
// separate file in our build process. This way we actually ship
|
||||
// a single CSS file in production instead of JS code injecting <style>
|
||||
// tags. If you use code splitting, however, any async bundles will still
|
||||
// use the "style" loader inside the async code so CSS from them won't be
|
||||
// in the main CSS file.
|
||||
{
|
||||
test: /\.css$/,
|
||||
loader: ExtractTextPlugin.extract(
|
||||
Object.assign(
|
||||
{
|
||||
fallback: {
|
||||
loader: require.resolve('style-loader'),
|
||||
options: {
|
||||
hmr: false,
|
||||
},
|
||||
},
|
||||
use: [
|
||||
{
|
||||
loader: require.resolve('css-loader'),
|
||||
options: {
|
||||
importLoaders: 1,
|
||||
minimize: true,
|
||||
sourceMap: shouldUseSourceMap,
|
||||
},
|
||||
},
|
||||
{
|
||||
loader: require.resolve('postcss-loader'),
|
||||
options: {
|
||||
// Necessary for external CSS imports to work
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2677
|
||||
ident: 'postcss',
|
||||
plugins: () => [
|
||||
require('postcss-flexbugs-fixes'),
|
||||
autoprefixer({
|
||||
browsers: [
|
||||
'>1%',
|
||||
'last 4 versions',
|
||||
'Firefox ESR',
|
||||
'not ie < 9', // React doesn't support IE8 anyway
|
||||
],
|
||||
flexbox: 'no-2009',
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
extractTextPluginOptions
|
||||
)
|
||||
),
|
||||
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
|
||||
},
|
||||
// "file" loader makes sure assets end up in the `build` folder.
|
||||
// When you `import` an asset, you get its filename.
|
||||
// This loader doesn't use a "test" so it will catch all modules
|
||||
// that fall through the other loaders.
|
||||
{
|
||||
loader: require.resolve('file-loader'),
|
||||
// Exclude `js` files to keep "css" loader working as it injects
|
||||
// it's runtime that would otherwise processed through "file" loader.
|
||||
// Also exclude `html` and `json` extensions so they get processed
|
||||
// by webpacks internal loaders.
|
||||
exclude: [/\.js$/, /\.html$/, /\.json$/],
|
||||
options: {
|
||||
name: 'media/[name].[ext]',
|
||||
},
|
||||
},
|
||||
// ** STOP ** Are you adding a new loader?
|
||||
// Make sure to add the new loader(s) before the "file" loader.
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
// Makes some environment variables available to the JS code, for example:
|
||||
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
|
||||
// It is absolutely essential that NODE_ENV was set to production here.
|
||||
// Otherwise React will be compiled in the very slow development mode.
|
||||
new webpack.DefinePlugin(env.stringified),
|
||||
// Minify the code.
|
||||
new webpack.optimize.UglifyJsPlugin({
|
||||
compress: {
|
||||
warnings: false,
|
||||
// Disabled because of an issue with Uglify breaking seemingly valid code:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2376
|
||||
// Pending further investigation:
|
||||
// https://github.com/mishoo/UglifyJS2/issues/2011
|
||||
comparisons: false,
|
||||
},
|
||||
mangle: {
|
||||
safari10: true,
|
||||
},
|
||||
output: {
|
||||
comments: false,
|
||||
// Turned on because emoji and regex is not minified properly using default
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2488
|
||||
ascii_only: true,
|
||||
},
|
||||
sourceMap: shouldUseSourceMap,
|
||||
}),
|
||||
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
|
||||
new ExtractTextPlugin({
|
||||
filename: cssFilename,
|
||||
}),
|
||||
// Moment.js is an extremely popular library that bundles large locale files
|
||||
// by default due to how Webpack interprets its code. This is a practical
|
||||
// solution that requires the user to opt into importing specific locales.
|
||||
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
|
||||
// You can remove this if you don't use Moment.js:
|
||||
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
|
||||
],
|
||||
// CRL: added externals block for library
|
||||
externals: {
|
||||
'react': 'react',
|
||||
'react-dom': 'react-dom'
|
||||
},
|
||||
// Some libraries import Node modules but don't use them in the browser.
|
||||
// Tell Webpack to provide empty mocks for them so importing them works.
|
||||
node: {
|
||||
dgram: 'empty',
|
||||
fs: 'empty',
|
||||
net: 'empty',
|
||||
tls: 'empty',
|
||||
child_process: 'empty',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
|
||||
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
|
||||
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
|
||||
const path = require('path');
|
||||
const config = require('./webpack.config.dev');
|
||||
const paths = require('./paths');
|
||||
|
||||
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
|
||||
const host = process.env.HOST || '0.0.0.0';
|
||||
|
||||
module.exports = function(proxy, allowedHost) {
|
||||
return {
|
||||
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
|
||||
// websites from potentially accessing local content through DNS rebinding:
|
||||
// https://github.com/webpack/webpack-dev-server/issues/887
|
||||
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
|
||||
// However, it made several existing use cases such as development in cloud
|
||||
// environment or subdomains in development significantly more complicated:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2271
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2233
|
||||
// While we're investigating better solutions, for now we will take a
|
||||
// compromise. Since our WDS configuration only serves files in the `public`
|
||||
// folder we won't consider accessing them a vulnerability. However, if you
|
||||
// use the `proxy` feature, it gets more dangerous because it can expose
|
||||
// remote code execution vulnerabilities in backends like Django and Rails.
|
||||
// So we will disable the host check normally, but enable it if you have
|
||||
// specified the `proxy` setting. Finally, we let you override it if you
|
||||
// really know what you're doing with a special environment variable.
|
||||
disableHostCheck:
|
||||
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
|
||||
// Enable gzip compression of generated files.
|
||||
compress: true,
|
||||
// Silence WebpackDevServer's own logs since they're generally not useful.
|
||||
// It will still show compile warnings and errors with this setting.
|
||||
clientLogLevel: 'none',
|
||||
// By default WebpackDevServer serves physical files from current directory
|
||||
// in addition to all the virtual build products that it serves from memory.
|
||||
// This is confusing because those files won’t automatically be available in
|
||||
// production build folder unless we copy them. However, copying the whole
|
||||
// project directory is dangerous because we may expose sensitive files.
|
||||
// Instead, we establish a convention that only files in `public` directory
|
||||
// get served. Our build script will copy `public` into the `build` folder.
|
||||
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
|
||||
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
|
||||
// Note that we only recommend to use `public` folder as an escape hatch
|
||||
// for files like `favicon.ico`, `manifest.json`, and libraries that are
|
||||
// for some reason broken when imported through Webpack. If you just want to
|
||||
// use an image, put it in `src` and `import` it from JavaScript instead.
|
||||
contentBase: paths.appPublic,
|
||||
// By default files from `contentBase` will not trigger a page reload.
|
||||
watchContentBase: true,
|
||||
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
|
||||
// for the WebpackDevServer client so it can learn when the files were
|
||||
// updated. The WebpackDevServer client is included as an entry point
|
||||
// in the Webpack development configuration. Note that only changes
|
||||
// to CSS are currently hot reloaded. JS changes will refresh the browser.
|
||||
hot: true,
|
||||
// It is important to tell WebpackDevServer to use the same "root" path
|
||||
// as we specified in the config. In development, we always serve from /.
|
||||
publicPath: config.output.publicPath,
|
||||
// WebpackDevServer is noisy by default so we emit custom message instead
|
||||
// by listening to the compiler events with `compiler.plugin` calls above.
|
||||
quiet: true,
|
||||
// Reportedly, this avoids CPU overload on some systems.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/293
|
||||
// src/node_modules is not ignored to support absolute imports
|
||||
// https://github.com/facebookincubator/create-react-app/issues/1065
|
||||
watchOptions: {
|
||||
ignored: new RegExp(
|
||||
`^(?!${path
|
||||
.normalize(paths.appSrc + '/')
|
||||
.replace(/[\\]+/g, '\\\\')}).+[\\\\/]node_modules[\\\\/]`,
|
||||
'g'
|
||||
),
|
||||
},
|
||||
// Enable HTTPS if the HTTPS environment variable is set to 'true'
|
||||
https: protocol === 'https',
|
||||
host: host,
|
||||
overlay: false,
|
||||
historyApiFallback: {
|
||||
// Paths with dots should still use the history fallback.
|
||||
// See https://github.com/facebookincubator/create-react-app/issues/387.
|
||||
disableDotRule: true,
|
||||
},
|
||||
public: allowedHost,
|
||||
proxy,
|
||||
before(app) {
|
||||
// This lets us open files from the runtime error overlay.
|
||||
app.use(errorOverlayMiddleware());
|
||||
// This service worker file is effectively a 'no-op' that will reset any
|
||||
// previous service worker registered for the same host:port combination.
|
||||
// We do this in development to avoid hitting the production cache if
|
||||
// it used the same host and port.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432
|
||||
app.use(noopServiceWorkerMiddleware());
|
||||
},
|
||||
};
|
||||
};
|
||||
Generated
+9231
-12755
File diff suppressed because it is too large
Load Diff
+81
-73
@@ -1,16 +1,14 @@
|
||||
{
|
||||
"name": "simple-keyboard",
|
||||
"version": "3.2.32",
|
||||
"description": "On-screen Javascript Virtual Keyboard",
|
||||
"version": "1.1.2",
|
||||
"description": "React.js Virtual Keyboard",
|
||||
"main": "build/index.js",
|
||||
"types": "build/types/index.d.ts",
|
||||
"scripts": {
|
||||
"start": "webpack serve --config webpack.config.demo.js",
|
||||
"build": "webpack && tsc",
|
||||
"test": "jest --silent",
|
||||
"coverage": "npm run test -- --coverage",
|
||||
"prepare": "npm run build",
|
||||
"trypublish": "npm publish || true"
|
||||
"start": "node scripts/start.js",
|
||||
"build": "node scripts/build.js",
|
||||
"demo": "node scripts/demo.js",
|
||||
"test": "node scripts/test.js --env=jsdom",
|
||||
"prepublish": "npm run build"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -20,96 +18,106 @@
|
||||
"bugs": {
|
||||
"url": "https://github.com/hodgef/simple-keyboard/issues"
|
||||
},
|
||||
"homepage": "https://virtual-keyboard.js.org/",
|
||||
"homepage": "https://github.com/hodgef/simple-keyboard",
|
||||
"keywords": [
|
||||
"javascript",
|
||||
"es6",
|
||||
"react",
|
||||
"reactjs",
|
||||
"digital",
|
||||
"keyboard",
|
||||
"onscreen",
|
||||
"virtual",
|
||||
"screen-keyboard",
|
||||
"component",
|
||||
"virtual-keyboard",
|
||||
"touchscreen",
|
||||
"touch-screen",
|
||||
"kiosk",
|
||||
"osk",
|
||||
"js"
|
||||
"simple",
|
||||
"easy"
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@babel/cli": "^7.14.8",
|
||||
"@babel/core": "^7.14.8",
|
||||
"@babel/plugin-proposal-class-properties": "^7.14.5",
|
||||
"@babel/plugin-transform-typescript": "^7.14.6",
|
||||
"@babel/polyfill": "^7.12.1",
|
||||
"@babel/preset-env": "^7.14.8",
|
||||
"@types/jest": "^26.0.24",
|
||||
"@typescript-eslint/eslint-plugin": "^4.28.5",
|
||||
"@typescript-eslint/parser": "^4.28.5",
|
||||
"autoprefixer": "^10.3.1",
|
||||
"babel-eslint": "^10.1.0",
|
||||
"babel-loader": "^8.2.2",
|
||||
"babel-preset-minify": "^0.5.0",
|
||||
"core-js": "^3.16.0",
|
||||
"css-loader": "^6.2.0",
|
||||
"eslint": "^7.31.0",
|
||||
"file-loader": "^6.2.0",
|
||||
"html-webpack-plugin": "^5.3.2",
|
||||
"jest": "^27.0.6",
|
||||
"mini-css-extract-plugin": "^2.1.0",
|
||||
"optimize-css-assets-webpack-plugin": "^6.0.1",
|
||||
"postcss": "^8.3.6",
|
||||
"postcss-loader": "^6.1.1",
|
||||
"prettier": "^2.3.2",
|
||||
"prettier-webpack-plugin": "^1.2.0",
|
||||
"style-loader": "^3.2.1",
|
||||
"terser-webpack-plugin": "^5.1.4",
|
||||
"typescript": "^4.3.5",
|
||||
"url-loader": "^4.1.1",
|
||||
"webpack": "^5.40.0",
|
||||
"webpack-cli": "^4.7.2",
|
||||
"webpack-dev-server": "4.0.0-rc.0"
|
||||
"autoprefixer": "7.1.6",
|
||||
"babel-core": "6.26.0",
|
||||
"babel-eslint": "7.2.3",
|
||||
"babel-jest": "20.0.3",
|
||||
"babel-loader": "7.1.2",
|
||||
"babel-preset-react-app": "^3.1.0",
|
||||
"babel-runtime": "6.26.0",
|
||||
"case-sensitive-paths-webpack-plugin": "2.1.1",
|
||||
"chalk": "1.1.3",
|
||||
"copy-webpack-plugin": "^4.3.1",
|
||||
"css-loader": "0.28.7",
|
||||
"dotenv": "4.0.0",
|
||||
"eslint": "4.10.0",
|
||||
"eslint-config-react-app": "^2.0.1",
|
||||
"eslint-loader": "1.9.0",
|
||||
"eslint-plugin-flowtype": "2.39.1",
|
||||
"eslint-plugin-import": "2.8.0",
|
||||
"eslint-plugin-jsx-a11y": "5.1.1",
|
||||
"eslint-plugin-react": "7.4.0",
|
||||
"extract-text-webpack-plugin": "3.0.2",
|
||||
"file-loader": "1.1.5",
|
||||
"fs-extra": "3.0.1",
|
||||
"html-webpack-plugin": "2.29.0",
|
||||
"jest": "20.0.4",
|
||||
"object-assign": "4.1.1",
|
||||
"postcss-flexbugs-fixes": "3.2.0",
|
||||
"postcss-loader": "2.0.8",
|
||||
"promise": "8.0.1",
|
||||
"raf": "3.4.0",
|
||||
"react": "^16.2.0",
|
||||
"react-dev-utils": "^4.2.1",
|
||||
"react-dom": "^16.2.0",
|
||||
"style-loader": "0.19.0",
|
||||
"sw-precache-webpack-plugin": "0.11.4",
|
||||
"url-loader": "0.6.2",
|
||||
"webpack": "3.8.1",
|
||||
"webpack-dev-server": "2.9.4",
|
||||
"webpack-manifest-plugin": "1.3.2",
|
||||
"whatwg-fetch": "2.0.3",
|
||||
"prop-types": "^15.6.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=0.14",
|
||||
"react-dom": ">=0.14"
|
||||
},
|
||||
"jest": {
|
||||
"roots": [
|
||||
"<rootDir>/src"
|
||||
],
|
||||
"collectCoverageFrom": [
|
||||
"src/**/*.{js,jsx,ts,tsx}",
|
||||
"!src/**/*.d.ts",
|
||||
"!src/lib/index.js",
|
||||
"!src/lib/polyfills.js",
|
||||
"!src/demo/**",
|
||||
"!src/utils/**",
|
||||
"!src/**/*.d.ts",
|
||||
"!**/tests/**"
|
||||
"src/**/*.{js,jsx,mjs}"
|
||||
],
|
||||
"setupFiles": [
|
||||
"<rootDir>/config/polyfills.js"
|
||||
],
|
||||
"testMatch": [
|
||||
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
|
||||
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
|
||||
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
|
||||
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
|
||||
],
|
||||
"testEnvironment": "node",
|
||||
"testURL": "http://localhost",
|
||||
"transform": {
|
||||
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
|
||||
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
|
||||
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
|
||||
},
|
||||
"transformIgnorePatterns": [
|
||||
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
|
||||
"^.+\\.module\\.(css|sass|scss)$"
|
||||
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
|
||||
],
|
||||
"modulePaths": [],
|
||||
"moduleNameMapper": {
|
||||
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/scripts/testMock.js",
|
||||
"\\.(css|less)$": "<rootDir>/scripts/testMock.js"
|
||||
"^react-native$": "react-native-web"
|
||||
},
|
||||
"moduleFileExtensions": [
|
||||
"web.js",
|
||||
"mjs",
|
||||
"js",
|
||||
"web.ts",
|
||||
"ts",
|
||||
"web.tsx",
|
||||
"tsx",
|
||||
"json",
|
||||
"web.jsx",
|
||||
"jsx",
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"babel": {
|
||||
"presets": [
|
||||
"react-app"
|
||||
]
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": "react-app"
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.5 KiB |
@@ -0,0 +1,40 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="theme-color" content="#000000">
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is added to the
|
||||
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
|
||||
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
You need to enable JavaScript to run this app.
|
||||
</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": "./index.html",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'production';
|
||||
process.env.NODE_ENV = 'production';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const chalk = require('chalk');
|
||||
const fs = require('fs-extra');
|
||||
const webpack = require('webpack');
|
||||
const config = require('../config/webpack.config.prod');
|
||||
const paths = require('../config/paths');
|
||||
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
|
||||
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
|
||||
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
|
||||
const printBuildError = require('react-dev-utils/printBuildError');
|
||||
|
||||
const measureFileSizesBeforeBuild =
|
||||
FileSizeReporter.measureFileSizesBeforeBuild;
|
||||
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
|
||||
|
||||
// These sizes are pretty large. We'll warn for bundles exceeding them.
|
||||
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
|
||||
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
|
||||
|
||||
// Warn and crash if required files are missing
|
||||
if (!checkRequiredFiles([paths.appLibIndexJs])) { // CRL: Updated with library index file
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// First, read the current file sizes in build directory.
|
||||
// This lets us display how much they changed later.
|
||||
measureFileSizesBeforeBuild(paths.appBuild)
|
||||
.then(previousFileSizes => {
|
||||
// Remove all content but keep the directory so that
|
||||
// if you're in it, you don't end up in Trash
|
||||
fs.emptyDirSync(paths.appBuild);
|
||||
|
||||
// Start the webpack build
|
||||
return build(previousFileSizes);
|
||||
})
|
||||
.then(
|
||||
({ stats, previousFileSizes, warnings }) => {
|
||||
if (warnings.length) {
|
||||
console.log(chalk.yellow('Compiled with warnings.\n'));
|
||||
console.log(warnings.join('\n\n'));
|
||||
console.log(
|
||||
'\nSearch for the ' +
|
||||
chalk.underline(chalk.yellow('keywords')) +
|
||||
' to learn more about each warning.'
|
||||
);
|
||||
console.log(
|
||||
'To ignore, add ' +
|
||||
chalk.cyan('// eslint-disable-next-line') +
|
||||
' to the line before.\n'
|
||||
);
|
||||
} else {
|
||||
console.log(chalk.green('Compiled successfully.\n'));
|
||||
}
|
||||
|
||||
console.log('File sizes after gzip:\n');
|
||||
printFileSizesAfterBuild(
|
||||
stats,
|
||||
previousFileSizes,
|
||||
paths.appBuild,
|
||||
WARN_AFTER_BUNDLE_GZIP_SIZE,
|
||||
WARN_AFTER_CHUNK_GZIP_SIZE
|
||||
);
|
||||
console.log();
|
||||
},
|
||||
err => {
|
||||
console.log(chalk.red('Failed to compile.\n'));
|
||||
printBuildError(err);
|
||||
process.exit(1);
|
||||
}
|
||||
);
|
||||
|
||||
// Create the production build and print the deployment instructions.
|
||||
function build(previousFileSizes) {
|
||||
console.log('Creating an optimized production build...');
|
||||
|
||||
let compiler = webpack(config);
|
||||
return new Promise((resolve, reject) => {
|
||||
compiler.run((err, stats) => {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
const messages = formatWebpackMessages(stats.toJson({}, true));
|
||||
if (messages.errors.length) {
|
||||
// Only keep the first error. Others are often indicative
|
||||
// of the same problem, but confuse the reader with noise.
|
||||
if (messages.errors.length > 1) {
|
||||
messages.errors.length = 1;
|
||||
}
|
||||
return reject(new Error(messages.errors.join('\n\n')));
|
||||
}
|
||||
if (
|
||||
process.env.CI &&
|
||||
(typeof process.env.CI !== 'string' ||
|
||||
process.env.CI.toLowerCase() !== 'false') &&
|
||||
messages.warnings.length
|
||||
) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'\nTreating warnings as errors because process.env.CI = true.\n' +
|
||||
'Most CI servers set it automatically.\n'
|
||||
)
|
||||
);
|
||||
return reject(new Error(messages.warnings.join('\n\n')));
|
||||
}
|
||||
return resolve({
|
||||
stats,
|
||||
previousFileSizes,
|
||||
warnings: messages.warnings,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'production';
|
||||
process.env.NODE_ENV = 'production';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const chalk = require('chalk');
|
||||
const fs = require('fs-extra');
|
||||
const webpack = require('webpack');
|
||||
const config = require('../config/webpack.config.demo');
|
||||
const paths = require('../config/paths');
|
||||
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
|
||||
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
|
||||
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
|
||||
const printBuildError = require('react-dev-utils/printBuildError');
|
||||
|
||||
const measureFileSizesBeforeBuild =
|
||||
FileSizeReporter.measureFileSizesBeforeBuild;
|
||||
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
|
||||
|
||||
// These sizes are pretty large. We'll warn for bundles exceeding them.
|
||||
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
|
||||
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
|
||||
|
||||
// Warn and crash if required files are missing
|
||||
if (!checkRequiredFiles([paths.appDemoIndexJs])) { // CRL: Updated with library index file
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// First, read the current file sizes in build directory.
|
||||
// This lets us display how much they changed later.
|
||||
measureFileSizesBeforeBuild(paths.appDemoBuild)
|
||||
.then(previousFileSizes => {
|
||||
// Remove all content but keep the directory so that
|
||||
// if you're in it, you don't end up in Trash
|
||||
fs.emptyDirSync(paths.appDemoBuild);
|
||||
|
||||
// Start the webpack build
|
||||
return build(previousFileSizes);
|
||||
})
|
||||
.then(
|
||||
({ stats, previousFileSizes, warnings }) => {
|
||||
if (warnings.length) {
|
||||
console.log(chalk.yellow('Compiled with warnings.\n'));
|
||||
console.log(warnings.join('\n\n'));
|
||||
console.log(
|
||||
'\nSearch for the ' +
|
||||
chalk.underline(chalk.yellow('keywords')) +
|
||||
' to learn more about each warning.'
|
||||
);
|
||||
console.log(
|
||||
'To ignore, add ' +
|
||||
chalk.cyan('// eslint-disable-next-line') +
|
||||
' to the line before.\n'
|
||||
);
|
||||
} else {
|
||||
console.log(chalk.green('Compiled successfully.\n'));
|
||||
}
|
||||
|
||||
console.log('File sizes after gzip:\n');
|
||||
printFileSizesAfterBuild(
|
||||
stats,
|
||||
previousFileSizes,
|
||||
paths.appDemoBuild,
|
||||
WARN_AFTER_BUNDLE_GZIP_SIZE,
|
||||
WARN_AFTER_CHUNK_GZIP_SIZE
|
||||
);
|
||||
console.log();
|
||||
},
|
||||
err => {
|
||||
console.log(chalk.red('Failed to compile.\n'));
|
||||
printBuildError(err);
|
||||
process.exit(1);
|
||||
}
|
||||
);
|
||||
|
||||
// Create the production build and print the deployment instructions.
|
||||
function build(previousFileSizes) {
|
||||
console.log('Creating a build of the demo app...');
|
||||
|
||||
let compiler = webpack(config);
|
||||
return new Promise((resolve, reject) => {
|
||||
compiler.run((err, stats) => {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
const messages = formatWebpackMessages(stats.toJson({}, true));
|
||||
if (messages.errors.length) {
|
||||
// Only keep the first error. Others are often indicative
|
||||
// of the same problem, but confuse the reader with noise.
|
||||
if (messages.errors.length > 1) {
|
||||
messages.errors.length = 1;
|
||||
}
|
||||
return reject(new Error(messages.errors.join('\n\n')));
|
||||
}
|
||||
if (
|
||||
process.env.CI &&
|
||||
(typeof process.env.CI !== 'string' ||
|
||||
process.env.CI.toLowerCase() !== 'false') &&
|
||||
messages.warnings.length
|
||||
) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'\nTreating warnings as errors because process.env.CI = true.\n' +
|
||||
'Most CI servers set it automatically.\n'
|
||||
)
|
||||
);
|
||||
return reject(new Error(messages.warnings.join('\n\n')));
|
||||
}
|
||||
return resolve({
|
||||
stats,
|
||||
previousFileSizes,
|
||||
warnings: messages.warnings,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* A module to get package informations from package.json
|
||||
* @module getPackageJson
|
||||
* @param {...string} keys from package.json if no arguments passed it returns package.json content as object
|
||||
* @returns {object} with given keys or content of package.json as object
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns package info
|
||||
*/
|
||||
const getPackageJson = function(...args) {
|
||||
const packageJSON = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json')));
|
||||
if (!args.length) {
|
||||
return packageJSON;
|
||||
}
|
||||
return args.reduce((out, key) => {
|
||||
out[key] = packageJSON[key];
|
||||
return out;
|
||||
}, {});
|
||||
};
|
||||
|
||||
module.exports = getPackageJson;
|
||||
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'development';
|
||||
process.env.NODE_ENV = 'development';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const fs = require('fs');
|
||||
const chalk = require('chalk');
|
||||
const webpack = require('webpack');
|
||||
const WebpackDevServer = require('webpack-dev-server');
|
||||
const clearConsole = require('react-dev-utils/clearConsole');
|
||||
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
|
||||
const {
|
||||
choosePort,
|
||||
createCompiler,
|
||||
prepareProxy,
|
||||
prepareUrls,
|
||||
} = require('react-dev-utils/WebpackDevServerUtils');
|
||||
const openBrowser = require('react-dev-utils/openBrowser');
|
||||
const paths = require('../config/paths');
|
||||
const config = require('../config/webpack.config.dev');
|
||||
const createDevServerConfig = require('../config/webpackDevServer.config');
|
||||
|
||||
const useYarn = fs.existsSync(paths.yarnLockFile);
|
||||
const isInteractive = process.stdout.isTTY;
|
||||
|
||||
// Warn and crash if required files are missing
|
||||
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Tools like Cloud9 rely on this.
|
||||
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
|
||||
// We attempt to use the default port but if it is busy, we offer the user to
|
||||
// run on a different port. `detect()` Promise resolves to the next free port.
|
||||
choosePort(HOST, DEFAULT_PORT)
|
||||
.then(port => {
|
||||
if (port == null) {
|
||||
// We have not found a port.
|
||||
return;
|
||||
}
|
||||
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
|
||||
const appName = require(paths.appPackageJson).name;
|
||||
const urls = prepareUrls(protocol, HOST, port);
|
||||
// Create a webpack compiler that is configured with custom messages.
|
||||
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
|
||||
// Load proxy config
|
||||
const proxySetting = require(paths.appPackageJson).proxy;
|
||||
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
|
||||
// Serve webpack assets generated by the compiler over a web sever.
|
||||
const serverConfig = createDevServerConfig(
|
||||
proxyConfig,
|
||||
urls.lanUrlForConfig
|
||||
);
|
||||
const devServer = new WebpackDevServer(compiler, serverConfig);
|
||||
// Launch WebpackDevServer.
|
||||
devServer.listen(port, HOST, err => {
|
||||
if (err) {
|
||||
return console.log(err);
|
||||
}
|
||||
if (isInteractive) {
|
||||
clearConsole();
|
||||
}
|
||||
console.log(chalk.cyan('Starting the development server...\n'));
|
||||
openBrowser(urls.localUrlForBrowser);
|
||||
});
|
||||
|
||||
['SIGINT', 'SIGTERM'].forEach(function(sig) {
|
||||
process.on(sig, function() {
|
||||
devServer.close();
|
||||
process.exit();
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(err => {
|
||||
if (err && err.message) {
|
||||
console.log(err.message);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'test';
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.PUBLIC_URL = '';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const jest = require('jest');
|
||||
const argv = process.argv.slice(2);
|
||||
|
||||
// Watch unless on CI or in coverage mode
|
||||
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
|
||||
argv.push('--watch');
|
||||
}
|
||||
|
||||
|
||||
jest.run(argv);
|
||||
@@ -1 +0,0 @@
|
||||
module.exports = {};
|
||||
@@ -0,0 +1,31 @@
|
||||
.demoPage {
|
||||
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
.demoPage .screenContainer {
|
||||
background: rgba(0,0,0,0.8);
|
||||
border: 20px solid;
|
||||
height: 300px;
|
||||
border-top-right-radius: 5px;
|
||||
border-top-left-radius: 5px;
|
||||
padding: 10px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.demoPage .inputContainer {
|
||||
color: white;
|
||||
background: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
font-family: monospace;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.simple-keyboard.hg-layout-custom {
|
||||
border-top-left-radius: 0px;
|
||||
border-top-right-radius: 0px;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import React, {Component} from 'react';
|
||||
import Keyboard from '../lib';
|
||||
import './App.css';
|
||||
|
||||
class App extends Component {
|
||||
state = {
|
||||
input: '',
|
||||
layoutName: "default"
|
||||
}
|
||||
|
||||
componentDidMount(){
|
||||
this.keyboard.setInput("Hello World!")
|
||||
.then(input => {
|
||||
this.setState({input: input});
|
||||
});
|
||||
}
|
||||
|
||||
onChange = (input) => {
|
||||
this.setState({
|
||||
input: input
|
||||
}, () => {
|
||||
console.log("Input changed", input);
|
||||
});
|
||||
}
|
||||
|
||||
onKeyPress = (button) => {
|
||||
console.log("Button pressed", button);
|
||||
|
||||
/**
|
||||
* Shift functionality
|
||||
*/
|
||||
if(button === "{lock}" || button === "{shift}")
|
||||
this.handleShiftButton();
|
||||
|
||||
}
|
||||
|
||||
handleShiftButton = () => {
|
||||
let layoutName = this.state.layoutName;
|
||||
let shiftToggle = layoutName === "default" ? "shift" : "default";
|
||||
|
||||
this.setState({
|
||||
layoutName: shiftToggle
|
||||
});
|
||||
}
|
||||
|
||||
render(){
|
||||
return (
|
||||
<div className={"demoPage"}>
|
||||
<div className={"screenContainer"}>
|
||||
<textarea className={"inputContainer"} value={this.state.input} />
|
||||
</div>
|
||||
<Keyboard
|
||||
ref={r => this.keyboard = r}
|
||||
onChange={input => this.onChange(input)}
|
||||
onKeyPress={button => this.onKeyPress(button)}
|
||||
layoutName={this.state.layoutName}
|
||||
layout={{
|
||||
'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}'
|
||||
]
|
||||
}}
|
||||
theme={"hg-layout-default hg-theme-default"}
|
||||
debug={true}
|
||||
display={{
|
||||
'{bksp}': 'delete',
|
||||
'{enter}': '< enter',
|
||||
'{shift}': 'shift',
|
||||
'{s}': 'shift',
|
||||
'{tab}': 'tab',
|
||||
'{lock}': 'caps',
|
||||
'{accept}': 'Submit',
|
||||
'{space}': ' ',
|
||||
'{//}': ' '
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -1,55 +0,0 @@
|
||||
import Keyboard from "../lib";
|
||||
import "./css/BasicDemo.css";
|
||||
|
||||
const setDOM = () => {
|
||||
document.querySelector("body").innerHTML = `
|
||||
<input class="input" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="simple-keyboard"></div>
|
||||
`;
|
||||
};
|
||||
|
||||
class Demo {
|
||||
constructor() {
|
||||
setDOM();
|
||||
|
||||
/**
|
||||
* Demo Start
|
||||
*/
|
||||
this.keyboard = new Keyboard({
|
||||
onChange: input => this.onChange(input),
|
||||
onKeyPress: button => this.onKeyPress(button)
|
||||
});
|
||||
|
||||
/**
|
||||
* Update simple-keyboard when input is changed directly
|
||||
*/
|
||||
document.querySelector(".input").addEventListener("input", event => {
|
||||
this.keyboard.setInput(event.target.value);
|
||||
});
|
||||
}
|
||||
|
||||
onChange(input) {
|
||||
document.querySelector(".input").value = input;
|
||||
console.log("Input changed", input);
|
||||
}
|
||||
|
||||
onKeyPress(button) {
|
||||
console.log("Button pressed", button);
|
||||
|
||||
/**
|
||||
* If you want to handle the shift and caps lock buttons
|
||||
*/
|
||||
if (button === "{shift}" || button === "{lock}") this.handleShift();
|
||||
}
|
||||
|
||||
handleShift() {
|
||||
const currentLayout = this.keyboard.options.layoutName;
|
||||
const shiftToggle = currentLayout === "default" ? "shift" : "default";
|
||||
|
||||
this.keyboard.setOptions({
|
||||
layoutName: shiftToggle
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Demo;
|
||||
@@ -1,73 +0,0 @@
|
||||
import Keyboard from "../lib";
|
||||
import "./css/ButtonThemeDemo.css";
|
||||
|
||||
const setDOM = () => {
|
||||
document.querySelector("body").innerHTML = `
|
||||
<input class="input" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="simple-keyboard"></div>
|
||||
`;
|
||||
};
|
||||
|
||||
class Demo {
|
||||
constructor() {
|
||||
setDOM();
|
||||
|
||||
/**
|
||||
* Demo Start
|
||||
*/
|
||||
this.keyboard = new Keyboard({
|
||||
theme: "hg-theme-default my-theme",
|
||||
onChange: input => this.onChange(input),
|
||||
onKeyPress: button => this.onKeyPress(button),
|
||||
buttonTheme: [
|
||||
{
|
||||
class: "my-button",
|
||||
buttons: "{enter} {bksp} q Q"
|
||||
},
|
||||
{
|
||||
class: "my-button-outline",
|
||||
buttons: "q Q b B"
|
||||
}
|
||||
],
|
||||
buttonAttributes: [
|
||||
{
|
||||
attribute: "aria-label",
|
||||
value: "bee",
|
||||
buttons: "b B"
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
/**
|
||||
* Update simple-keyboard when input is changed directly
|
||||
*/
|
||||
document.querySelector(".input").addEventListener("input", event => {
|
||||
this.keyboard.setInput(event.target.value);
|
||||
});
|
||||
}
|
||||
|
||||
onChange(input) {
|
||||
document.querySelector(".input").value = input;
|
||||
console.log("Input changed", input);
|
||||
}
|
||||
|
||||
onKeyPress(button) {
|
||||
console.log("Button pressed", button);
|
||||
|
||||
/**
|
||||
* If you want to handle the shift and caps lock buttons
|
||||
*/
|
||||
if (button === "{shift}" || button === "{lock}") this.handleShift();
|
||||
}
|
||||
|
||||
handleShift() {
|
||||
const currentLayout = this.keyboard.options.layoutName;
|
||||
const shiftToggle = currentLayout === "default" ? "shift" : "default";
|
||||
|
||||
this.keyboard.setOptions({
|
||||
layoutName: shiftToggle
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Demo;
|
||||
@@ -1,81 +0,0 @@
|
||||
import Keyboard from "../lib";
|
||||
import "./css/CandidateBoxDemo.css";
|
||||
|
||||
const setDOM = () => {
|
||||
document.querySelector("body").innerHTML = `
|
||||
<input class="input" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="simple-keyboard"></div>
|
||||
`;
|
||||
};
|
||||
|
||||
class Demo {
|
||||
constructor() {
|
||||
setDOM();
|
||||
|
||||
/**
|
||||
* Demo Start
|
||||
*/
|
||||
this.keyboard = new Keyboard({
|
||||
onChange: input => this.onChange(input),
|
||||
onKeyPress: button => this.onKeyPress(button),
|
||||
preventMouseDownDefault: true,
|
||||
layoutCandidates: {
|
||||
ni: "你 尼",
|
||||
hao: "好 号"
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Update simple-keyboard when input is changed directly
|
||||
*/
|
||||
document.querySelector(".input").addEventListener("input", event => {
|
||||
this.keyboard.setInput(event.target.value);
|
||||
});
|
||||
}
|
||||
|
||||
onChange(input) {
|
||||
const inputElement = document.querySelector(".input");
|
||||
|
||||
/**
|
||||
* Updating input's value
|
||||
*/
|
||||
inputElement.value = input;
|
||||
console.log("Input changed", input);
|
||||
|
||||
/**
|
||||
* Synchronizing input caret position
|
||||
*/
|
||||
const caretPosition = this.keyboard.caretPosition;
|
||||
if (caretPosition !== null)
|
||||
this.setInputCaretPosition(inputElement, caretPosition);
|
||||
|
||||
console.log("caretPosition", caretPosition);
|
||||
}
|
||||
|
||||
setInputCaretPosition(elem, pos) {
|
||||
if (elem.setSelectionRange) {
|
||||
elem.focus();
|
||||
elem.setSelectionRange(pos, pos);
|
||||
}
|
||||
}
|
||||
|
||||
onKeyPress(button) {
|
||||
console.log("Button pressed", button);
|
||||
|
||||
/**
|
||||
* If you want to handle the shift and caps lock buttons
|
||||
*/
|
||||
if (button === "{shift}" || button === "{lock}") this.handleShift();
|
||||
}
|
||||
|
||||
handleShift() {
|
||||
const currentLayout = this.keyboard.options.layoutName;
|
||||
const shiftToggle = currentLayout === "default" ? "shift" : "default";
|
||||
|
||||
this.keyboard.setOptions({
|
||||
layoutName: shiftToggle
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Demo;
|
||||
@@ -1,31 +0,0 @@
|
||||
import Keyboard from "../lib";
|
||||
import "./css/DOMElementDemo.css";
|
||||
|
||||
class Demo {
|
||||
constructor() {
|
||||
const rootDOM =
|
||||
document.querySelector("body") || document.createElement("div");
|
||||
|
||||
const keyboard1DOM = document.createElement("div");
|
||||
keyboard1DOM.className = "my-keyboard";
|
||||
|
||||
const keyboard2DOM = document.createElement("div");
|
||||
keyboard2DOM.className = "my-keyboard2";
|
||||
|
||||
/**
|
||||
* Demo Start
|
||||
*/
|
||||
this.keyboard1 = new Keyboard(keyboard1DOM, {
|
||||
onChange: input => console.log(this.keyboard1.keyboardDOMClass, input)
|
||||
});
|
||||
|
||||
this.keyboard2 = new Keyboard(keyboard2DOM, {
|
||||
onChange: input => console.log(this.keyboard2.keyboardDOMClass, input)
|
||||
});
|
||||
|
||||
rootDOM.appendChild(keyboard1DOM);
|
||||
rootDOM.appendChild(keyboard2DOM);
|
||||
}
|
||||
}
|
||||
|
||||
export default Demo;
|
||||
@@ -1,157 +0,0 @@
|
||||
import Keyboard from "../lib";
|
||||
import "./css/FullKeyboardDemo.css";
|
||||
|
||||
const setDOM = () => {
|
||||
document.querySelector("body").innerHTML = `
|
||||
<input class="input" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="keyboardContainer">
|
||||
<div class="simple-keyboard-main"></div>
|
||||
|
||||
<div class="controlArrows">
|
||||
<div class="simple-keyboard-control"></div>
|
||||
<div class="simple-keyboard-arrows"></div>
|
||||
</div>
|
||||
|
||||
<div class="numPad">
|
||||
<div class="simple-keyboard-numpad"></div>
|
||||
<div class="simple-keyboard-numpadEnd"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
class Demo {
|
||||
constructor() {
|
||||
setDOM();
|
||||
|
||||
/**
|
||||
* Demo Start
|
||||
*/
|
||||
const commonKeyboardOptions = {
|
||||
onChange: input => this.onChange(input),
|
||||
onKeyPress: button => this.onKeyPress(button),
|
||||
theme: "simple-keyboard hg-theme-default hg-layout-default",
|
||||
physicalKeyboardHighlight: true,
|
||||
syncInstanceInputs: true,
|
||||
mergeDisplay: true,
|
||||
debug: true
|
||||
};
|
||||
|
||||
this.keyboard = new Keyboard(".simple-keyboard-main", {
|
||||
...commonKeyboardOptions,
|
||||
/**
|
||||
* Layout by:
|
||||
* Sterling Butters (https://github.com/SterlingButters)
|
||||
*/
|
||||
layout: {
|
||||
default: [
|
||||
"{escape} {f1} {f2} {f3} {f4} {f5} {f6} {f7} {f8} {f9} {f10} {f11} {f12}",
|
||||
"` 1 2 3 4 5 6 7 8 9 0 - = {backspace}",
|
||||
"{tab} q w e r t y u i o p [ ] \\",
|
||||
"{capslock} a s d f g h j k l ; ' {enter}",
|
||||
"{shiftleft} z x c v b n m , . / {shiftright}",
|
||||
"{controlleft} {altleft} {metaleft} {space} {metaright} {altright}"
|
||||
],
|
||||
shift: [
|
||||
"{escape} {f1} {f2} {f3} {f4} {f5} {f6} {f7} {f8} {f9} {f10} {f11} {f12}",
|
||||
"~ ! @ # $ % ^ & * ( ) _ + {backspace}",
|
||||
"{tab} Q W E R T Y U I O P { } |",
|
||||
'{capslock} A S D F G H J K L : " {enter}',
|
||||
"{shiftleft} Z X C V B N M < > ? {shiftright}",
|
||||
"{controlleft} {altleft} {metaleft} {space} {metaright} {altright}"
|
||||
]
|
||||
},
|
||||
display: {
|
||||
"{escape}": "esc ⎋",
|
||||
"{tab}": "tab ⇥",
|
||||
"{backspace}": "backspace ⌫",
|
||||
"{enter}": "enter ↵",
|
||||
"{capslock}": "caps lock ⇪",
|
||||
"{shiftleft}": "shift ⇧",
|
||||
"{shiftright}": "shift ⇧",
|
||||
"{controlleft}": "ctrl ⌃",
|
||||
"{controlright}": "ctrl ⌃",
|
||||
"{altleft}": "alt ⌥",
|
||||
"{altright}": "alt ⌥",
|
||||
"{metaleft}": "cmd ⌘",
|
||||
"{metaright}": "cmd ⌘"
|
||||
}
|
||||
});
|
||||
|
||||
this.keyboardControlPad = new Keyboard(".simple-keyboard-control", {
|
||||
...commonKeyboardOptions,
|
||||
layout: {
|
||||
default: [
|
||||
"{prtscr} {scrolllock} {pause}",
|
||||
"{insert} {home} {pageup}",
|
||||
"{delete} {end} {pagedown}"
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
this.keyboardArrows = new Keyboard(".simple-keyboard-arrows", {
|
||||
...commonKeyboardOptions,
|
||||
layout: {
|
||||
default: ["{arrowup}", "{arrowleft} {arrowdown} {arrowright}"]
|
||||
}
|
||||
});
|
||||
|
||||
this.keyboardNumPad = new Keyboard(".simple-keyboard-numpad", {
|
||||
...commonKeyboardOptions,
|
||||
layout: {
|
||||
default: [
|
||||
"{numlock} {numpaddivide} {numpadmultiply}",
|
||||
"{numpad7} {numpad8} {numpad9}",
|
||||
"{numpad4} {numpad5} {numpad6}",
|
||||
"{numpad1} {numpad2} {numpad3}",
|
||||
"{numpad0} {numpaddecimal}"
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
this.keyboardNumPadEnd = new Keyboard(".simple-keyboard-numpadEnd", {
|
||||
...commonKeyboardOptions,
|
||||
layout: {
|
||||
default: ["{numpadsubtract}", "{numpadadd}", "{numpadenter}"]
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector(".input").addEventListener("input", () => {
|
||||
const input = document.querySelector(".input").value;
|
||||
this.keyboard.setInput(input);
|
||||
});
|
||||
}
|
||||
|
||||
onChange(input) {
|
||||
document.querySelector(".input").value = input;
|
||||
this.keyboard.setInput(input);
|
||||
|
||||
console.log("Input changed", input);
|
||||
}
|
||||
|
||||
onKeyPress(button) {
|
||||
console.log("Button pressed", button);
|
||||
|
||||
/**
|
||||
* If you want to handle the shift and caps lock buttons
|
||||
*/
|
||||
if (
|
||||
button === "{shift}" ||
|
||||
button === "{shiftleft}" ||
|
||||
button === "{shiftright}" ||
|
||||
button === "{capslock}"
|
||||
)
|
||||
this.handleShift();
|
||||
}
|
||||
|
||||
handleShift() {
|
||||
const currentLayout = this.keyboard.options.layoutName;
|
||||
const shiftToggle = currentLayout === "default" ? "shift" : "default";
|
||||
|
||||
this.keyboard.setOptions({
|
||||
layoutName: shiftToggle
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Demo;
|
||||
@@ -1,92 +0,0 @@
|
||||
import Keyboard from "../lib";
|
||||
import "./css/MultipleKeyboardsDestroyDemo.css";
|
||||
|
||||
const setDOM = () => {
|
||||
document.querySelector("body").innerHTML = `
|
||||
<input class="input" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="simple-keyboard"></div>
|
||||
|
||||
<input class="input2" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="keyboard2"></div>
|
||||
`;
|
||||
};
|
||||
|
||||
class Demo {
|
||||
constructor() {
|
||||
setDOM();
|
||||
|
||||
/**
|
||||
* Demo Start
|
||||
*/
|
||||
this.keyboard = new Keyboard({
|
||||
onChange: input => this.onChange(input),
|
||||
onKeyPress: button => this.onKeyPress(button),
|
||||
debug: true
|
||||
});
|
||||
|
||||
this.keyboard2 = new Keyboard(".keyboard2", {
|
||||
theme: "simple-keyboard hg-theme-default",
|
||||
onChange: input => this.onChange(input, "input2"),
|
||||
onKeyPress: button => this.onKeyPress(button, "keyboard2"),
|
||||
debug: true
|
||||
});
|
||||
|
||||
console.log(this.keyboard);
|
||||
setTimeout(() => {
|
||||
this.keyboard.destroy();
|
||||
document.querySelector(".input").value = "";
|
||||
}, 10000);
|
||||
setTimeout(() => {
|
||||
this.keyboard = new Keyboard({
|
||||
theme: "hg-theme-default myTheme",
|
||||
onChange: input => this.onChange(input),
|
||||
onKeyPress: button => this.onKeyPress(button),
|
||||
debug: true,
|
||||
onInit: () => {
|
||||
console.log(
|
||||
"Reinitialized simple-keyboard instance:",
|
||||
this.keyboard.keyboardDOMClass
|
||||
);
|
||||
}
|
||||
});
|
||||
}, 15000);
|
||||
|
||||
/**
|
||||
* Update simple-keyboard when input is changed directly
|
||||
*/
|
||||
document.querySelector(".input").addEventListener("input", event => {
|
||||
this.keyboard.setInput(event.target.value);
|
||||
});
|
||||
|
||||
document.querySelector(".input2").addEventListener("input", event => {
|
||||
this.keyboard2.setInput(event.target.value);
|
||||
});
|
||||
}
|
||||
|
||||
onChange(input, inputClass) {
|
||||
document.querySelector(`.${inputClass || "input"}`).value = input;
|
||||
console.log("Input changed", input);
|
||||
}
|
||||
|
||||
onKeyPress(button, keyboardInstanceKey) {
|
||||
console.log("Button pressed", button);
|
||||
|
||||
/**
|
||||
* If you want to handle the shift and caps lock buttons
|
||||
*/
|
||||
if (button === "{shift}" || button === "{lock}")
|
||||
this.handleShift(keyboardInstanceKey);
|
||||
}
|
||||
|
||||
handleShift(keyboardInstanceKey) {
|
||||
const keyboard = this[keyboardInstanceKey || "keyboard"];
|
||||
const currentLayout = keyboard.options.layoutName;
|
||||
const shiftToggle = currentLayout === "default" ? "shift" : "default";
|
||||
|
||||
keyboard.setOptions({
|
||||
layoutName: shiftToggle
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Demo;
|
||||
@@ -1,72 +0,0 @@
|
||||
import Keyboard from "../lib";
|
||||
import "./css/RTLDemo.css";
|
||||
|
||||
const setDOM = () => {
|
||||
document.querySelector("body").innerHTML = `
|
||||
<input class="input" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="simple-keyboard"></div>
|
||||
`;
|
||||
};
|
||||
|
||||
class Demo {
|
||||
constructor() {
|
||||
setDOM();
|
||||
|
||||
/**
|
||||
* Demo Start
|
||||
*/
|
||||
this.keyboard = new Keyboard({
|
||||
onChange: input => this.onChange(input),
|
||||
onKeyPress: button => this.onKeyPress(button),
|
||||
rtl: true,
|
||||
layout: {
|
||||
default: [
|
||||
"\u05e5 1 2 3 4 5 6 7 8 9 0 - = {bksp}",
|
||||
"{tab} \u05e3 \u05df \u05e7 \u05e8 \u05d0 \u05d8 \u05d5 \u05ea \u05dd \u05e4 ] [ \\",
|
||||
"{lock} \u05e9 \u05d3 \u05d2 \u05db \u05e2 \u05d9 \u05d7 \u05dc \u05da : ' {enter}",
|
||||
"{shift} \u05d6 \u05e1 \u05d1 \u05d4 \u05e0 \u05de \u05e6 , . / {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}"
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Update simple-keyboard when input is changed directly
|
||||
*/
|
||||
document.querySelector(".input").addEventListener("input", event => {
|
||||
this.keyboard.setInput(event.target.value);
|
||||
});
|
||||
}
|
||||
|
||||
onChange(input) {
|
||||
document.querySelector(".input").value = input;
|
||||
console.log("Input changed", input, input.split(""));
|
||||
}
|
||||
|
||||
onKeyPress(button) {
|
||||
console.log("Button pressed", button);
|
||||
|
||||
/**
|
||||
* If you want to handle the shift and caps lock buttons
|
||||
*/
|
||||
if (button === "{shift}" || button === "{lock}") this.handleShift();
|
||||
}
|
||||
|
||||
handleShift() {
|
||||
const currentLayout = this.keyboard.options.layoutName;
|
||||
const shiftToggle = currentLayout === "default" ? "shift" : "default";
|
||||
|
||||
this.keyboard.setOptions({
|
||||
layoutName: shiftToggle
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Demo;
|
||||
@@ -1,12 +0,0 @@
|
||||
input {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
padding: 20px;
|
||||
font-size: 20px;
|
||||
border: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.simple-keyboard {
|
||||
max-width: 850px;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
input {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
padding: 20px;
|
||||
font-size: 20px;
|
||||
border: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.simple-keyboard {
|
||||
max-width: 850px;
|
||||
}
|
||||
|
||||
.simple-keyboard.my-theme .hg-button.my-button {
|
||||
background: blue;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.simple-keyboard.my-theme .hg-button[aria-label] {
|
||||
background: black;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.simple-keyboard.my-theme .hg-button.my-button-outline {
|
||||
border: 2px solid red;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
input {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
padding: 20px;
|
||||
font-size: 20px;
|
||||
border: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.simple-keyboard {
|
||||
max-width: 850px;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
input {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
padding: 20px;
|
||||
font-size: 20px;
|
||||
border: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.my-keyboard,
|
||||
.my-keyboard2 {
|
||||
max-width: 850px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
input {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
padding: 20px;
|
||||
font-size: 20px;
|
||||
border: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.keyboardContainer {
|
||||
display: flex;
|
||||
background-color: rgba(0, 0, 0, 0.1);
|
||||
justify-content: center;
|
||||
width: 1024px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.simple-keyboard.hg-theme-default {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.simple-keyboard-main.simple-keyboard {
|
||||
width: 640px;
|
||||
min-width: 640px;
|
||||
background: none;
|
||||
}
|
||||
|
||||
.simple-keyboard-main.simple-keyboard .hg-row:first-child {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.simple-keyboard-arrows.simple-keyboard {
|
||||
align-self: flex-end;
|
||||
background: none;
|
||||
}
|
||||
|
||||
.simple-keyboard .hg-button.selectedButton {
|
||||
background: rgba(5, 25, 70, 0.53);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.simple-keyboard .hg-button.emptySpace {
|
||||
pointer-events: none;
|
||||
background: none;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.simple-keyboard-arrows .hg-row {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.simple-keyboard-arrows .hg-button {
|
||||
width: 50px;
|
||||
flex-grow: 0;
|
||||
justify-content: center;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.controlArrows {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-flow: column;
|
||||
}
|
||||
|
||||
.simple-keyboard-control.simple-keyboard {
|
||||
background: none;
|
||||
}
|
||||
|
||||
.simple-keyboard-control.simple-keyboard .hg-row:first-child {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.simple-keyboard-control .hg-button {
|
||||
width: 50px;
|
||||
flex-grow: 0;
|
||||
justify-content: center;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.numPad {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.simple-keyboard-numpad.simple-keyboard {
|
||||
background: none;
|
||||
}
|
||||
|
||||
.simple-keyboard-numpad.simple-keyboard {
|
||||
width: 160px;
|
||||
}
|
||||
|
||||
.simple-keyboard-numpad.simple-keyboard .hg-button {
|
||||
width: 50px;
|
||||
justify-content: center;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.simple-keyboard-numpadEnd.simple-keyboard {
|
||||
width: 50px;
|
||||
background: none;
|
||||
margin: 0;
|
||||
padding: 5px 5px 5px 0;
|
||||
}
|
||||
|
||||
.simple-keyboard-numpadEnd.simple-keyboard .hg-button {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.simple-keyboard-numpadEnd .hg-button.hg-standardBtn.hg-button-plus {
|
||||
height: 85px;
|
||||
}
|
||||
|
||||
.simple-keyboard-numpadEnd.simple-keyboard .hg-button.hg-button-enter {
|
||||
height: 85px;
|
||||
}
|
||||
|
||||
.simple-keyboard.hg-theme-default .hg-button.hg-selectedButton {
|
||||
background: rgba(5, 25, 70, 0.53);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.hg-button.hg-functionBtn.hg-button-space {
|
||||
width: 350px;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
input {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
padding: 20px;
|
||||
font-size: 20px;
|
||||
border: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.simple-keyboard {
|
||||
max-width: 850px;
|
||||
}
|
||||
|
||||
.simple-keyboard.hg-theme-default.myTheme {
|
||||
background-color: #bde6c6;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
input {
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
padding: 20px;
|
||||
font-size: 20px;
|
||||
border: none;
|
||||
box-sizing: border-box;
|
||||
direction: rtl;
|
||||
}
|
||||
|
||||
.simple-keyboard {
|
||||
max-width: 850px;
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
#root {
|
||||
padding: 0px 40px;
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 6.7 KiB |
+6
-21
@@ -1,22 +1,7 @@
|
||||
import "./css/index.css";
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import App from './App';
|
||||
import registerServiceWorker from './registerServiceWorker';
|
||||
|
||||
/**
|
||||
* Demos
|
||||
*/
|
||||
import BasicDemo from "./BasicDemo";
|
||||
//import RTLDemo from "./RTLDemo";
|
||||
//import ButtonThemeDemo from "./ButtonThemeDemo";
|
||||
//import DOMElementDemo from "./DOMElementDemo";
|
||||
//import FullKeyboardDemo from "./FullKeyboardDemo";
|
||||
//import MultipleKeyboardsDemo from "./MultipleKeyboardsDestroyDemo";
|
||||
//import CandidateBoxDemo from "./CandidateBoxDemo";
|
||||
|
||||
/**
|
||||
* Selected demo
|
||||
*/
|
||||
const SELECTED_DEMO = BasicDemo;
|
||||
|
||||
/**
|
||||
* Bootstrap
|
||||
*/
|
||||
new SELECTED_DEMO();
|
||||
ReactDOM.render(<App />, document.getElementById('root'));
|
||||
registerServiceWorker();
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// In production, we register a service worker to serve assets from local cache.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on the "N+1" visit to a page, since previously
|
||||
// cached resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
|
||||
// This link also includes instructions on opting out of this behavior.
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
);
|
||||
|
||||
export default function register() {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Lets check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl);
|
||||
} else {
|
||||
// Is not local host. Just register service worker
|
||||
registerValidSW(swUrl);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing;
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the old content will have been purged and
|
||||
// the fresh content will have been added to the cache.
|
||||
// It's the perfect time to display a "New content is
|
||||
// available; please refresh." message in your web app.
|
||||
console.log('New content is available; please refresh.');
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.');
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
if (
|
||||
response.status === 404 ||
|
||||
response.headers.get('content-type').indexOf('javascript') === -1
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { setDOM } from '../../utils/TestUtility';
|
||||
import BasicDemo from '../BasicDemo';
|
||||
|
||||
it('Demo will load', () => {
|
||||
setDOM();
|
||||
|
||||
new BasicDemo();
|
||||
});
|
||||
|
||||
it('Demo onDOMLoaded will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new BasicDemo();
|
||||
|
||||
expect(demo.keyboard).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new BasicDemo();
|
||||
|
||||
demo.onChange("test");
|
||||
|
||||
expect(document.body.querySelector('.input').value).toBe("test");
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new BasicDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("q").onclick();
|
||||
|
||||
expect(document.body.querySelector('.input').value).toBe("q");
|
||||
});
|
||||
|
||||
it('Demo input change will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new BasicDemo();
|
||||
|
||||
document.body.querySelector('.input').value = "test";
|
||||
document.body.querySelector('.input').dispatchEvent(new Event('input'));
|
||||
|
||||
expect(demo.keyboard.getInput()).toBe("test");
|
||||
});
|
||||
|
||||
it('Demo handleShiftButton will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new BasicDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("shift");
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("default");
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import { setDOM } from '../../utils/TestUtility';
|
||||
import ButtonThemeDemo from '../ButtonThemeDemo';
|
||||
|
||||
it('Demo will load', () => {
|
||||
setDOM();
|
||||
|
||||
new ButtonThemeDemo();
|
||||
});
|
||||
|
||||
it('Demo onDOMLoaded will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new ButtonThemeDemo();
|
||||
|
||||
expect(demo.keyboard).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new ButtonThemeDemo();
|
||||
|
||||
demo.onChange("test");
|
||||
|
||||
expect(document.body.querySelector('.input').value).toBe("test");
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new ButtonThemeDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("q").onclick();
|
||||
|
||||
expect(document.body.querySelector('.input').value).toBe("q");
|
||||
});
|
||||
|
||||
it('Demo input change will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new ButtonThemeDemo();
|
||||
|
||||
document.body.querySelector('.input').value = "test";
|
||||
document.body.querySelector('.input').dispatchEvent(new Event('input'));
|
||||
|
||||
expect(demo.keyboard.getInput()).toBe("test");
|
||||
});
|
||||
|
||||
it('Demo handleShiftButton will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new ButtonThemeDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("shift");
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("default");
|
||||
});
|
||||
|
||||
it('Demo buttons will have proper attributes and classes', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new ButtonThemeDemo();
|
||||
|
||||
const buttonDOM = demo.keyboard.getButtonElement("b");
|
||||
|
||||
console.log("buttonDOM", buttonDOM.outerHTML);
|
||||
|
||||
const hasAttribute = buttonDOM.hasAttribute("aria-label");
|
||||
expect(hasAttribute).toBeTruthy();
|
||||
|
||||
const hasClass = buttonDOM.classList.contains("my-button-outline");
|
||||
expect(hasClass).toBeTruthy();
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import { setDOM } from '../../utils/TestUtility';
|
||||
import CandidateBoxDemo from '../CandidateBoxDemo';
|
||||
|
||||
it('Demo will load', () => {
|
||||
setDOM();
|
||||
|
||||
new CandidateBoxDemo();
|
||||
});
|
||||
|
||||
it('Demo caret positioning will adjust accordingly', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new CandidateBoxDemo();
|
||||
|
||||
demo.keyboard.setCaretPosition(0);
|
||||
|
||||
demo.keyboard.getButtonElement("n").click();
|
||||
demo.keyboard.getButtonElement("h").click();
|
||||
demo.keyboard.getButtonElement("a").click();
|
||||
demo.keyboard.getButtonElement("o").click();
|
||||
expect(demo.keyboard.getCaretPosition()).toBe(4);
|
||||
|
||||
demo.keyboard.candidateBox.candidateBoxElement.querySelector("li").click();
|
||||
|
||||
expect(demo.keyboard.getCaretPosition()).toBe(2);
|
||||
|
||||
demo.keyboard.setCaretPosition(1);
|
||||
demo.keyboard.getButtonElement("i").click();
|
||||
|
||||
expect(demo.keyboard.getCaretPosition()).toBe(2);
|
||||
|
||||
demo.keyboard.candidateBox.candidateBoxElement.querySelector("li").click();
|
||||
|
||||
expect(demo.keyboard.getCaretPosition()).toBe(1);
|
||||
expect(demo.keyboard.getInput()).toBe("你好");
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
import DOMElementDemo from '../DOMElementDemo';
|
||||
import Keyboard from '../../lib/components/Keyboard';
|
||||
|
||||
it('Demo will load', () => {
|
||||
new DOMElementDemo();
|
||||
});
|
||||
|
||||
it('Demo keyboards will be instantiated', () => {
|
||||
const demo = new DOMElementDemo();
|
||||
expect(demo.keyboard1).toBeInstanceOf(Keyboard);
|
||||
expect(demo.keyboard2).toBeInstanceOf(Keyboard);
|
||||
});
|
||||
|
||||
it('Demo input change will work', () => {
|
||||
const demo = new DOMElementDemo();
|
||||
|
||||
demo.keyboard1.getButtonElement("q").onclick();
|
||||
demo.keyboard2.getButtonElement("e").onclick();
|
||||
|
||||
expect(demo.keyboard1.getInput()).toBe("q");
|
||||
expect(demo.keyboard2.getInput()).toBe("e");
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
import { setDOM } from '../../utils/TestUtility';
|
||||
import FullKeyboardDemo from '../FullKeyboardDemo';
|
||||
|
||||
it('Demo will load', () => {
|
||||
setDOM();
|
||||
new FullKeyboardDemo();
|
||||
});
|
||||
|
||||
it('Demo onDOMLoaded will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new FullKeyboardDemo();
|
||||
|
||||
expect(demo.keyboard).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new FullKeyboardDemo();
|
||||
|
||||
demo.onChange("test");
|
||||
|
||||
expect(document.body.querySelector('.input').value).toBe("test");
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new FullKeyboardDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("q").onclick();
|
||||
|
||||
expect(document.body.querySelector('.input').value).toBe("q");
|
||||
});
|
||||
|
||||
it('Demo input change will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new FullKeyboardDemo();
|
||||
|
||||
document.body.querySelector('.input').value = "test";
|
||||
document.body.querySelector('.input').dispatchEvent(new Event('input'));
|
||||
|
||||
expect(demo.keyboard.getInput()).toBe("test");
|
||||
expect(demo.keyboardNumPad.getInput()).toBe("test");
|
||||
});
|
||||
|
||||
it('Demo handleShiftButton will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new FullKeyboardDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("{shiftleft}").onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("shift");
|
||||
|
||||
demo.keyboard.getButtonElement("{shiftright}").onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("default");
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
import { setDOM } from '../../utils/TestUtility';
|
||||
import MultipleKeyboardsDestroyDemo from '../MultipleKeyboardsDestroyDemo';
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
it('Demo will load', () => {
|
||||
setDOM();
|
||||
|
||||
new MultipleKeyboardsDestroyDemo();
|
||||
});
|
||||
|
||||
it('Demo onDOMLoaded will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new MultipleKeyboardsDestroyDemo();
|
||||
|
||||
expect(demo.keyboard).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new MultipleKeyboardsDestroyDemo();
|
||||
|
||||
demo.onChange("test");
|
||||
demo.keyboard2.getButtonElement("q").click();
|
||||
|
||||
expect(document.body.querySelector('.input').value).toBe("test");
|
||||
expect(document.body.querySelector('.input2').value).toBe("q");
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new MultipleKeyboardsDestroyDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("q").onclick();
|
||||
|
||||
expect(document.body.querySelector('.input').value).toBe("q");
|
||||
});
|
||||
|
||||
it('Demo input change will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new MultipleKeyboardsDestroyDemo();
|
||||
|
||||
document.body.querySelector('.input').value = "test";
|
||||
document.body.querySelector('.input').dispatchEvent(new Event('input'));
|
||||
|
||||
document.body.querySelector('.input2').value = "test2";
|
||||
document.body.querySelector('.input2').dispatchEvent(new Event('input'));
|
||||
|
||||
expect(demo.keyboard.getInput()).toBe("test");
|
||||
expect(demo.keyboard2.getInput()).toBe("test2");
|
||||
});
|
||||
|
||||
it('Demo handleShiftButton will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new MultipleKeyboardsDestroyDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("shift");
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("default");
|
||||
});
|
||||
|
||||
it('MultipleKeyboardsDestroyDemo will run all timers', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new MultipleKeyboardsDestroyDemo();
|
||||
jest.runAllTimers();
|
||||
|
||||
expect(demo.keyboard.options.theme).toBe("hg-theme-default myTheme");
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("shift");
|
||||
|
||||
demo.keyboard.getButtonElement("A").onclick();
|
||||
expect(demo.keyboard.input.default).toBe("A");
|
||||
});
|
||||
@@ -1,72 +0,0 @@
|
||||
import { setDOM, removeRTLControls } from '../../utils/TestUtility';
|
||||
import RTLDemo from '../RTLDemo';
|
||||
|
||||
it('Demo will load', () => {
|
||||
setDOM();
|
||||
|
||||
new RTLDemo();
|
||||
});
|
||||
|
||||
it('Demo onDOMLoaded will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new RTLDemo();
|
||||
|
||||
expect(demo.keyboard).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new RTLDemo();
|
||||
|
||||
demo.onChange("test");
|
||||
|
||||
expect(removeRTLControls(document.body.querySelector('.input').value)).toBe("test");
|
||||
});
|
||||
|
||||
it('Demo onChange will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new RTLDemo();
|
||||
|
||||
demo.keyboard.getButtonElement(".").onclick();
|
||||
|
||||
expect(removeRTLControls(document.body.querySelector('.input').value)).toBe(".");
|
||||
});
|
||||
|
||||
it('Demo input change will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new RTLDemo();
|
||||
|
||||
document.body.querySelector('.input').value = "test";
|
||||
document.body.querySelector('.input').dispatchEvent(new Event('input'));
|
||||
|
||||
expect(removeRTLControls(demo.keyboard.getInput())).toBe("test");
|
||||
});
|
||||
|
||||
it('Demo handleShiftButton will work', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new RTLDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("shift");
|
||||
|
||||
demo.keyboard.getButtonElement("{shift}")[0].onclick();
|
||||
expect(demo.keyboard.options.layoutName).toBe("default");
|
||||
});
|
||||
|
||||
it('RTL control caracters will be added to ', () => {
|
||||
setDOM();
|
||||
|
||||
const demo = new RTLDemo();
|
||||
|
||||
demo.keyboard.getButtonElement("פ").onclick();
|
||||
demo.keyboard.getButtonElement("ם").onclick();
|
||||
demo.keyboard.getButtonElement("[").onclick();
|
||||
|
||||
expect(demo.keyboard.getInput()).toBe("פם[");
|
||||
expect(demo.keyboard.input[demo.keyboard.options.inputName]).toBe("פם[");
|
||||
});
|
||||
@@ -1,138 +0,0 @@
|
||||
import "./css/CandidateBox.css";
|
||||
|
||||
import Utilities from "../services/Utilities";
|
||||
import {
|
||||
CandidateBoxParams,
|
||||
CandidateBoxRenderParams,
|
||||
CandidateBoxShowParams,
|
||||
} from "./../interfaces";
|
||||
|
||||
class CandidateBox {
|
||||
utilities: Utilities;
|
||||
candidateBoxElement!: HTMLDivElement;
|
||||
pageIndex = 0;
|
||||
pageSize;
|
||||
|
||||
constructor({ utilities }: CandidateBoxParams) {
|
||||
this.utilities = utilities;
|
||||
Utilities.bindMethods(CandidateBox, this);
|
||||
this.pageSize = this.utilities.getOptions().layoutCandidatesPageSize || 5;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (this.candidateBoxElement) {
|
||||
this.candidateBoxElement.remove();
|
||||
this.pageIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
show({
|
||||
candidateValue,
|
||||
targetElement,
|
||||
onSelect,
|
||||
}: CandidateBoxShowParams): void {
|
||||
if (!candidateValue || !candidateValue.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const candidateListPages = this.utilities.chunkArray(
|
||||
candidateValue.split(" "),
|
||||
this.pageSize
|
||||
);
|
||||
|
||||
this.renderPage({
|
||||
candidateListPages,
|
||||
targetElement,
|
||||
pageIndex: this.pageIndex,
|
||||
nbPages: candidateListPages.length,
|
||||
onItemSelected: (selectedCandidate: string, e: MouseEvent) => {
|
||||
onSelect(selectedCandidate, e);
|
||||
this.destroy();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
renderPage({
|
||||
candidateListPages,
|
||||
targetElement,
|
||||
pageIndex,
|
||||
nbPages,
|
||||
onItemSelected,
|
||||
}: CandidateBoxRenderParams) {
|
||||
// Remove current candidate box, if any
|
||||
this.candidateBoxElement?.remove();
|
||||
|
||||
// Create candidate box element
|
||||
this.candidateBoxElement = document.createElement("div");
|
||||
this.candidateBoxElement.className = "hg-candidate-box";
|
||||
|
||||
// Candidate box list
|
||||
const candidateListULElement = document.createElement("ul");
|
||||
candidateListULElement.className = "hg-candidate-box-list";
|
||||
|
||||
// Create Candidate box list items
|
||||
candidateListPages[pageIndex].forEach((candidateListItem) => {
|
||||
const candidateListLIElement = document.createElement("li");
|
||||
const getMouseEvent = () => {
|
||||
const mouseEvent = new MouseEvent("click");
|
||||
Object.defineProperty(mouseEvent, "target", {
|
||||
value: candidateListLIElement,
|
||||
});
|
||||
return mouseEvent;
|
||||
};
|
||||
|
||||
candidateListLIElement.className = "hg-candidate-box-list-item";
|
||||
candidateListLIElement.textContent = candidateListItem;
|
||||
candidateListLIElement.onclick = (e = getMouseEvent()) =>
|
||||
onItemSelected(candidateListItem, e);
|
||||
|
||||
// Append list item to ul
|
||||
candidateListULElement.appendChild(candidateListLIElement);
|
||||
});
|
||||
|
||||
// Add previous button
|
||||
const isPrevBtnElementActive = pageIndex > 0;
|
||||
const prevBtnElement = document.createElement("div");
|
||||
prevBtnElement.classList.add("hg-candidate-box-prev");
|
||||
isPrevBtnElementActive &&
|
||||
prevBtnElement.classList.add("hg-candidate-box-btn-active");
|
||||
prevBtnElement.onclick = () => {
|
||||
if (!isPrevBtnElementActive) return;
|
||||
this.renderPage({
|
||||
candidateListPages,
|
||||
targetElement,
|
||||
pageIndex: pageIndex - 1,
|
||||
nbPages,
|
||||
onItemSelected,
|
||||
});
|
||||
};
|
||||
this.candidateBoxElement.appendChild(prevBtnElement);
|
||||
|
||||
// Add elements to container
|
||||
this.candidateBoxElement.appendChild(candidateListULElement);
|
||||
|
||||
// Add next button
|
||||
const isNextBtnElementActive = pageIndex < nbPages - 1;
|
||||
const nextBtnElement = document.createElement("div");
|
||||
nextBtnElement.classList.add("hg-candidate-box-next");
|
||||
isNextBtnElementActive &&
|
||||
nextBtnElement.classList.add("hg-candidate-box-btn-active");
|
||||
|
||||
nextBtnElement.onclick = () => {
|
||||
if (!isNextBtnElementActive) return;
|
||||
this.renderPage({
|
||||
candidateListPages,
|
||||
targetElement,
|
||||
pageIndex: pageIndex + 1,
|
||||
nbPages,
|
||||
onItemSelected,
|
||||
});
|
||||
};
|
||||
this.candidateBoxElement.appendChild(nextBtnElement);
|
||||
|
||||
// Append candidate box to target element
|
||||
targetElement.prepend(this.candidateBoxElement);
|
||||
}
|
||||
}
|
||||
|
||||
export default CandidateBox;
|
||||
@@ -0,0 +1,66 @@
|
||||
body, html {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.simple-keyboard {
|
||||
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
|
||||
width: 100%;
|
||||
user-select: none;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.simple-keyboard .hg-row {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.simple-keyboard .hg-row:not(:last-child) {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.simple-keyboard .hg-row .hg-button:not(:last-child) {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.simple-keyboard .hg-button {
|
||||
display: inline-block;
|
||||
flex-grow: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.simple-keyboard.hg-layout-default .hg-button.hg-standardBtn {
|
||||
max-width: 100px;
|
||||
}
|
||||
|
||||
/**
|
||||
* hg-theme-default theme
|
||||
*/
|
||||
.simple-keyboard.hg-theme-default {
|
||||
background-color: rgba(0,0,0,0.2);
|
||||
padding: 5px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.simple-keyboard.hg-theme-default .hg-button {
|
||||
box-shadow: 0px 0px 3px -1px rgba(0,0,0,0.3);
|
||||
height: 40px;
|
||||
border: 1px solid rgba(0,0,0,0.25);
|
||||
border-radius: 5px;
|
||||
box-sizing: border-box;
|
||||
padding: 5px;
|
||||
background: white;
|
||||
border-bottom: 1px solid gray;
|
||||
}
|
||||
|
||||
.simple-keyboard.hg-theme-default .hg-button:active {
|
||||
background: #e4e4e4;
|
||||
}
|
||||
|
||||
.simple-keyboard.hg-theme-default.hg-layout-numeric .hg-button {
|
||||
width: 33.3%;
|
||||
height: 60px;
|
||||
align-items: center;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import React, { Component } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './Keyboard.css';
|
||||
|
||||
// Services
|
||||
import KeyboardLayout from '../services/KeyboardLayout';
|
||||
import Utilities from '../services/Utilities';
|
||||
|
||||
class App extends Component {
|
||||
state = {
|
||||
input: ''
|
||||
}
|
||||
|
||||
componentWillReceiveProps = (nextProps) => {
|
||||
if(
|
||||
this.props !== nextProps
|
||||
){
|
||||
this.setState({
|
||||
layoutName: nextProps.layoutName,
|
||||
layout: nextProps.layout,
|
||||
themeClass: nextProps.theme
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
clearInput = () => {
|
||||
this.setState({
|
||||
input: ''
|
||||
});
|
||||
}
|
||||
|
||||
getInput = () => {
|
||||
return this.state.input;
|
||||
}
|
||||
|
||||
setInput = input => {
|
||||
return new Promise(resolve => {
|
||||
this.setState({
|
||||
input: input
|
||||
}, () => {
|
||||
resolve(input);
|
||||
});
|
||||
})
|
||||
.catch(reason => {
|
||||
console.warn(reason);
|
||||
});
|
||||
}
|
||||
|
||||
handleButtonClicked = (button) => {
|
||||
let debug = this.props.debug;
|
||||
|
||||
/**
|
||||
* Ignoring placeholder buttons
|
||||
*/
|
||||
if(button === '{//}')
|
||||
return false;
|
||||
|
||||
/**
|
||||
* Calling onKeyPress
|
||||
*/
|
||||
if(typeof this.props.onKeyPress === "function")
|
||||
this.props.onKeyPress(button);
|
||||
|
||||
/**
|
||||
* Updating input
|
||||
*/
|
||||
let options = {
|
||||
newLineOnEnter: this.props.newLineOnEnter !== false || true
|
||||
}
|
||||
|
||||
let updatedInput = Utilities.getUpdatedInput(button, this.state.input, options);
|
||||
|
||||
if(this.state.input !== updatedInput){
|
||||
this.setState({
|
||||
input: updatedInput
|
||||
}, () => {
|
||||
if(debug){
|
||||
console.log('Input changed:', this.state.input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calling onChange
|
||||
*/
|
||||
if(typeof this.props.onChange === "function")
|
||||
this.props.onChange(this.state.input);
|
||||
});
|
||||
}
|
||||
|
||||
if(debug){
|
||||
console.log("Key pressed:", button);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
let layoutName = this.props.layoutName || "default";
|
||||
let layout = this.props.layout || KeyboardLayout.getLayout(layoutName);
|
||||
let themeClass = this.props.theme || "hg-theme-default";
|
||||
let layoutClass = this.props.layout ? "hg-layout-custom" : `hg-layout-${layoutName}`;
|
||||
|
||||
return (
|
||||
<div className={`simple-keyboard ${themeClass} ${layoutClass}`}>
|
||||
{layout[layoutName].map((row, index) => {
|
||||
let rowArray = row.split(' ');
|
||||
|
||||
return (
|
||||
<div key={`hg-row-${index}`} className="hg-row">
|
||||
{rowArray.map((button, index) => {
|
||||
let fctBtnClass = Utilities.getButtonClass(button);
|
||||
let buttonDisplayName = Utilities.getButtonDisplayName(button, this.props.display);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`hg-button-${index}`}
|
||||
className={`hg-button ${fctBtnClass}`}
|
||||
onClick={() => this.handleButtonClicked(button)}
|
||||
><span>{buttonDisplayName}</span></div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
App.propTypes = {
|
||||
layoutName: PropTypes.string,
|
||||
layout: PropTypes.object,
|
||||
theme: PropTypes.string,
|
||||
display: PropTypes.object,
|
||||
onChange: PropTypes.func,
|
||||
onKeyPress: PropTypes.func,
|
||||
debug: PropTypes.bool
|
||||
};
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,8 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import Keyboard from './Keyboard';
|
||||
|
||||
it('Keyboard renders without crashing', () => {
|
||||
const div = document.createElement('div');
|
||||
ReactDOM.render(<Keyboard />, div);
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,68 +0,0 @@
|
||||
.hg-candidate-box {
|
||||
display: inline-flex;
|
||||
border-radius: 5px;
|
||||
position: absolute;
|
||||
background: #ececec;
|
||||
border-bottom: 2px solid #b5b5b5;
|
||||
user-select: none;
|
||||
max-width: 272px;
|
||||
transform: translateY(-100%);
|
||||
margin-top: -10px;
|
||||
}
|
||||
|
||||
ul.hg-candidate-box-list {
|
||||
display: flex;
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
li.hg-candidate-box-list-item {
|
||||
height: 40px;
|
||||
width: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
li.hg-candidate-box-list-item:hover {
|
||||
background: rgba(0, 0, 0, 0.03);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
li.hg-candidate-box-list-item:active {
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.hg-candidate-box-prev::before {
|
||||
content: "◄";
|
||||
}
|
||||
|
||||
.hg-candidate-box-next::before {
|
||||
content: "►";
|
||||
}
|
||||
|
||||
.hg-candidate-box-next,
|
||||
.hg-candidate-box-prev {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 10px;
|
||||
background: #d0d0d0;
|
||||
color: #969696;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.hg-candidate-box-next {
|
||||
border-top-right-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
}
|
||||
|
||||
.hg-candidate-box-prev {
|
||||
border-top-left-radius: 5px;
|
||||
border-bottom-left-radius: 5px;
|
||||
}
|
||||
|
||||
.hg-candidate-box-btn-active {
|
||||
color: #444;
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* simple-keyboard
|
||||
* Theme: hg-theme-default
|
||||
*/
|
||||
.hg-theme-default {
|
||||
width: 100%;
|
||||
user-select: none;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
touch-action: manipulation;
|
||||
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue",
|
||||
Helvetica, Arial, "Lucida Grande", sans-serif;
|
||||
background-color: #ececec;
|
||||
padding: 5px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button span {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* When using option "useButtonTag" */
|
||||
.hg-theme-default button.hg-button {
|
||||
border-width: 0;
|
||||
outline: 0;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button {
|
||||
display: inline-block;
|
||||
flex-grow: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-row {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-row:not(:last-child) {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-row .hg-button:not(:last-child) {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-row .hg-button-container {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-row > div:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-row .hg-button-container {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button {
|
||||
box-shadow: 0px 0px 3px -1px rgba(0, 0, 0, 0.3);
|
||||
height: 40px;
|
||||
border-radius: 5px;
|
||||
box-sizing: border-box;
|
||||
padding: 5px;
|
||||
background: white;
|
||||
border-bottom: 1px solid #b5b5b5;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-standardBtn {
|
||||
width: 20px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-activeButton {
|
||||
background: #efefef;
|
||||
}
|
||||
|
||||
.hg-theme-default.hg-layout-numeric .hg-button {
|
||||
width: 33.3%;
|
||||
height: 60px;
|
||||
align-items: center;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-button-numpadadd {
|
||||
height: 85px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-button-numpadenter {
|
||||
height: 85px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-button-numpad0 {
|
||||
width: 105px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-button-com {
|
||||
max-width: 85px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-standardBtn.hg-button-at {
|
||||
max-width: 45px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-selectedButton {
|
||||
background: rgba(5, 25, 70, 0.53);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-standardBtn[data-skbtn=".com"] {
|
||||
max-width: 82px;
|
||||
}
|
||||
|
||||
.hg-theme-default .hg-button.hg-standardBtn[data-skbtn="@"] {
|
||||
max-width: 60px;
|
||||
}
|
||||
@@ -1,372 +0,0 @@
|
||||
import Keyboard from '../Keyboard';
|
||||
import { setDOM, clearDOM } from '../../../utils/TestUtility';
|
||||
import CandidateBox from '../CandidateBox';
|
||||
|
||||
beforeEach(() => {
|
||||
setDOM();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clearDOM();
|
||||
});
|
||||
|
||||
it('CandidateBox class will be instantiated by default', () => {
|
||||
document.querySelector("body").innerHTML = `
|
||||
<input class="input" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="simple-keyboard"></div>
|
||||
|
||||
<input class="input2" placeholder="Tap on the virtual keyboard to start" />
|
||||
<div class="keyboard2"></div>
|
||||
`;
|
||||
|
||||
const keyboard1 = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b"
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
const keyboard2 = new Keyboard(".keyboard2", {
|
||||
layout: {
|
||||
default: [
|
||||
"a b"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2"
|
||||
}
|
||||
});
|
||||
|
||||
expect(keyboard1.candidateBox).toBeInstanceOf(CandidateBox);
|
||||
expect(keyboard2.candidateBox).toBeInstanceOf(CandidateBox);
|
||||
|
||||
keyboard1.destroy();
|
||||
keyboard2.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox class will not be instantiated on enableLayoutCandidates: false', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2"
|
||||
},
|
||||
enableLayoutCandidates: false
|
||||
});
|
||||
|
||||
expect(keyboard.candidateBox).toBeNull();
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox will respect layoutCandidatesPageSize', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3 4 5 6"
|
||||
},
|
||||
layoutCandidatesPageSize: 3
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelectorAll("li").length).toBe(3);
|
||||
|
||||
keyboard.getButtonElement("{bksp}").click();
|
||||
keyboard.setOptions({
|
||||
layoutCandidatesPageSize: 6
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelectorAll("li").length).toBe(6);
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox will respect layoutCandidatesPageSize', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3 4 5 6"
|
||||
},
|
||||
layoutCandidatesPageSize: 3
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelectorAll("li").length).toBe(3);
|
||||
|
||||
keyboard.getButtonElement("{bksp}").click();
|
||||
keyboard.setOptions({
|
||||
layoutCandidatesPageSize: 6
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelectorAll("li").length).toBe(6);
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox will reset on layoutCandidates change', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3 4 5 6"
|
||||
},
|
||||
layoutCandidatesPageSize: 3
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("li").textContent).toBe("1");
|
||||
|
||||
keyboard.getButtonElement("{bksp}").click();
|
||||
keyboard.setOptions({
|
||||
layoutCandidates: {
|
||||
a: "s1 s2 s3 s4 s5 s6"
|
||||
}
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("li").textContent).toBe("s1");
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox show will return early if candidateValue is not provided', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
keyboard.candidateBox.renderPage = jest.fn();
|
||||
keyboard.candidateBox.show({
|
||||
candidateValue: null,
|
||||
targetElement: document.createElement("div"),
|
||||
onSelect: () => {}
|
||||
});
|
||||
|
||||
expect(keyboard.candidateBox.renderPage).not.toBeCalled();
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox show will call renderPage if candidateValue is provided', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
keyboard.candidateBox.renderPage = jest.fn();
|
||||
keyboard.candidateBox.show({
|
||||
candidateValue: "a b",
|
||||
targetElement: document.createElement("div"),
|
||||
onSelect: () => {}
|
||||
});
|
||||
|
||||
expect(keyboard.candidateBox.renderPage).toBeCalled();
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox select candidate will work', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3 4 5 6"
|
||||
}
|
||||
});
|
||||
|
||||
let candidateBoxOnItemSelected;
|
||||
const onSelect = jest.fn().mockImplementation((selectedCandidate) => {
|
||||
candidateBoxOnItemSelected(selectedCandidate);
|
||||
keyboard.candidateBox.destroy();
|
||||
});
|
||||
|
||||
const candidateBoxRenderFn = keyboard.candidateBox.renderPage;
|
||||
jest.spyOn(keyboard.candidateBox, "renderPage").mockImplementation((params) => {
|
||||
candidateBoxOnItemSelected = params.onItemSelected;
|
||||
params.onItemSelected = onSelect;
|
||||
candidateBoxRenderFn(params);
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
keyboard.candidateBox.candidateBoxElement.querySelector("li").click();
|
||||
|
||||
expect(onSelect).toBeCalledWith("1", expect.anything());
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox select next and previous page will work', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3 4 5 6"
|
||||
},
|
||||
layoutCandidatesPageSize: 3
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
keyboard.candidateBox.candidateBoxElement.querySelector(".hg-candidate-box-next").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("ul").textContent).toBe("456");
|
||||
|
||||
keyboard.candidateBox.candidateBoxElement.querySelector(".hg-candidate-box-prev").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("ul").textContent).toBe("123");
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox selecting next and previous page when not available will do nothing', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3 4 5 6"
|
||||
},
|
||||
layoutCandidatesPageSize: 3
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
|
||||
keyboard.candidateBox.candidateBoxElement.querySelector(".hg-candidate-box-prev").click();
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("ul").textContent).toBe("123");
|
||||
|
||||
keyboard.candidateBox.candidateBoxElement.querySelector(".hg-candidate-box-next").click();
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("ul").textContent).toBe("456");
|
||||
|
||||
keyboard.candidateBox.candidateBoxElement.querySelector(".hg-candidate-box-next").click();
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("ul").textContent).toBe("456");
|
||||
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox will not show anything when there is no candidates', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3 4 5 6"
|
||||
}
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("b").click();
|
||||
|
||||
expect(keyboard.candidateBox.candidateBoxElement).toBeUndefined();
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox will propose the better matching result, regardless of layoutCandidates order', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3",
|
||||
aa: "6 7 8"
|
||||
}
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("ul").textContent).toBe("123");
|
||||
|
||||
keyboard.getButtonElement("a").click(); // This will get you the 'aa' layoutCandidates instead of the 'a' ones.
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("ul").textContent).toBe("678");
|
||||
|
||||
keyboard.getButtonElement("{bksp}").click();
|
||||
expect(keyboard.candidateBox.candidateBoxElement.querySelector("ul").textContent).toBe("123");
|
||||
|
||||
keyboard.destroy();
|
||||
});
|
||||
|
||||
it('CandidateBox show not be called if keyboard.candidateBox is undefined upon showCandidatesBox call', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3",
|
||||
aa: "6 7 8"
|
||||
}
|
||||
});
|
||||
|
||||
keyboard.candidateBox = null;
|
||||
keyboard.showCandidatesBox();
|
||||
});
|
||||
|
||||
it('CandidateBox selection should trigger onChange', () => {
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"a b {bksp}"
|
||||
]
|
||||
},
|
||||
layoutCandidates: {
|
||||
a: "1 2 3 4 5 6"
|
||||
},
|
||||
onChange: jest.fn(),
|
||||
onChangeAll: jest.fn()
|
||||
});
|
||||
|
||||
let candidateBoxOnItemSelected;
|
||||
|
||||
const onSelect = jest.fn().mockImplementation((selectedCandidate) => {
|
||||
candidateBoxOnItemSelected(selectedCandidate);
|
||||
keyboard.candidateBox.destroy();
|
||||
});
|
||||
|
||||
const candidateBoxRenderFn = keyboard.candidateBox.renderPage;
|
||||
|
||||
jest.spyOn(keyboard.candidateBox, "renderPage").mockImplementation((params) => {
|
||||
candidateBoxOnItemSelected = params.onItemSelected;
|
||||
params.onItemSelected = onSelect;
|
||||
candidateBoxRenderFn(params);
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("a").click();
|
||||
keyboard.candidateBox.candidateBoxElement.querySelector("li").click();
|
||||
|
||||
expect(keyboard.options.onChange.mock.calls[0][0]).toBe("a");
|
||||
expect(keyboard.options.onChangeAll.mock.calls[0][0]).toMatchObject({"default": "a"});
|
||||
|
||||
expect(keyboard.options.onChange.mock.calls[1][0]).toBe("1");
|
||||
expect(keyboard.options.onChangeAll.mock.calls[1][0]).toMatchObject({"default": "1"});
|
||||
keyboard.destroy();
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
import Keyboard from './components/Keyboard';
|
||||
export default Keyboard;
|
||||
@@ -1,3 +0,0 @@
|
||||
import "./polyfills";
|
||||
import SimpleKeyboard from "./components/Keyboard";
|
||||
export default SimpleKeyboard;
|
||||
@@ -1,264 +0,0 @@
|
||||
/* eslint-disable no-unused-vars */
|
||||
import SimpleKeyboard from "./components/Keyboard";
|
||||
import Utilities from "./services/Utilities";
|
||||
|
||||
export interface KeyboardLayoutObject {
|
||||
[key: string]: string[];
|
||||
}
|
||||
|
||||
export type KeyboardButtonTheme = {
|
||||
class: string;
|
||||
buttons: string;
|
||||
} | null;
|
||||
|
||||
export interface KeyboardButtonAttributes {
|
||||
attribute: string;
|
||||
value: string;
|
||||
buttons: string;
|
||||
}
|
||||
|
||||
export interface KeyboardInput {
|
||||
[key: string]: string
|
||||
}
|
||||
|
||||
export type KeyboardParams = [KeyboardOptions] | [string | HTMLDivElement, KeyboardOptions];
|
||||
|
||||
export type CandidateBoxParams = {
|
||||
utilities: Utilities
|
||||
}
|
||||
|
||||
export type CandidateBoxShowParams = {
|
||||
candidateValue: string,
|
||||
targetElement: KeyboardElement,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
onSelect: (selectedCandidate: string, e: MouseEvent) => void
|
||||
}
|
||||
|
||||
export type CandidateBoxRenderParams = {
|
||||
candidateListPages: string[][],
|
||||
targetElement: KeyboardElement,
|
||||
pageIndex: number;
|
||||
nbPages: number;
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
onItemSelected: (selectedCandidate: string, e: MouseEvent) => void
|
||||
}
|
||||
|
||||
export type KeyboardElement = HTMLDivElement | HTMLButtonElement;
|
||||
export type KeyboardHandlerEvent = any;
|
||||
|
||||
export interface KeyboardButtonElements {
|
||||
[key: string]: KeyboardElement[]
|
||||
}
|
||||
|
||||
export interface UtilitiesParams {
|
||||
getOptions: () => KeyboardOptions;
|
||||
getCaretPosition: () => number | null;
|
||||
getCaretPositionEnd: () => number | null;
|
||||
dispatch: any;
|
||||
}
|
||||
|
||||
export interface PhysicalKeyboardParams {
|
||||
getOptions: () => KeyboardOptions;
|
||||
dispatch: any;
|
||||
}
|
||||
|
||||
export interface KeyboardOptions {
|
||||
/**
|
||||
* Modify the keyboard layout.
|
||||
*/
|
||||
layout?: KeyboardLayoutObject;
|
||||
|
||||
/**
|
||||
* Specifies which layout should be used.
|
||||
*/
|
||||
layoutName?: string;
|
||||
|
||||
/**
|
||||
* Replaces variable buttons (such as `{bksp}`) with a human-friendly name (e.g.: `backspace`).
|
||||
*/
|
||||
display?: { [button: string]: string };
|
||||
|
||||
/**
|
||||
* By default, when you set the display property, you replace the default one. This setting merges them instead.
|
||||
*/
|
||||
mergeDisplay?: boolean;
|
||||
|
||||
/**
|
||||
* A prop to add your own css classes to the keyboard wrapper. You can add multiple classes separated by a space.
|
||||
*/
|
||||
theme?: string;
|
||||
|
||||
/**
|
||||
* A prop to add your own css classes to one or several buttons.
|
||||
*/
|
||||
buttonTheme?: KeyboardButtonTheme[];
|
||||
|
||||
/**
|
||||
* A prop to add your own attributes to one or several buttons.
|
||||
*/
|
||||
buttonAttributes?: KeyboardButtonAttributes[];
|
||||
|
||||
/**
|
||||
* Runs a `console.log` every time a key is pressed. Displays the buttons pressed and the current input.
|
||||
*/
|
||||
debug?: boolean;
|
||||
|
||||
/**
|
||||
* Specifies whether clicking the "ENTER" button will input a newline (`\n`) or not.
|
||||
*/
|
||||
newLineOnEnter?: boolean;
|
||||
|
||||
/**
|
||||
* Specifies whether clicking the "TAB" button will input a tab character (`\t`) or not.
|
||||
*/
|
||||
tabCharOnTab?: boolean;
|
||||
|
||||
/**
|
||||
* Allows you to use a single simple-keyboard instance for several inputs.
|
||||
*/
|
||||
inputName?: string;
|
||||
|
||||
/**
|
||||
* `number`: Restrains all of simple-keyboard inputs to a certain length. This should be used in addition to the input element’s maxlengthattribute.
|
||||
*
|
||||
* `{ [inputName: string]: number }`: Restrains simple-keyboard’s individual inputs to a certain length. This should be used in addition to the input element’s maxlengthattribute.
|
||||
*/
|
||||
maxLength?: any;
|
||||
|
||||
/**
|
||||
* When set to true, this option synchronizes the internal input of every simple-keyboard instance.
|
||||
*/
|
||||
syncInstanceInputs?: boolean;
|
||||
|
||||
/**
|
||||
* Enable highlighting of keys pressed on physical keyboard.
|
||||
*/
|
||||
physicalKeyboardHighlight?: boolean;
|
||||
|
||||
/**
|
||||
* Calls handler for a button highlighted by physicalKeyboardHighlight
|
||||
* In other words, this calls keyboard.handleButtonClicked(buttonName) on the highlighted button
|
||||
*/
|
||||
physicalKeyboardHighlightPress?: boolean;
|
||||
|
||||
/**
|
||||
* Trigger click on a button's element when using physicalKeyboardHighlightPress
|
||||
* In other words, this calls button.click() on the highlighted button
|
||||
*/
|
||||
physicalKeyboardHighlightPressUseClick?: boolean;
|
||||
|
||||
/**
|
||||
* Define the text color that the physical keyboard highlighted key should have.
|
||||
*/
|
||||
physicalKeyboardHighlightTextColor?: string;
|
||||
|
||||
/**
|
||||
* Define the background color that the physical keyboard highlighted key should have.
|
||||
*/
|
||||
physicalKeyboardHighlightBgColor?: string;
|
||||
|
||||
/**
|
||||
* Calling preventDefault for the mousedown events keeps the focus on the input.
|
||||
*/
|
||||
preventMouseDownDefault?: boolean;
|
||||
|
||||
/**
|
||||
* Calling preventDefault for the mouseup events.
|
||||
*/
|
||||
preventMouseUpDefault?: boolean;
|
||||
|
||||
/**
|
||||
* Stops pointer down events on simple-keyboard buttons from bubbling to parent elements.
|
||||
*/
|
||||
stopMouseDownPropagation?: boolean;
|
||||
|
||||
/**
|
||||
* Stops pointer up events on simple-keyboard buttons from bubbling to parent elements.
|
||||
*/
|
||||
stopMouseUpPropagation?: boolean;
|
||||
|
||||
/**
|
||||
* Render buttons as a button element instead of a div element.
|
||||
*/
|
||||
useButtonTag?: boolean;
|
||||
|
||||
/**
|
||||
* A prop to ensure characters are always be added/removed at the end of the string.
|
||||
*/
|
||||
disableCaretPositioning?: boolean;
|
||||
|
||||
/**
|
||||
* Restrains input(s) change to the defined regular expression pattern.
|
||||
*/
|
||||
inputPattern?: any;
|
||||
|
||||
/**
|
||||
* Instructs simple-keyboard to use touch events instead of click events.
|
||||
*/
|
||||
useTouchEvents?: boolean;
|
||||
|
||||
/**
|
||||
* Enable useTouchEvents automatically when touch device is detected.
|
||||
*/
|
||||
autoUseTouchEvents?: boolean;
|
||||
|
||||
/**
|
||||
* Opt out of PointerEvents handling, falling back to the prior mouse event logic.
|
||||
*/
|
||||
useMouseEvents?: boolean;
|
||||
|
||||
/**
|
||||
* Disable button hold action.
|
||||
*/
|
||||
disableButtonHold?: boolean;
|
||||
|
||||
/**
|
||||
* Adds unicode right-to-left control characters to input return values.
|
||||
*/
|
||||
rtl?: boolean;
|
||||
|
||||
/**
|
||||
* Enable input method editor candidate list support.
|
||||
*/
|
||||
enableLayoutCandidates?: boolean;
|
||||
|
||||
/**
|
||||
* Character suggestions to be shown on certain key presses
|
||||
*/
|
||||
layoutCandidates?: { [key: string]: string };
|
||||
|
||||
/**
|
||||
* Exclude buttons from layout
|
||||
*/
|
||||
excludeFromLayout?: { [key: string]: string[] };
|
||||
|
||||
/**
|
||||
* Determine size of layout candidate list
|
||||
*/
|
||||
layoutCandidatesPageSize?: number;
|
||||
|
||||
/**
|
||||
* Executes the callback function every time simple-keyboard is rendered (e.g: when you change layouts).
|
||||
*/
|
||||
onRender?: (instance?: SimpleKeyboard) => void;
|
||||
|
||||
/**
|
||||
* Executes the callback function once simple-keyboard is rendered for the first time (on initialization).
|
||||
*/
|
||||
onInit?: (instance?: SimpleKeyboard) => void;
|
||||
|
||||
/**
|
||||
* Retrieves the current input
|
||||
*/
|
||||
onChange?: (input: string, e?: MouseEvent) => any;
|
||||
|
||||
/**
|
||||
* Retrieves all inputs
|
||||
*/
|
||||
onChangeAll?: (inputObj: KeyboardInput, e?: MouseEvent) => any;
|
||||
|
||||
/**
|
||||
* Module options can have any format
|
||||
*/
|
||||
[name: string]: any;
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
// element.remove() polyfill
|
||||
if (typeof Element !== "undefined" && !("remove" in Element.prototype)) {
|
||||
Element.prototype["remove"] = function () {
|
||||
if (this.parentNode) {
|
||||
this.parentNode.removeChild(this);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
* classList.js: Cross-browser full element.classList implementation.
|
||||
* 1.2.20171210
|
||||
*
|
||||
* By Eli Grey, http://eligrey.com
|
||||
* License: Dedicated to the public domain.
|
||||
* See https://github.com/eligrey/classList.js/blob/master/LICENSE.md
|
||||
*/
|
||||
if (typeof self !== "undefined" && "document" in self) {
|
||||
// Full polyfill for browsers with no classList support
|
||||
// Including IE < Edge missing SVGElement.classList
|
||||
if (
|
||||
!("classList" in document.createElement("_")) ||
|
||||
(document.createElementNS &&
|
||||
!(
|
||||
"classList" in
|
||||
document.createElementNS("http://www.w3.org/2000/svg", "g")
|
||||
))
|
||||
) {
|
||||
(function (view) {
|
||||
"use strict";
|
||||
|
||||
if (!("Element" in view)) return;
|
||||
|
||||
var classListProp = "classList",
|
||||
protoProp = "prototype",
|
||||
elemCtrProto = view.Element[protoProp],
|
||||
objCtr = Object,
|
||||
strTrim =
|
||||
String[protoProp].trim ||
|
||||
function () {
|
||||
return this.replace(/^\s+|\s+$/g, "");
|
||||
},
|
||||
arrIndexOf =
|
||||
Array[protoProp].indexOf ||
|
||||
function (item) {
|
||||
var i = 0,
|
||||
len = this.length;
|
||||
for (; i < len; i++) {
|
||||
if (i in this && this[i] === item) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
},
|
||||
// Vendors: please allow content code to instantiate DOMExceptions
|
||||
DOMEx = function (type, message) {
|
||||
this.name = type;
|
||||
this.code = DOMException[type];
|
||||
this.message = message;
|
||||
},
|
||||
checkTokenAndGetIndex = function (classList, token) {
|
||||
if (token === "") {
|
||||
throw new DOMEx("SYNTAX_ERR", "The token must not be empty.");
|
||||
}
|
||||
if (/\s/.test(token)) {
|
||||
throw new DOMEx(
|
||||
"INVALID_CHARACTER_ERR",
|
||||
"The token must not contain space characters."
|
||||
);
|
||||
}
|
||||
return arrIndexOf.call(classList, token);
|
||||
},
|
||||
ClassList = function (elem) {
|
||||
var trimmedClasses = strTrim.call(elem.getAttribute("class") || ""),
|
||||
classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [],
|
||||
i = 0,
|
||||
len = classes.length;
|
||||
for (; i < len; i++) {
|
||||
this.push(classes[i]);
|
||||
}
|
||||
this._updateClassName = function () {
|
||||
elem.setAttribute("class", this.toString());
|
||||
};
|
||||
},
|
||||
classListProto = (ClassList[protoProp] = []),
|
||||
classListGetter = function () {
|
||||
return new ClassList(this);
|
||||
};
|
||||
// Most DOMException implementations don't allow calling DOMException's toString()
|
||||
// on non-DOMExceptions. Error's toString() is sufficient here.
|
||||
DOMEx[protoProp] = Error[protoProp];
|
||||
classListProto.item = function (i) {
|
||||
return this[i] || null;
|
||||
};
|
||||
classListProto.contains = function (token) {
|
||||
return ~checkTokenAndGetIndex(this, token + "");
|
||||
};
|
||||
classListProto.add = function () {
|
||||
var tokens = arguments,
|
||||
i = 0,
|
||||
l = tokens.length,
|
||||
token,
|
||||
updated = false;
|
||||
do {
|
||||
token = tokens[i] + "";
|
||||
if (!~checkTokenAndGetIndex(this, token)) {
|
||||
this.push(token);
|
||||
updated = true;
|
||||
}
|
||||
} while (++i < l);
|
||||
|
||||
if (updated) {
|
||||
this._updateClassName();
|
||||
}
|
||||
};
|
||||
classListProto.remove = function () {
|
||||
var tokens = arguments,
|
||||
i = 0,
|
||||
l = tokens.length,
|
||||
token,
|
||||
updated = false,
|
||||
index;
|
||||
do {
|
||||
token = tokens[i] + "";
|
||||
index = checkTokenAndGetIndex(this, token);
|
||||
while (~index) {
|
||||
this.splice(index, 1);
|
||||
updated = true;
|
||||
index = checkTokenAndGetIndex(this, token);
|
||||
}
|
||||
} while (++i < l);
|
||||
|
||||
if (updated) {
|
||||
this._updateClassName();
|
||||
}
|
||||
};
|
||||
classListProto.toggle = function (token, force) {
|
||||
var result = this.contains(token),
|
||||
method = result
|
||||
? force !== true && "remove"
|
||||
: force !== false && "add";
|
||||
if (method) {
|
||||
this[method](token);
|
||||
}
|
||||
|
||||
if (force === true || force === false) {
|
||||
return force;
|
||||
} else {
|
||||
return !result;
|
||||
}
|
||||
};
|
||||
classListProto.replace = function (token, replacement_token) {
|
||||
var index = checkTokenAndGetIndex(token + "");
|
||||
if (~index) {
|
||||
this.splice(index, 1, replacement_token);
|
||||
this._updateClassName();
|
||||
}
|
||||
};
|
||||
classListProto.toString = function () {
|
||||
return this.join(" ");
|
||||
};
|
||||
|
||||
if (objCtr.defineProperty) {
|
||||
var classListPropDesc = {
|
||||
get: classListGetter,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
};
|
||||
try {
|
||||
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
|
||||
} catch (ex) {
|
||||
// IE 8 doesn't support enumerable:true
|
||||
// adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36
|
||||
// modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected
|
||||
if (ex.number === undefined || ex.number === -0x7ff5ec54) {
|
||||
classListPropDesc.enumerable = false;
|
||||
objCtr.defineProperty(
|
||||
elemCtrProto,
|
||||
classListProp,
|
||||
classListPropDesc
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if (objCtr[protoProp].__defineGetter__) {
|
||||
elemCtrProto.__defineGetter__(classListProp, classListGetter);
|
||||
}
|
||||
})(self);
|
||||
}
|
||||
|
||||
// There is full or partial native classList support, so just check if we need
|
||||
// to normalize the add/remove and toggle APIs.
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var testElement = document.createElement("_");
|
||||
|
||||
testElement.classList.add("c1", "c2");
|
||||
|
||||
// Polyfill for IE 10/11 and Firefox <26, where classList.add and
|
||||
// classList.remove exist but support only one argument at a time.
|
||||
if (!testElement.classList.contains("c2")) {
|
||||
var createMethod = function (method) {
|
||||
var original = DOMTokenList.prototype[method];
|
||||
|
||||
DOMTokenList.prototype[method] = function (token) {
|
||||
var i,
|
||||
len = arguments.length;
|
||||
|
||||
for (i = 0; i < len; i++) {
|
||||
token = arguments[i];
|
||||
original.call(this, token);
|
||||
}
|
||||
};
|
||||
};
|
||||
createMethod("add");
|
||||
createMethod("remove");
|
||||
}
|
||||
|
||||
testElement.classList.toggle("c3", false);
|
||||
|
||||
// Polyfill for IE 10 and Firefox <24, where classList.toggle does not
|
||||
// support the second argument.
|
||||
if (testElement.classList.contains("c3")) {
|
||||
var _toggle = DOMTokenList.prototype.toggle;
|
||||
|
||||
DOMTokenList.prototype.toggle = function (token, force) {
|
||||
if (1 in arguments && !this.contains(token) === !force) {
|
||||
return force;
|
||||
} else {
|
||||
return _toggle.call(this, token);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// replace() polyfill
|
||||
if (!("replace" in document.createElement("_").classList)) {
|
||||
DOMTokenList.prototype.replace = function (token, replacement_token) {
|
||||
var tokens = this.toString().split(" "),
|
||||
index = tokens.indexOf(token + "");
|
||||
if (~index) {
|
||||
tokens = tokens.slice(index);
|
||||
this.remove.apply(this, tokens);
|
||||
this.add(replacement_token);
|
||||
this.add.apply(this, tokens.slice(1));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
testElement = null;
|
||||
})();
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default KeyboardLayout;
|
||||
@@ -1,18 +0,0 @@
|
||||
export const 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}",
|
||||
],
|
||||
};
|
||||
};
|
||||
@@ -1,211 +0,0 @@
|
||||
import { KeyboardOptions, PhysicalKeyboardParams } from "../interfaces";
|
||||
import Utilities from "../services/Utilities";
|
||||
|
||||
/**
|
||||
* Physical Keyboard Service
|
||||
*/
|
||||
class PhysicalKeyboard {
|
||||
getOptions: () => KeyboardOptions;
|
||||
dispatch: any;
|
||||
|
||||
/**
|
||||
* Creates an instance of the PhysicalKeyboard service
|
||||
*/
|
||||
constructor({ dispatch, getOptions }: PhysicalKeyboardParams) {
|
||||
/**
|
||||
* @type {object} A simple-keyboard instance
|
||||
*/
|
||||
this.dispatch = dispatch;
|
||||
this.getOptions = getOptions;
|
||||
|
||||
/**
|
||||
* Bindings
|
||||
*/
|
||||
Utilities.bindMethods(PhysicalKeyboard, this);
|
||||
}
|
||||
|
||||
handleHighlightKeyDown(event: KeyboardEvent) {
|
||||
const options = this.getOptions();
|
||||
const buttonPressed = this.getSimpleKeyboardLayoutKey(event);
|
||||
|
||||
this.dispatch((instance: any) => {
|
||||
const standardButtonPressed = instance.getButtonElement(buttonPressed);
|
||||
const functionButtonPressed = instance.getButtonElement(
|
||||
`{${buttonPressed}}`
|
||||
);
|
||||
let buttonDOM;
|
||||
let buttonName;
|
||||
|
||||
if (standardButtonPressed) {
|
||||
buttonDOM = standardButtonPressed;
|
||||
buttonName = buttonPressed;
|
||||
} else if (functionButtonPressed) {
|
||||
buttonDOM = functionButtonPressed;
|
||||
buttonName = `{${buttonPressed}}`;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (buttonDOM) {
|
||||
buttonDOM.style.backgroundColor =
|
||||
options.physicalKeyboardHighlightBgColor || "#dadce4";
|
||||
buttonDOM.style.color =
|
||||
options.physicalKeyboardHighlightTextColor || "black";
|
||||
|
||||
if (options.physicalKeyboardHighlightPress) {
|
||||
if (options.physicalKeyboardHighlightPressUseClick) {
|
||||
buttonDOM.click();
|
||||
} else {
|
||||
instance.handleButtonClicked(buttonName, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
handleHighlightKeyUp(event: KeyboardEvent) {
|
||||
const buttonPressed = this.getSimpleKeyboardLayoutKey(event);
|
||||
|
||||
this.dispatch((instance: any) => {
|
||||
const buttonDOM =
|
||||
instance.getButtonElement(buttonPressed) ||
|
||||
instance.getButtonElement(`{${buttonPressed}}`);
|
||||
|
||||
if (buttonDOM && buttonDOM.removeAttribute) {
|
||||
buttonDOM.removeAttribute("style");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a KeyboardEvent's "key.code" string into a simple-keyboard layout format
|
||||
* @param {object} event The KeyboardEvent
|
||||
*/
|
||||
getSimpleKeyboardLayoutKey(event: KeyboardEvent) {
|
||||
let output = "";
|
||||
const keyId = event.code || event.key || this.keyCodeToKey(event?.keyCode);
|
||||
|
||||
if (
|
||||
keyId?.includes("Numpad") ||
|
||||
keyId?.includes("Shift") ||
|
||||
keyId?.includes("Space") ||
|
||||
keyId?.includes("Backspace") ||
|
||||
keyId?.includes("Control") ||
|
||||
keyId?.includes("Alt") ||
|
||||
keyId?.includes("Meta")
|
||||
) {
|
||||
output = event.code || "";
|
||||
} else {
|
||||
output = event.key || this.keyCodeToKey(event?.keyCode) || "";
|
||||
}
|
||||
|
||||
return output.length > 1 ? output?.toLowerCase() : output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve key from keyCode
|
||||
*/
|
||||
keyCodeToKey(keyCode: number) {
|
||||
return {
|
||||
8: "Backspace",
|
||||
9: "Tab",
|
||||
13: "Enter",
|
||||
16: "Shift",
|
||||
17: "Ctrl",
|
||||
18: "Alt",
|
||||
19: "Pause",
|
||||
20: "CapsLock",
|
||||
27: "Esc",
|
||||
32: "Space",
|
||||
33: "PageUp",
|
||||
34: "PageDown",
|
||||
35: "End",
|
||||
36: "Home",
|
||||
37: "ArrowLeft",
|
||||
38: "ArrowUp",
|
||||
39: "ArrowRight",
|
||||
40: "ArrowDown",
|
||||
45: "Insert",
|
||||
46: "Delete",
|
||||
48: "0",
|
||||
49: "1",
|
||||
50: "2",
|
||||
51: "3",
|
||||
52: "4",
|
||||
53: "5",
|
||||
54: "6",
|
||||
55: "7",
|
||||
56: "8",
|
||||
57: "9",
|
||||
65: "A",
|
||||
66: "B",
|
||||
67: "C",
|
||||
68: "D",
|
||||
69: "E",
|
||||
70: "F",
|
||||
71: "G",
|
||||
72: "H",
|
||||
73: "I",
|
||||
74: "J",
|
||||
75: "K",
|
||||
76: "L",
|
||||
77: "M",
|
||||
78: "N",
|
||||
79: "O",
|
||||
80: "P",
|
||||
81: "Q",
|
||||
82: "R",
|
||||
83: "S",
|
||||
84: "T",
|
||||
85: "U",
|
||||
86: "V",
|
||||
87: "W",
|
||||
88: "X",
|
||||
89: "Y",
|
||||
90: "Z",
|
||||
91: "Meta",
|
||||
96: "Numpad0",
|
||||
97: "Numpad1",
|
||||
98: "Numpad2",
|
||||
99: "Numpad3",
|
||||
100: "Numpad4",
|
||||
101: "Numpad5",
|
||||
102: "Numpad6",
|
||||
103: "Numpad7",
|
||||
104: "Numpad8",
|
||||
105: "Numpad9",
|
||||
106: "NumpadMultiply",
|
||||
107: "NumpadAdd",
|
||||
109: "NumpadSubtract",
|
||||
110: "NumpadDecimal",
|
||||
111: "NumpadDivide",
|
||||
112: "F1",
|
||||
113: "F2",
|
||||
114: "F3",
|
||||
115: "F4",
|
||||
116: "F5",
|
||||
117: "F6",
|
||||
118: "F7",
|
||||
119: "F8",
|
||||
120: "F9",
|
||||
121: "F10",
|
||||
122: "F11",
|
||||
123: "F12",
|
||||
144: "NumLock",
|
||||
145: "ScrollLock",
|
||||
186: ";",
|
||||
187: "=",
|
||||
188: ",",
|
||||
189: "-",
|
||||
190: ".",
|
||||
191: "/",
|
||||
192: "`",
|
||||
219: "[",
|
||||
220: "\\",
|
||||
221: "]",
|
||||
222: "'",
|
||||
}[keyCode];
|
||||
}
|
||||
}
|
||||
|
||||
export default PhysicalKeyboard;
|
||||
@@ -0,0 +1,92 @@
|
||||
class Utilities {
|
||||
static 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
|
||||
output = '';
|
||||
|
||||
return output ? ` hg-button-${output}` : '';
|
||||
}
|
||||
|
||||
static getButtonClass = button => {
|
||||
let buttonTypeClass = (button.includes("{") && button !== '{//}') ? "functionBtn" : "standardBtn";
|
||||
let buttonWithoutBraces = button.replace("{", "").replace("}", "");
|
||||
|
||||
let buttonNormalized =
|
||||
buttonTypeClass === "standardBtn" ?
|
||||
Utilities.normalizeString(buttonWithoutBraces) : ` hg-button-${buttonWithoutBraces}`;
|
||||
|
||||
return `hg-${buttonTypeClass}${buttonNormalized}`;
|
||||
}
|
||||
|
||||
static getDefaultDiplay(){
|
||||
return {
|
||||
'{bksp}': 'delete',
|
||||
'{enter}': '< enter',
|
||||
'{shift}': 'shift',
|
||||
'{s}': 'shift',
|
||||
'{tab}': 'tab',
|
||||
'{lock}': 'caps',
|
||||
'{accept}': 'Submit',
|
||||
'{space}': ' ',
|
||||
'{//}': ' '
|
||||
};
|
||||
}
|
||||
|
||||
static getButtonDisplayName = (button, display) => {
|
||||
display = display || Utilities.getDefaultDiplay();
|
||||
return display[button] || button;
|
||||
}
|
||||
|
||||
static getUpdatedInput = (button, input, options) => {
|
||||
let output = input;
|
||||
let newLineOnEnter = options.newLineOnEnter;
|
||||
|
||||
if(button === "{bksp}" && output.length > 0)
|
||||
output = output.slice(0, -1);
|
||||
else if(button === "{space}")
|
||||
output = output + ' ';
|
||||
else if(button === "{tab}")
|
||||
output = output + "\t";
|
||||
else if(button === "{enter}" && newLineOnEnter)
|
||||
output = output + "\n";
|
||||
else if(!button.includes("{") && !button.includes("{"))
|
||||
output = output + button;
|
||||
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
export default Utilities;
|
||||
@@ -1,541 +0,0 @@
|
||||
import { KeyboardInput } from "./../interfaces";
|
||||
import { KeyboardOptions, UtilitiesParams } from "../interfaces";
|
||||
|
||||
/**
|
||||
* Utility Service
|
||||
*/
|
||||
class Utilities {
|
||||
getOptions: () => KeyboardOptions;
|
||||
getCaretPosition: () => number | null;
|
||||
getCaretPositionEnd: () => number | null;
|
||||
dispatch: any;
|
||||
maxLengthReached!: boolean;
|
||||
|
||||
/**
|
||||
* Creates an instance of the Utility service
|
||||
*/
|
||||
constructor({
|
||||
getOptions,
|
||||
getCaretPosition,
|
||||
getCaretPositionEnd,
|
||||
dispatch,
|
||||
}: UtilitiesParams) {
|
||||
this.getOptions = getOptions;
|
||||
this.getCaretPosition = getCaretPosition;
|
||||
this.getCaretPositionEnd = getCaretPositionEnd;
|
||||
this.dispatch = dispatch;
|
||||
|
||||
/**
|
||||
* Bindings
|
||||
*/
|
||||
Utilities.bindMethods(Utilities, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve button type
|
||||
*
|
||||
* @param {string} button The button's layout name
|
||||
* @return {string} The button type
|
||||
*/
|
||||
getButtonType(button: string): string {
|
||||
return button.includes("{") && button.includes("}") && button !== "{//}"
|
||||
? "functionBtn"
|
||||
: "standardBtn";
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds default classes to a given button
|
||||
*
|
||||
* @param {string} button The button's layout name
|
||||
* @return {string} The classes to be added to the button
|
||||
*/
|
||||
getButtonClass(button: string): string {
|
||||
const buttonTypeClass = this.getButtonType(button);
|
||||
const buttonWithoutBraces = button.replace("{", "").replace("}", "");
|
||||
let buttonNormalized = "";
|
||||
|
||||
if (buttonTypeClass !== "standardBtn")
|
||||
buttonNormalized = ` hg-button-${buttonWithoutBraces}`;
|
||||
|
||||
return `hg-${buttonTypeClass}${buttonNormalized}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default button display labels
|
||||
*/
|
||||
getDefaultDiplay() {
|
||||
return {
|
||||
"{bksp}": "backspace",
|
||||
"{backspace}": "backspace",
|
||||
"{enter}": "< enter",
|
||||
"{shift}": "shift",
|
||||
"{shiftleft}": "shift",
|
||||
"{shiftright}": "shift",
|
||||
"{alt}": "alt",
|
||||
"{s}": "shift",
|
||||
"{tab}": "tab",
|
||||
"{lock}": "caps",
|
||||
"{capslock}": "caps",
|
||||
"{accept}": "Submit",
|
||||
"{space}": " ",
|
||||
"{//}": " ",
|
||||
"{esc}": "esc",
|
||||
"{escape}": "esc",
|
||||
"{f1}": "f1",
|
||||
"{f2}": "f2",
|
||||
"{f3}": "f3",
|
||||
"{f4}": "f4",
|
||||
"{f5}": "f5",
|
||||
"{f6}": "f6",
|
||||
"{f7}": "f7",
|
||||
"{f8}": "f8",
|
||||
"{f9}": "f9",
|
||||
"{f10}": "f10",
|
||||
"{f11}": "f11",
|
||||
"{f12}": "f12",
|
||||
"{numpaddivide}": "/",
|
||||
"{numlock}": "lock",
|
||||
"{arrowup}": "↑",
|
||||
"{arrowleft}": "←",
|
||||
"{arrowdown}": "↓",
|
||||
"{arrowright}": "→",
|
||||
"{prtscr}": "print",
|
||||
"{scrolllock}": "scroll",
|
||||
"{pause}": "pause",
|
||||
"{insert}": "ins",
|
||||
"{home}": "home",
|
||||
"{pageup}": "up",
|
||||
"{delete}": "del",
|
||||
"{forwarddelete}": "del",
|
||||
"{end}": "end",
|
||||
"{pagedown}": "down",
|
||||
"{numpadmultiply}": "*",
|
||||
"{numpadsubtract}": "-",
|
||||
"{numpadadd}": "+",
|
||||
"{numpadenter}": "enter",
|
||||
"{period}": ".",
|
||||
"{numpaddecimal}": ".",
|
||||
"{numpad0}": "0",
|
||||
"{numpad1}": "1",
|
||||
"{numpad2}": "2",
|
||||
"{numpad3}": "3",
|
||||
"{numpad4}": "4",
|
||||
"{numpad5}": "5",
|
||||
"{numpad6}": "6",
|
||||
"{numpad7}": "7",
|
||||
"{numpad8}": "8",
|
||||
"{numpad9}": "9",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Returns the display (label) name for a given button
|
||||
*
|
||||
* @param {string} button The button's layout name
|
||||
* @param {object} display The provided display option
|
||||
* @param {boolean} mergeDisplay Whether the provided param value should be merged with the default one.
|
||||
*/
|
||||
getButtonDisplayName(
|
||||
button: string,
|
||||
display: KeyboardOptions["display"],
|
||||
mergeDisplay: boolean
|
||||
) {
|
||||
if (mergeDisplay) {
|
||||
display = Object.assign({}, this.getDefaultDiplay(), display);
|
||||
} else {
|
||||
display = display || this.getDefaultDiplay();
|
||||
}
|
||||
|
||||
return display[button] || button;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the updated input resulting from clicking a given button
|
||||
*
|
||||
* @param {string} button The button's layout name
|
||||
* @param {string} input The input string
|
||||
* @param {number} caretPos The cursor's current position
|
||||
* @param {number} caretPosEnd The cursor's current end position
|
||||
* @param {boolean} moveCaret Whether to update simple-keyboard's cursor
|
||||
*/
|
||||
getUpdatedInput(
|
||||
button: string,
|
||||
input: string,
|
||||
caretPos: number,
|
||||
caretPosEnd = caretPos,
|
||||
moveCaret = false
|
||||
) {
|
||||
const options = this.getOptions();
|
||||
const commonParams: [number, number, boolean] = [
|
||||
caretPos,
|
||||
caretPosEnd,
|
||||
moveCaret,
|
||||
];
|
||||
|
||||
let output = input;
|
||||
|
||||
if (
|
||||
(button === "{bksp}" || button === "{backspace}") &&
|
||||
output.length > 0
|
||||
) {
|
||||
output = this.removeAt(output, ...commonParams);
|
||||
} else if (
|
||||
(button === "{delete}" || button === "{forwarddelete}") &&
|
||||
output.length > 0
|
||||
) {
|
||||
output = this.removeForwardsAt(output, ...commonParams);
|
||||
} else if (button === "{space}")
|
||||
output = this.addStringAt(output, " ", ...commonParams);
|
||||
else if (
|
||||
button === "{tab}" &&
|
||||
!(
|
||||
typeof options.tabCharOnTab === "boolean" &&
|
||||
options.tabCharOnTab === false
|
||||
)
|
||||
) {
|
||||
output = this.addStringAt(output, "\t", ...commonParams);
|
||||
} else if (
|
||||
(button === "{enter}" || button === "{numpadenter}") &&
|
||||
options.newLineOnEnter
|
||||
)
|
||||
output = this.addStringAt(output, "\n", ...commonParams);
|
||||
else if (
|
||||
button.includes("numpad") &&
|
||||
Number.isInteger(Number(button[button.length - 2]))
|
||||
) {
|
||||
output = this.addStringAt(
|
||||
output,
|
||||
button[button.length - 2],
|
||||
...commonParams
|
||||
);
|
||||
} else if (button === "{numpaddivide}")
|
||||
output = this.addStringAt(output, "/", ...commonParams);
|
||||
else if (button === "{numpadmultiply}")
|
||||
output = this.addStringAt(output, "*", ...commonParams);
|
||||
else if (button === "{numpadsubtract}")
|
||||
output = this.addStringAt(output, "-", ...commonParams);
|
||||
else if (button === "{numpadadd}")
|
||||
output = this.addStringAt(output, "+", ...commonParams);
|
||||
else if (button === "{numpaddecimal}")
|
||||
output = this.addStringAt(output, ".", ...commonParams);
|
||||
else if (button === "{" || button === "}")
|
||||
output = this.addStringAt(output, button, ...commonParams);
|
||||
else if (!button.includes("{") && !button.includes("}"))
|
||||
output = this.addStringAt(output, button, ...commonParams);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the cursor position by a given amount
|
||||
*
|
||||
* @param {number} length Represents by how many characters the input should be moved
|
||||
* @param {boolean} minus Whether the cursor should be moved to the left or not.
|
||||
*/
|
||||
updateCaretPos(length: number, minus = false) {
|
||||
const newCaretPos = this.updateCaretPosAction(length, minus);
|
||||
|
||||
this.dispatch((instance: any) => {
|
||||
instance.setCaretPosition(newCaretPos);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Action method of updateCaretPos
|
||||
*
|
||||
* @param {number} length Represents by how many characters the input should be moved
|
||||
* @param {boolean} minus Whether the cursor should be moved to the left or not.
|
||||
*/
|
||||
updateCaretPosAction(length: number, minus = false) {
|
||||
const options = this.getOptions();
|
||||
let caretPosition = this.getCaretPosition();
|
||||
|
||||
if (caretPosition != null) {
|
||||
if (minus) {
|
||||
if (caretPosition > 0) caretPosition = caretPosition - length;
|
||||
} else {
|
||||
caretPosition = caretPosition + length;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.debug) {
|
||||
console.log("Caret at:", caretPosition);
|
||||
}
|
||||
|
||||
return caretPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a string to the input at a given position
|
||||
*
|
||||
* @param {string} source The source input
|
||||
* @param {string} str The string to add
|
||||
* @param {number} position The (cursor) position where the string should be added
|
||||
* @param {boolean} moveCaret Whether to update simple-keyboard's cursor
|
||||
*/
|
||||
addStringAt(
|
||||
source: string,
|
||||
str: string,
|
||||
position = source.length,
|
||||
positionEnd = source.length,
|
||||
moveCaret = false
|
||||
) {
|
||||
let output;
|
||||
|
||||
if (!position && position !== 0) {
|
||||
output = source + str;
|
||||
} else {
|
||||
output = [source.slice(0, position), str, source.slice(positionEnd)].join(
|
||||
""
|
||||
);
|
||||
|
||||
/**
|
||||
* Avoid caret position change when maxLength is set
|
||||
*/
|
||||
if (!this.isMaxLengthReached()) {
|
||||
if (moveCaret) this.updateCaretPos(str.length);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the button is a standard button
|
||||
*/
|
||||
isStandardButton = (button: string) =>
|
||||
button && !(button[0] === "{" && button[button.length - 1] === "}");
|
||||
|
||||
/**
|
||||
* Removes an amount of characters before a given position
|
||||
*
|
||||
* @param {string} source The source input
|
||||
* @param {number} position The (cursor) position from where the characters should be removed
|
||||
* @param {boolean} moveCaret Whether to update simple-keyboard's cursor
|
||||
*/
|
||||
removeAt(
|
||||
source: string,
|
||||
position = source.length,
|
||||
positionEnd = source.length,
|
||||
moveCaret = false
|
||||
) {
|
||||
if (position === 0 && positionEnd === 0) {
|
||||
return source;
|
||||
}
|
||||
|
||||
let output;
|
||||
|
||||
if (position === positionEnd) {
|
||||
let prevTwoChars;
|
||||
let emojiMatched;
|
||||
const emojiMatchedReg = /([\uD800-\uDBFF][\uDC00-\uDFFF])/g;
|
||||
|
||||
/**
|
||||
* Emojis are made out of two characters, so we must take a custom approach to trim them.
|
||||
* For more info: https://mathiasbynens.be/notes/javascript-unicode
|
||||
*/
|
||||
if (position && position >= 0) {
|
||||
prevTwoChars = source.substring(position - 2, position);
|
||||
emojiMatched = prevTwoChars.match(emojiMatchedReg);
|
||||
|
||||
if (emojiMatched) {
|
||||
output = source.substr(0, position - 2) + source.substr(position);
|
||||
if (moveCaret) this.updateCaretPos(2, true);
|
||||
} else {
|
||||
output = source.substr(0, position - 1) + source.substr(position);
|
||||
if (moveCaret) this.updateCaretPos(1, true);
|
||||
}
|
||||
} else {
|
||||
prevTwoChars = source.slice(-2);
|
||||
emojiMatched = prevTwoChars.match(emojiMatchedReg);
|
||||
|
||||
if (emojiMatched) {
|
||||
output = source.slice(0, -2);
|
||||
if (moveCaret) this.updateCaretPos(2, true);
|
||||
} else {
|
||||
output = source.slice(0, -1);
|
||||
if (moveCaret) this.updateCaretPos(1, true);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
output = source.slice(0, position) + source.slice(positionEnd);
|
||||
if (moveCaret) {
|
||||
this.dispatch((instance: any) => {
|
||||
instance.setCaretPosition(position);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an amount of characters after a given position
|
||||
*
|
||||
* @param {string} source The source input
|
||||
* @param {number} position The (cursor) position from where the characters should be removed
|
||||
*/
|
||||
removeForwardsAt(
|
||||
source: string,
|
||||
position: number = source.length,
|
||||
positionEnd: number = source.length,
|
||||
moveCaret = false
|
||||
) {
|
||||
if (!source?.length || position === null) {
|
||||
return source;
|
||||
}
|
||||
|
||||
let output;
|
||||
|
||||
if (position === positionEnd) {
|
||||
const emojiMatchedReg = /([\uD800-\uDBFF][\uDC00-\uDFFF])/g;
|
||||
|
||||
/**
|
||||
* Emojis are made out of two characters, so we must take a custom approach to trim them.
|
||||
* For more info: https://mathiasbynens.be/notes/javascript-unicode
|
||||
*/
|
||||
const nextTwoChars = source.substring(position, position + 2);
|
||||
const emojiMatched = nextTwoChars.match(emojiMatchedReg);
|
||||
|
||||
if (emojiMatched) {
|
||||
output = source.substr(0, position) + source.substr(position + 2);
|
||||
} else {
|
||||
output = source.substr(0, position) + source.substr(position + 1);
|
||||
}
|
||||
} else {
|
||||
output = source.slice(0, position) + source.slice(positionEnd);
|
||||
if (moveCaret) {
|
||||
this.dispatch((instance: any) => {
|
||||
instance.setCaretPosition(position);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the maxLength has been reached. This function is called when the maxLength option it set.
|
||||
*
|
||||
* @param {object} inputObj
|
||||
* @param {string} updatedInput
|
||||
*/
|
||||
handleMaxLength(inputObj: KeyboardInput, updatedInput: string) {
|
||||
const options = this.getOptions();
|
||||
const maxLength = options.maxLength;
|
||||
const currentInput = inputObj[options.inputName || "default"];
|
||||
const condition = updatedInput.length - 1 >= maxLength;
|
||||
|
||||
if (
|
||||
/**
|
||||
* If pressing this button won't add more characters
|
||||
* We exit out of this limiter function
|
||||
*/
|
||||
updatedInput.length <= currentInput.length
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Number.isInteger(maxLength)) {
|
||||
if (options.debug) {
|
||||
console.log("maxLength (num) reached:", condition);
|
||||
}
|
||||
|
||||
if (condition) {
|
||||
/**
|
||||
* @type {boolean} Boolean value that shows whether maxLength has been reached
|
||||
*/
|
||||
this.maxLengthReached = true;
|
||||
return true;
|
||||
} else {
|
||||
this.maxLengthReached = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof maxLength === "object") {
|
||||
const condition =
|
||||
updatedInput.length - 1 >= maxLength[options.inputName || "default"];
|
||||
|
||||
if (options.debug) {
|
||||
console.log("maxLength (obj) reached:", condition);
|
||||
}
|
||||
|
||||
if (condition) {
|
||||
this.maxLengthReached = true;
|
||||
return true;
|
||||
} else {
|
||||
this.maxLengthReached = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current value of maxLengthReached
|
||||
*/
|
||||
isMaxLengthReached() {
|
||||
return Boolean(this.maxLengthReached);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a touch device is being used
|
||||
*/
|
||||
isTouchDevice() {
|
||||
return "ontouchstart" in window || navigator.maxTouchPoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether pointer events are supported
|
||||
*/
|
||||
pointerEventsSupported() {
|
||||
return !!window.PointerEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind all methods in a given class
|
||||
*/
|
||||
|
||||
static bindMethods(myClass: any, instance: any) {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
for (const myMethod of Object.getOwnPropertyNames(myClass.prototype)) {
|
||||
const excludeMethod =
|
||||
myMethod === "constructor" || myMethod === "bindMethods";
|
||||
if (!excludeMethod) {
|
||||
instance[myMethod] = instance[myMethod].bind(instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms an arbitrary string to camelCase
|
||||
*
|
||||
* @param {string} str The string to transform.
|
||||
*/
|
||||
camelCase(str: string): string {
|
||||
if (!str) return "";
|
||||
|
||||
return str
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.split(/[.\-_\s]/g)
|
||||
.reduce((str, word) =>
|
||||
word.length ? str + word[0].toUpperCase() + word.slice(1) : str
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split array into chunks
|
||||
*/
|
||||
chunkArray<T>(arr: T[], size: number): T[][] {
|
||||
return [...Array(Math.ceil(arr.length / size))].map((_, i) =>
|
||||
arr.slice(size * i, size + size * i)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reusable empty function
|
||||
*/
|
||||
static noop = () => {};
|
||||
}
|
||||
|
||||
export default Utilities;
|
||||
@@ -1,225 +0,0 @@
|
||||
import Keyboard from '../../components/Keyboard';
|
||||
import { setDOM } from '../../../utils/TestUtility';
|
||||
|
||||
it('PhysicalKeyboard keydown will be handled with physicalKeyboardHighlight', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard keydown will be handled without physicalKeyboardHighlight', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: false
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard keydown will not style non-existent buttons', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
code: "WRONG",
|
||||
key: "WRONG",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard keyup will be handled with physicalKeyboardHighlight', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard keyup will be handle special buttons', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
code: "Shift",
|
||||
key: "Shift",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard keyup will not style non-existent buttons', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: true,
|
||||
debug: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
code: "WRONG",
|
||||
key: "WRONG",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard will work with F1-F12 keys', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: true,
|
||||
debug: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
code: "F12",
|
||||
key: "F12",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard will work with physicalKeyboardHighlightPress', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: true,
|
||||
physicalKeyboardHighlightPress: true,
|
||||
debug: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard will work with physicalKeyboardHighlightPress (touch)', () => {
|
||||
setDOM();
|
||||
|
||||
new Keyboard({
|
||||
physicalKeyboardHighlight: true,
|
||||
physicalKeyboardHighlightPress: true,
|
||||
useTouchEvents: true,
|
||||
debug: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard with physicalKeyboardHighlightPress can trigger noop', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
physicalKeyboardHighlight: true,
|
||||
physicalKeyboardHighlightPress: true,
|
||||
useTouchEvents: true,
|
||||
debug: true
|
||||
});
|
||||
|
||||
keyboard.getButtonElement('f').onmousedown = null;
|
||||
keyboard.getButtonElement('f').onpointerdown = null;
|
||||
keyboard.getButtonElement('f').ontouchstart = null;
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
|
||||
keyboard.getButtonElement('f').onmouseup = null;
|
||||
keyboard.getButtonElement('f').onpointerup = null;
|
||||
keyboard.getButtonElement('f').ontouchend = null;
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
code: "KeyF",
|
||||
key: "f",
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
it('PhysicalKeyboard keyCodeToKey will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
physicalKeyboardHighlight: true
|
||||
});
|
||||
|
||||
expect(keyboard.physicalKeyboard.keyCodeToKey(186)).toBe(";");
|
||||
|
||||
const methodTest = spyOn(keyboard.physicalKeyboard, "keyCodeToKey");
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
keyCode: 186,
|
||||
target: {
|
||||
tagName: "input"
|
||||
}
|
||||
}));
|
||||
|
||||
expect(methodTest).toBeCalledWith(186);
|
||||
});
|
||||
@@ -1,761 +0,0 @@
|
||||
import Keyboard from '../../components/Keyboard';
|
||||
import { setDOM, clearDOM, testLayoutFctButtons } from '../../../utils/TestUtility';
|
||||
|
||||
it('Keyboard mergeDisplay will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
mergeDisplay: true,
|
||||
display: {
|
||||
"q": "qreplaced"
|
||||
}
|
||||
});
|
||||
|
||||
expect(keyboard.getButtonElement("q").querySelector("span").innerHTML).toBe("qreplaced");
|
||||
});
|
||||
|
||||
it('Keyboard function buttons will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
testLayoutFctButtons(keyboard, (fctBtnCount, fctBtnHasOnclickCount) => {
|
||||
expect(fctBtnCount).toBe(fctBtnHasOnclickCount);
|
||||
}, keyboard);
|
||||
});
|
||||
|
||||
it('Keyboard {bksp} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{bksp}", "test");
|
||||
|
||||
expect(output).toBe("tes");
|
||||
});
|
||||
|
||||
it('Keyboard {delete} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{delete}", "test", 1);
|
||||
|
||||
expect(output).toBe("tst");
|
||||
});
|
||||
|
||||
it('Keyboard {space} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{space}", "test");
|
||||
|
||||
expect(output).toBe("test ");
|
||||
});
|
||||
|
||||
it('Keyboard {tab} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{tab}", "test");
|
||||
|
||||
expect(output).toBe("test\t");
|
||||
});
|
||||
|
||||
it('Keyboard {tab} button will work with tabCharOnTab:false', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
tabCharOnTab: false
|
||||
});
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{tab}", "test");
|
||||
|
||||
expect(output).toBe("test");
|
||||
});
|
||||
|
||||
it('Keyboard {enter} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{enter}", "test");
|
||||
|
||||
expect(output).toBe("test");
|
||||
});
|
||||
|
||||
it('Keyboard {enter} button will work with newLineOnEnter:true', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
newLineOnEnter: true
|
||||
});
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{enter}", "test");
|
||||
|
||||
expect(output).toBe("test\n");
|
||||
});
|
||||
|
||||
it('Keyboard {numpadX} buttons will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
for(let i = 0;i<=9;i++){
|
||||
const output = keyboard.utilities.getUpdatedInput(`{numpad${i}}`, "test");
|
||||
expect(output).toBe(`test${i}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('Keyboard {numpaddivide} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{numpaddivide}", "test");
|
||||
|
||||
expect(output).toBe("test/");
|
||||
});
|
||||
|
||||
it('Keyboard {numpadmultiply} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{numpadmultiply}", "test");
|
||||
|
||||
expect(output).toBe("test*");
|
||||
});
|
||||
|
||||
it('Keyboard {numpadsubtract} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{numpadsubtract}", "test");
|
||||
|
||||
expect(output).toBe("test-");
|
||||
});
|
||||
|
||||
it('Keyboard {numpadadd} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{numpadadd}", "test");
|
||||
|
||||
expect(output).toBe("test+");
|
||||
});
|
||||
|
||||
it('Keyboard {numpadadd} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{numpadadd}", "test");
|
||||
|
||||
expect(output).toBe("test+");
|
||||
});
|
||||
|
||||
it('Keyboard {numpaddecimal} button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{numpaddecimal}", "test");
|
||||
|
||||
expect(output).toBe("test.");
|
||||
});
|
||||
|
||||
it('Keyboard custom function buttons will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
layout: {
|
||||
default: [
|
||||
"{randombuttontest}"
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{randombuttontest}", "test");
|
||||
|
||||
expect(output).toBe("test");
|
||||
expect(keyboard.getButtonElement("{randombuttontest}").onclick).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Keyboard "{" button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("{", "test");
|
||||
|
||||
expect(output).toBe("test{");
|
||||
});
|
||||
|
||||
it('Keyboard "}" button will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
const output = keyboard.utilities.getUpdatedInput("}", "test");
|
||||
|
||||
expect(output).toBe("test}");
|
||||
});
|
||||
|
||||
it('Keyboard standard button will affect input', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
for (let i = 65; i <= 90; i++) {
|
||||
const char = String.fromCharCode(i);
|
||||
const output = keyboard.utilities.getUpdatedInput(char, "test");
|
||||
expect(output).toBe(`test${char}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('Keyboard updateCaretPos will work with minus', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
syncInstanceInputs: true
|
||||
});
|
||||
|
||||
keyboard.setCaretPosition(5);
|
||||
keyboard.utilities.updateCaretPos(2, true);
|
||||
|
||||
expect(keyboard.caretPosition).toBe(3);
|
||||
});
|
||||
|
||||
it('Keyboard updateCaretPos will work with minus', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
keyboard.setCaretPosition(5);
|
||||
keyboard.utilities.updateCaretPos(2, true);
|
||||
|
||||
expect(keyboard.caretPosition).toBe(3);
|
||||
});
|
||||
|
||||
it('Keyboard updateCaretPos will work with plus', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
keyboard.setCaretPosition(5);
|
||||
keyboard.utilities.updateCaretPos(2);
|
||||
|
||||
expect(keyboard.caretPosition).toBe(7);
|
||||
});
|
||||
|
||||
it('Keyboard addStringAt will work with debug', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
debug: true
|
||||
});
|
||||
|
||||
keyboard.getButtonElement("q").onclick();
|
||||
|
||||
expect(keyboard.getInput()).toBe("q");
|
||||
});
|
||||
|
||||
it('Keyboard addStringAt will work with position', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
debug: true
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
keyboard.setCaretPosition(5);
|
||||
|
||||
keyboard.getButtonElement("q").onclick();
|
||||
|
||||
expect(keyboard.getInput()).toBe("testq");
|
||||
});
|
||||
|
||||
it('Keyboard addStringAt will respect maxLength', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
debug: true,
|
||||
maxLength: 4
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
keyboard.setCaretPosition(4);
|
||||
|
||||
keyboard.utilities.handleMaxLength(keyboard.input, "testq")
|
||||
keyboard.utilities.addStringAt("test", "q", 4, 4);
|
||||
|
||||
expect(keyboard.caretPosition).toBe(4);
|
||||
});
|
||||
|
||||
it('Keyboard handleMaxLength will exit out on same updatedInput', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
debug: true
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
const output = keyboard.utilities.handleMaxLength(keyboard.input, "test")
|
||||
|
||||
expect(output).toBeFalsy();
|
||||
});
|
||||
|
||||
it('Keyboard handleMaxLength will work with object maxLength', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
maxLength: {
|
||||
default: 4
|
||||
}
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
const output = keyboard.utilities.handleMaxLength(keyboard.input, "testq");
|
||||
|
||||
expect(output).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Keyboard handleMaxLength will work with object maxLength and debug', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
maxLength: {
|
||||
default: 4
|
||||
},
|
||||
debug: true
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
const output = keyboard.utilities.handleMaxLength(keyboard.input, "testq");
|
||||
|
||||
expect(output).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Keyboard handleMaxLength will return false if obj maxLength not reached', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
maxLength: {
|
||||
default: 7
|
||||
}
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
const output = keyboard.utilities.handleMaxLength(keyboard.input, "testq");
|
||||
|
||||
expect(output).toBeFalsy();
|
||||
});
|
||||
|
||||
|
||||
it('Keyboard handleMaxLength will work without debug', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
maxLength: 4
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
const output = keyboard.utilities.handleMaxLength(keyboard.input, "testq");
|
||||
|
||||
expect(output).toBeTruthy();
|
||||
});
|
||||
|
||||
|
||||
it('Keyboard handleMaxLength will work with numeric maxLength', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
maxLength: 3
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
const output = keyboard.utilities.handleMaxLength(keyboard.input, "testq");
|
||||
|
||||
expect(output).toBe(true);
|
||||
});
|
||||
|
||||
it('Keyboard handleMaxLength wont work with non numeric or object maxLength', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
maxLength: "wrong"
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
const output = keyboard.utilities.handleMaxLength(keyboard.input, "testq");
|
||||
|
||||
expect(output).toBeFalsy();
|
||||
});
|
||||
|
||||
it('Keyboard handleMaxLength wont work with non numeric or object maxLength (with debug)', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
maxLength: "wrong",
|
||||
debug: true
|
||||
});
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
const output = keyboard.utilities.handleMaxLength(keyboard.input, "testq");
|
||||
|
||||
expect(output).toBeFalsy();
|
||||
});
|
||||
|
||||
it('Keyboard isMaxLengthReached will work', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
maxLength: 5
|
||||
});
|
||||
|
||||
const output = keyboard.utilities.isMaxLengthReached();
|
||||
|
||||
expect(output).toBeFalsy();
|
||||
});
|
||||
|
||||
it('Keyboard removeAt will exit out on caretPosition:0', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
keyboard.setCaretPosition(0);
|
||||
keyboard.utilities.removeAt(keyboard.getInput(), 0);
|
||||
expect(keyboard.getInput()).toBe("test");
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
keyboard.setCaretPosition(5);
|
||||
keyboard.utilities.removeAt(keyboard.getInput(), 0, 0, true);
|
||||
expect(keyboard.caretPosition).toBe(5);
|
||||
});
|
||||
|
||||
it('Keyboard removeAt will remove multi-byte unicodes with caretPos>0', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
keyboard.setCaretPosition(6);
|
||||
let output = keyboard.utilities.removeAt("test\uD83D\uDE00", 6, 6);
|
||||
expect(output).toBe("test");
|
||||
|
||||
keyboard.setCaretPosition(6);
|
||||
output = keyboard.utilities.removeAt("test\uD83D\uDE00", 6, 6, true);
|
||||
expect(keyboard.caretPosition).toBe(4);
|
||||
});
|
||||
|
||||
it('Keyboard removeAt will not remove multi-byte unicodes with caretPos:0', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
let output = keyboard.utilities.removeAt("\uD83D\uDE00");
|
||||
expect(output).toBeFalsy();
|
||||
|
||||
output = keyboard.utilities.removeAt("\uD83D\uDE00", 0, 0, true);
|
||||
expect(output).toBe("\uD83D\uDE00");
|
||||
});
|
||||
|
||||
it('Keyboard removeAt will propagate caretPosition', () => {
|
||||
clearDOM();
|
||||
|
||||
document.body.innerHTML = `
|
||||
<div class="simple-keyboard"></div>
|
||||
<div class="keyboard2"></div>
|
||||
`;
|
||||
|
||||
const keyboard = new Keyboard({ useMouseEvents: true });
|
||||
const keyboard2 = new Keyboard('.keyboard2');
|
||||
|
||||
keyboard.input.default = "hello";
|
||||
keyboard2.input.default = "world"
|
||||
|
||||
keyboard.setCaretPosition(1);
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(1);
|
||||
|
||||
keyboard.setCaretPosition(1, 3);
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(3);
|
||||
|
||||
keyboard.getButtonElement('{bksp}').onclick();
|
||||
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard2.getCaretPosition()).toBe(1);
|
||||
|
||||
expect(keyboard.getInput()).toBe('hlo');
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(1);
|
||||
expect(keyboard2.getCaretPositionEnd()).toBe(1);
|
||||
});
|
||||
|
||||
it('Keyboard removeAt will propagate caretPosition in a syncInstanceInputs setting', () => {
|
||||
clearDOM();
|
||||
|
||||
document.body.innerHTML = `
|
||||
<div class="simple-keyboard"></div>
|
||||
<div class="keyboard2"></div>
|
||||
`;
|
||||
|
||||
const keyboard = new Keyboard({ useMouseEvents: true, syncInstanceInputs: true });
|
||||
const keyboard2 = new Keyboard('.keyboard2');
|
||||
|
||||
keyboard.input.default = "hello"
|
||||
|
||||
keyboard.setCaretPosition(1);
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(1);
|
||||
|
||||
keyboard.setCaretPosition(1, 3);
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(3);
|
||||
|
||||
keyboard.getButtonElement('{bksp}').onclick();
|
||||
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard2.getCaretPosition()).toBe(1);
|
||||
|
||||
expect(keyboard.getInput()).toBe('hlo');
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(1);
|
||||
expect(keyboard2.getCaretPositionEnd()).toBe(1);
|
||||
});
|
||||
|
||||
it('Keyboard removeAt will remove regular strings', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
debug: true
|
||||
});
|
||||
|
||||
keyboard.setCaretPosition(6);
|
||||
let output = keyboard.utilities.removeAt("testie", 6, 6);
|
||||
expect(output).toBe("testi");
|
||||
|
||||
keyboard.setCaretPosition(6);
|
||||
output = keyboard.utilities.removeAt("testie", 6, 6, true);
|
||||
expect(keyboard.caretPosition).toBe(5);
|
||||
});
|
||||
|
||||
it('Keyboard removeAt will work with unset or start caretPosition', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
debug: true
|
||||
});
|
||||
|
||||
let output = keyboard.utilities.removeAt("test");
|
||||
expect(output).toBe("tes");
|
||||
|
||||
output = keyboard.utilities.removeAt("test", null, null);
|
||||
expect(output).toBe("tes");
|
||||
|
||||
output = keyboard.utilities.removeAt("😀", null, null);
|
||||
expect(output).toBe("");
|
||||
|
||||
/**
|
||||
* Will also work with moveCaret
|
||||
*/
|
||||
keyboard.setCaretPosition(3);
|
||||
output = keyboard.utilities.removeAt("test", null, null, true);
|
||||
expect(output).toBe("tes");
|
||||
expect(keyboard.getCaretPosition()).toBe(2);
|
||||
|
||||
keyboard.setCaretPosition(2);
|
||||
output = keyboard.utilities.removeAt("😀", null, null, true);
|
||||
expect(output).toBe("");
|
||||
expect(keyboard.getCaretPosition()).toBe(0);
|
||||
});
|
||||
|
||||
it('Keyboard will work with custom (and weird) class', () => {
|
||||
setDOM("my--weird--class");
|
||||
const keyboard = new Keyboard(".my--weird--class");
|
||||
expect(keyboard.keyboardDOMClass).toBe("my--weird--class");
|
||||
});
|
||||
|
||||
it('Keyboard camelCase will work with empty strings', () => {
|
||||
setDOM();
|
||||
const keyboard = new Keyboard();
|
||||
expect(keyboard.utilities.camelCase()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('Keyboard removeForwardsAt will exit out on caretPosition:0', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
keyboard.setCaretPosition(0);
|
||||
keyboard.utilities.removeForwardsAt(keyboard.getInput(), 0);
|
||||
expect(keyboard.getInput()).toBe("test");
|
||||
|
||||
keyboard.setInput("test");
|
||||
|
||||
keyboard.setCaretPosition(5);
|
||||
keyboard.utilities.removeForwardsAt(keyboard.getInput(), 0, 0, true);
|
||||
expect(keyboard.caretPosition).toBe(5);
|
||||
});
|
||||
|
||||
it('Keyboard removeForwardsAt will remove multi-byte unicodes with caretPos>0', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard();
|
||||
|
||||
keyboard.setCaretPosition(4);
|
||||
let output = keyboard.utilities.removeForwardsAt("test\uD83D\uDE00", 4, 4);
|
||||
expect(output).toBe("test");
|
||||
|
||||
keyboard.setCaretPosition(4);
|
||||
output = keyboard.utilities.removeForwardsAt("test\uD83D\uDE00", 4, 4, true);
|
||||
expect(keyboard.caretPosition).toBe(4);
|
||||
});
|
||||
|
||||
it('Keyboard removeForwardsAt will not remove multi-byte unicodes with caretPos:0', () => {
|
||||
setDOM();
|
||||
|
||||
const str = "\uD83D\uDE00";
|
||||
const keyboard = new Keyboard();
|
||||
let output = keyboard.utilities.removeForwardsAt(str, 0);
|
||||
expect(output).toBe("");
|
||||
|
||||
output = keyboard.utilities.removeForwardsAt(str, 0, 0, true);
|
||||
expect(output).toBe("");
|
||||
});
|
||||
|
||||
it('Keyboard removeForwardsAt will propagate caretPosition', () => {
|
||||
clearDOM();
|
||||
|
||||
document.body.innerHTML = `
|
||||
<div class="simple-keyboard"></div>
|
||||
<div class="keyboard2"></div>
|
||||
`;
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
useMouseEvents: true,
|
||||
layout: {
|
||||
default: ["{delete}"]
|
||||
}
|
||||
});
|
||||
const keyboard2 = new Keyboard('.keyboard2');
|
||||
|
||||
keyboard.input.default = "hello";
|
||||
keyboard2.input.default = "world"
|
||||
|
||||
keyboard.setCaretPosition(1);
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(1);
|
||||
|
||||
keyboard.setCaretPosition(1, 3);
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(3);
|
||||
|
||||
keyboard.getButtonElement('{delete}').onclick();
|
||||
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard2.getCaretPosition()).toBe(1);
|
||||
|
||||
expect(keyboard.getInput()).toBe('hlo');
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(1);
|
||||
expect(keyboard2.getCaretPositionEnd()).toBe(1);
|
||||
});
|
||||
|
||||
it('Keyboard removeForwardsAt will propagate caretPosition in a syncInstanceInputs setting', () => {
|
||||
clearDOM();
|
||||
|
||||
document.body.innerHTML = `
|
||||
<div class="simple-keyboard"></div>
|
||||
<div class="keyboard2"></div>
|
||||
`;
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
useMouseEvents: true,
|
||||
syncInstanceInputs: true,
|
||||
layout: {
|
||||
default: ["{delete}"]
|
||||
}
|
||||
});
|
||||
const keyboard2 = new Keyboard('.keyboard2');
|
||||
|
||||
keyboard.input.default = "hello"
|
||||
|
||||
keyboard.setCaretPosition(1);
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(1);
|
||||
|
||||
keyboard.setCaretPosition(1, 3);
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(3);
|
||||
|
||||
keyboard.getButtonElement('{delete}').onclick();
|
||||
|
||||
expect(keyboard.getCaretPosition()).toBe(1);
|
||||
expect(keyboard2.getCaretPosition()).toBe(1);
|
||||
|
||||
expect(keyboard.getInput()).toBe('hlo');
|
||||
expect(keyboard.getCaretPositionEnd()).toBe(1);
|
||||
expect(keyboard2.getCaretPositionEnd()).toBe(1);
|
||||
});
|
||||
|
||||
it('Keyboard removeForwardsAt will remove regular strings', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
debug: true
|
||||
});
|
||||
|
||||
keyboard.setCaretPosition(6);
|
||||
let output = keyboard.utilities.removeForwardsAt("testie", 5, 5);
|
||||
expect(output).toBe("testi");
|
||||
|
||||
keyboard.setCaretPosition(5);
|
||||
output = keyboard.utilities.removeForwardsAt("testie", 5, 5, true);
|
||||
expect(keyboard.caretPosition).toBe(5);
|
||||
});
|
||||
|
||||
it('Keyboard removeForwardsAt will work with unset or start caretPosition', () => {
|
||||
setDOM();
|
||||
|
||||
const keyboard = new Keyboard({
|
||||
debug: true
|
||||
});
|
||||
|
||||
let output = keyboard.utilities.removeForwardsAt("test", 3);
|
||||
expect(output).toBe("tes");
|
||||
|
||||
output = keyboard.utilities.removeForwardsAt("test", null, null);
|
||||
expect(output).toBe("test");
|
||||
|
||||
output = keyboard.utilities.removeForwardsAt("😀", 0);
|
||||
expect(output).toBe("");
|
||||
|
||||
/**
|
||||
* Will also work with moveCaret
|
||||
*/
|
||||
output = keyboard.utilities.removeForwardsAt("test", null, null, true);
|
||||
expect(output).toBe("test");
|
||||
expect(keyboard.getCaretPosition()).toBe(null);
|
||||
|
||||
keyboard.setCaretPosition(2);
|
||||
const str = "😀";
|
||||
output = keyboard.utilities.removeForwardsAt(str, null, null, true);
|
||||
expect(output).toBe(str);
|
||||
expect(keyboard.getCaretPosition()).toBe(2);
|
||||
});
|
||||
@@ -1,118 +0,0 @@
|
||||
/**
|
||||
* Test Utility Functions
|
||||
*/
|
||||
/**
|
||||
* Sets a basic DOM structure to test in
|
||||
*/
|
||||
export const setDOM = (divClass) => {
|
||||
clearDOM();
|
||||
const wrapperDOM = document.createElement('div');
|
||||
wrapperDOM.setAttribute("id", "root");
|
||||
|
||||
const keyboardDOM = document.createElement('div');
|
||||
keyboardDOM.className = divClass || "simple-keyboard";
|
||||
|
||||
wrapperDOM.appendChild(keyboardDOM);
|
||||
document.body.appendChild(wrapperDOM);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears DOM structure
|
||||
*/
|
||||
export const clearDOM = () => {
|
||||
document.body.innerHTML = "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger pointerup
|
||||
*/
|
||||
export const triggerDocumentPointerUp = (e = {}) => {
|
||||
document.dispatchEvent(new MouseEvent('mouseup', e));
|
||||
};
|
||||
|
||||
/**
|
||||
* Trigger pointerdown
|
||||
*/
|
||||
export const triggerDocumentPointerDown = (e = {}) => {
|
||||
document.dispatchEvent(new MouseEvent('mousedown', e));
|
||||
};
|
||||
|
||||
/**
|
||||
* Test if standard buttons respect maxLength and do input a value
|
||||
*/
|
||||
export const testLayoutStdButtons = (keyboard) => {
|
||||
let stdBtnCount = 0;
|
||||
let fullInput = '';
|
||||
|
||||
keyboard.recurseButtons((button) => {
|
||||
const label = button.getAttribute("data-skbtn");
|
||||
|
||||
if(label.includes("{"))
|
||||
return false;
|
||||
|
||||
// Click all standard buttons, respects maxLength
|
||||
button.onclick();
|
||||
|
||||
// Recording fullInput, bypasses maxLength
|
||||
fullInput = keyboard.utilities.getUpdatedInput(label, fullInput);
|
||||
|
||||
stdBtnCount += label.length;
|
||||
});
|
||||
|
||||
/**
|
||||
* Check if maxLength is respected
|
||||
*/
|
||||
if(
|
||||
(
|
||||
typeof keyboard.options.maxLength === "object" &&
|
||||
keyboard.getInput().length !== keyboard.options.maxLength[keyboard.options.layoutName]
|
||||
) ||
|
||||
(
|
||||
typeof keyboard.options.maxLength !== "object" &&
|
||||
keyboard.getInput().length !== keyboard.options.maxLength
|
||||
)
|
||||
)
|
||||
throw new Error("MAX_LENGTH_ISSUE");
|
||||
else
|
||||
console.log("MAX_LENGTH PASSED:", keyboard.options.layoutName, keyboard.getInput().length, keyboard.options.maxLength);
|
||||
|
||||
/**
|
||||
* Check if all standard buttons are inputting something
|
||||
* (Regardless of maxLength)
|
||||
*/
|
||||
if(stdBtnCount !== fullInput.length)
|
||||
throw new Error("STANDARD_BUTTONS_ISSUE");
|
||||
else
|
||||
console.log("STANDARD_BUTTONS PASSED:", keyboard.options.layoutName, stdBtnCount, fullInput.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if function buttons are interactive (have an onclick)
|
||||
*/
|
||||
export const testLayoutFctButtons = (keyboard, callback) => {
|
||||
let fctBtnCount = 0;
|
||||
let fctBtnHasOnclickCount = 0;
|
||||
|
||||
keyboard.recurseButtons((button) => {
|
||||
const label = button.getAttribute("data-skbtn");
|
||||
|
||||
if(!label.includes("{") && !label.includes("}"))
|
||||
return false;
|
||||
|
||||
fctBtnCount++;
|
||||
|
||||
if(button.onclick){
|
||||
button.onclick();
|
||||
fctBtnHasOnclickCount++;
|
||||
}
|
||||
|
||||
callback(fctBtnCount, fctBtnHasOnclickCount);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove RTL control chars
|
||||
*/
|
||||
export const removeRTLControls = (input) => {
|
||||
return input.replace("\u202B", "").replace("\u202C", "");
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user