├── .babelrc ├── .gitignore ├── .npmignore ├── .nvmrc ├── CODE_OF_CONDUCT.md ├── README.md ├── lib ├── index.js └── index.js.map ├── package.json ├── src └── index.js └── webpack.config.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["env","react"], 3 | "env": { 4 | "production": { 5 | "plugins": [ 6 | ["transform-react-remove-prop-types", { 7 | "removeImport": true, 8 | "ignoreFilenames": ["node_modules"] 9 | }] 10 | ] 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # misc 10 | .DS_Store 11 | .env.local 12 | .env.development.local 13 | .env.test.local 14 | .env.production.local 15 | .vscode 16 | 17 | npm-debug.log* 18 | yarn-debug.log* 19 | yarn-error.log* 20 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package 2 | 3 | #tests 4 | test 5 | coverage 6 | 7 | #build tools 8 | .travis.yml 9 | 10 | #linters 11 | .jscsrc 12 | .jshintrc 13 | .eslintrc* 14 | 15 | #editor settings 16 | .vscode 17 | 18 | #files 19 | src 20 | 21 | #misc 22 | .babelrc 23 | .nvmrc 24 | webpack.config.js -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v7.2.0 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🔋 React Device Battery 2 | 3 | > 👀 In development 4 | 5 | Notifies your React app of the device battery status 6 | 7 | This component is based on the [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API) 8 | 9 | __The Battery Status API, more often referred to as the Battery API, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change.__ 10 | 11 | ## Demo 12 | 13 | [![Edit react-battery](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/3kp5mjkj81) 14 | 15 | ## :package: Installation 16 | 17 | ```bash 18 | npm install react-device-battery 19 | ``` 20 | 21 | ## :rocket: Load 22 | 23 | ```js 24 | // using es modules 25 | import Battery from 'react-device-battery' 26 | 27 | // common.js 28 | const Battery = require('react-device-battery') 29 | 30 | // AMD 31 | 32 | ``` 33 | 34 | Or use script tags and globals. 35 | 36 | ```html 37 | 38 | ``` 39 | 40 | And then grab it off the global like so: 41 | 42 | ```js 43 | const Battery = reactDeviceBattery 44 | ``` 45 | 46 | ## :bulb: Usage 47 | 48 | Let's assume you want to check if you have enough battery before doing somenthing or you want to render based on how much battery you got left: 49 | 50 | ```javascript 51 | const App = () => ( 52 |
53 |    

Magic is happening ⚡️

54 | { 56 | console.log(battery) 57 | }} 58 | render={({ battery }) => 59 |

Battery Level: {battery ? battery : Not Supported}.

60 | } 61 | /> 62 |
63 | ); 64 | 65 | render(, document.getElementById('root')); 66 | ``` 67 | 68 | > If the Battery API is not supported, the render function is passed `null`. 69 | 70 | ## Props 71 | 72 | #### `render` [required] 73 | Default: `null` 74 | 75 | Whatever you'd like to render in response to changes in the battery level 76 | 77 | ```javascript 78 | 80 |

Battery Level: {battery ? battery : Not Supported}.

81 | } 82 | /> 83 | ``` 84 | 85 | #### `onChange` [optional] 86 | Default: `undefined` 87 | 88 | Called whenever the batter level changes 89 | 90 | ```javascript 91 | handleBatteryChange = ({ battery }) => { 92 | if (battery <= 10) { 93 | this.saveMyData(); // Oh my... 94 | } 95 | } 96 | 97 | 100 |

Battery Level: {battery ? battery : Not Supported}.

101 | } 102 | /> 103 | ``` 104 | 105 | ## Component info 106 | 107 | This component has been built using `React Render Callback` pattern. Basically it is a way for the parent to provide some logic to the child, and the child have the control on how to execute that logic. 108 | 109 | ## Legal 110 | 111 | Released under MIT license. 112 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.reactDeviceBattery=t(require("react")):e.reactDeviceBattery=t(e.React)}(this,function(e){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=1)}([function(t,n){t.exports=e},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n {\n const percentage = this.getBatteryLevel(battery);\n this.props.onChange(percentage);\n this.setState({ battery: percentage });\n });\n }\n getBatteryLevel(battery) {\n return parseFloat((battery.level * 100).toFixed(2));\n }\n handleChange() {\n this.setBatteryState();\n }\n componentDidMount() {\n if (this.isBatteryStatusAPISupported()) {\n this.setBatteryState();\n this.props.onChange(this.state.battery);\n navigator.getBattery().then(battery => {\n battery.addEventListener(\"levelchange\", this.handleChange); \n });\n }\n }\n componentWillUnmount() {\n navigator.getBattery().then(battery => {\n battery.removeEventListener(\"levelchange\", this.handleChange);\n });\n }\n render() {\n return this.props.render(this.state);\n }\n}\nif (process.env.NODE_ENV !== \"production\") {\n Battery.defaultProps = {\n render: () => null,\n onChange: () => { }\n };\n Battery.propTypes = {\n render: PropTypes.func.isRequired,\n onChange: PropTypes.func\n };\n}\n\nexport default Battery;\n\n\n// WEBPACK FOOTER //\n// ./src/index.js"],"sourceRoot":""} -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-device-battery", 3 | "version": "0.1.0", 4 | "description": "Get battery status", 5 | "main": "lib/index.js", 6 | "module": "lib/index.js", 7 | "peerDependencies": { 8 | "prop-types": "^15.5.10", 9 | "react": "15.x || ^16.0.0-rc" 10 | }, 11 | "scripts": { 12 | "test": "echo \"Error: no test specified\" && exit 1", 13 | "start": "webpack --watch", 14 | "build": "NODE_ENV=production webpack --config webpack.config.js", 15 | "prepublish": "npm run build" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "git+https://github.com/zanonnicola/react-device-battery.git" 20 | }, 21 | "keywords": [ 22 | "react-component", 23 | "Battery", 24 | "javascript" 25 | ], 26 | "author": "Nicola Zanon (https://nicola-zanon.com/)", 27 | "devDependencies": { 28 | "babel-cli": "^6.24.1", 29 | "babel-core": "^6.26.0", 30 | "babel-loader": "^7.1.2", 31 | "babel-plugin-transform-object-rest-spread": "^6.23.0", 32 | "babel-plugin-transform-react-jsx": "^6.24.1", 33 | "babel-plugin-transform-react-remove-prop-types": "^0.4.8", 34 | "babel-preset-env": "^1.6.0", 35 | "babel-preset-es2015": "^6.24.1", 36 | "babel-preset-react": "^6.24.1", 37 | "react": "^15.5.4", 38 | "webpack": "^2.6.1" 39 | }, 40 | "license": "MIT", 41 | "bugs": { 42 | "url": "https://github.com/zanonnicola/react-device-battery/issues" 43 | }, 44 | "homepage": "https://github.com/zanonnicola/react-device-battery#readme", 45 | "dependencies": {} 46 | } 47 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React, {Component} from 'react'; 2 | import PropTypes from 'prop-types'; 3 | 4 | class Battery extends Component { 5 | constructor(props) { 6 | super(props); 7 | this.state = { 8 | battery: null 9 | }; 10 | this.handleChange = this.handleChange.bind(this); 11 | } 12 | isBatteryStatusAPISupported() { 13 | if (navigator.getBattery || navigator.battery || navigator.mozBattery) { 14 | return true; 15 | } 16 | return false; 17 | } 18 | setBatteryState() { 19 | navigator.getBattery().then( battery => { 20 | const percentage = this.getBatteryLevel(battery); 21 | this.props.onChange(percentage); 22 | this.setState({ battery: percentage }); 23 | }); 24 | } 25 | getBatteryLevel({level}) { 26 | return parseFloat((level * 100).toFixed(2)); 27 | } 28 | handleChange() { 29 | this.setBatteryState(); 30 | } 31 | componentDidMount() { 32 | if (this.isBatteryStatusAPISupported()) { 33 | this.setBatteryState(); 34 | this.props.onChange(this.state.battery); 35 | navigator.getBattery().then(battery => { 36 | battery.addEventListener("levelchange", this.handleChange); 37 | }); 38 | } 39 | } 40 | componentWillUnmount() { 41 | navigator.getBattery().then(battery => { 42 | battery.removeEventListener("levelchange", this.handleChange); 43 | }); 44 | } 45 | render() { 46 | return this.props.render(this.state); 47 | } 48 | } 49 | if (process.env.NODE_ENV !== "production") { 50 | Battery.defaultProps = { 51 | render: () => null, 52 | onChange: () => { } 53 | }; 54 | Battery.propTypes = { 55 | render: PropTypes.func.isRequired, 56 | onChange: PropTypes.func 57 | }; 58 | } 59 | 60 | export default Battery; 61 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const webpack = require('webpack'); 3 | module.exports = { 4 | entry: './src/index.js', 5 | output: { 6 | path: path.resolve(__dirname, 'lib'), 7 | filename: 'index.js', 8 | library: 'reactDeviceBattery', 9 | libraryTarget: 'umd' 10 | }, 11 | devtool: "source-map", 12 | module: { 13 | rules: [ 14 | { 15 | test: /\.js$/, 16 | include: path.resolve(__dirname, 'src'), 17 | exclude: /(node_modules|bower_components|lib)/, 18 | loader: 'babel-loader' 19 | } 20 | ] 21 | }, 22 | externals: { 23 | 'react': { 24 | root: 'React', 25 | commonjs2: 'react', 26 | commonjs: 'react', 27 | amd: 'react' 28 | } 29 | }, 30 | plugins: [ 31 | new webpack.optimize.UglifyJsPlugin({ 32 | sourceMap: true, // enable source maps to map errors (stack traces) to modules 33 | output: { 34 | comments: false, // remove all comments 35 | }, 36 | }), 37 | new webpack.DefinePlugin({ 38 | "process.env": { 39 | NODE_ENV: JSON.stringify("production"), 40 | }, 41 | }), 42 | ] 43 | }; --------------------------------------------------------------------------------