├── .circleci
└── config.yml
├── .editorconfig
├── .gitattributes
├── .gitignore
├── .husky
├── .npmignore
├── commit-msg
└── pre-commit
├── .yarnrc
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.js
├── devices.png
├── example-1.png
├── example-2.png
├── example-3.png
├── example
├── app.json
├── babel.config.js
├── index.js
├── metro.config.js
├── package-lock.json
├── package.json
├── src
│ └── App.tsx
├── tsconfig.json
└── webpack.config.js
├── package-lock.json
├── package.json
├── scripts
└── bootstrap.js
├── src
├── __tests__
│ └── index.test.tsx
├── devices.ts
├── index.ts
└── utils.ts
├── tsconfig.build.json
└── tsconfig.json
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 |
3 | executors:
4 | default:
5 | docker:
6 | - image: circleci/node:10
7 | working_directory: ~/project
8 |
9 | commands:
10 | attach_project:
11 | steps:
12 | - attach_workspace:
13 | at: ~/project
14 |
15 | jobs:
16 | install-dependencies:
17 | executor: default
18 | steps:
19 | - checkout
20 | - attach_project
21 | - restore_cache:
22 | keys:
23 | - dependencies-{{ checksum "package.json" }}
24 | - dependencies-
25 | - restore_cache:
26 | keys:
27 | - dependencies-example-{{ checksum "example/package.json" }}
28 | - dependencies-example-
29 | - run:
30 | name: Install dependencies
31 | command: |
32 | yarn install --cwd example --frozen-lockfile
33 | yarn install --frozen-lockfile
34 | - save_cache:
35 | key: dependencies-{{ checksum "package.json" }}
36 | paths: node_modules
37 | - save_cache:
38 | key: dependencies-example-{{ checksum "example/package.json" }}
39 | paths: example/node_modules
40 | - persist_to_workspace:
41 | root: .
42 | paths: .
43 |
44 | lint:
45 | executor: default
46 | steps:
47 | - attach_project
48 | - run:
49 | name: Lint files
50 | command: |
51 | yarn lint
52 |
53 | typescript:
54 | executor: default
55 | steps:
56 | - attach_project
57 | - run:
58 | name: Typecheck files
59 | command: |
60 | yarn typescript
61 |
62 | unit-tests:
63 | executor: default
64 | steps:
65 | - attach_project
66 | - run:
67 | name: Run unit tests
68 | command: |
69 | yarn test --coverage
70 | - store_artifacts:
71 | path: coverage
72 | destination: coverage
73 |
74 | build-package:
75 | executor: default
76 | steps:
77 | - attach_project
78 | - run:
79 | name: Build package
80 | command: |
81 | yarn prepare
82 |
83 | workflows:
84 | build-and-test:
85 | jobs:
86 | - install-dependencies
87 | - lint:
88 | requires:
89 | - install-dependencies
90 | - typescript:
91 | requires:
92 | - install-dependencies
93 | - unit-tests:
94 | requires:
95 | - install-dependencies
96 | - build-package:
97 | requires:
98 | - install-dependencies
99 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig helps developers define and maintain consistent
2 | # coding styles between different editors and IDEs
3 | # editorconfig.org
4 |
5 | root = true
6 |
7 | [*]
8 |
9 | indent_style = space
10 | indent_size = 2
11 |
12 | end_of_line = lf
13 | charset = utf-8
14 | trim_trailing_whitespace = true
15 | insert_final_newline = true
16 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # VSCode
9 | .vscode/
10 | jsconfig.json
11 |
12 | # Xcode
13 | #
14 | build/
15 | *.pbxuser
16 | !default.pbxuser
17 | *.mode1v3
18 | !default.mode1v3
19 | *.mode2v3
20 | !default.mode2v3
21 | *.perspectivev3
22 | !default.perspectivev3
23 | xcuserdata
24 | *.xccheckout
25 | *.moved-aside
26 | DerivedData
27 | *.hmap
28 | *.ipa
29 | *.xcuserstate
30 | project.xcworkspace
31 |
32 | # Android/IJ
33 | #
34 | .classpath
35 | .cxx
36 | .gradle
37 | .idea
38 | .project
39 | .settings
40 | local.properties
41 | android.iml
42 |
43 | # Cocoapods
44 | #
45 | example/ios/Pods
46 |
47 | # node.js
48 | #
49 | node_modules/
50 | npm-debug.log
51 | yarn-debug.log
52 | yarn-error.log
53 |
54 | # BUCK
55 | buck-out/
56 | \.buckd/
57 | android/app/libs
58 | android/keystores/debug.keystore
59 |
60 | # Expo
61 | .expo/*
62 |
63 | # generated by bob
64 | lib/
65 |
--------------------------------------------------------------------------------
/.husky/.npmignore:
--------------------------------------------------------------------------------
1 | _
2 |
--------------------------------------------------------------------------------
/.husky/commit-msg:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | . "$(dirname "$0")/_/husky.sh"
3 |
4 | yarn commitlint -E HUSKY_GIT_PARAMS
5 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | . "$(dirname "$0")/_/husky.sh"
3 |
4 | yarn lint && yarn typescript
5 |
--------------------------------------------------------------------------------
/.yarnrc:
--------------------------------------------------------------------------------
1 | # Override Yarn command so we can automatically setup the repo on running `yarn`
2 |
3 | yarn-path "scripts/bootstrap.js"
4 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project.
4 |
5 | ## Development workflow
6 |
7 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
8 |
9 | ```sh
10 | yarn
11 | ```
12 |
13 | > While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development.
14 |
15 | While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app.
16 |
17 | To start the packager:
18 |
19 | ```sh
20 | yarn example start
21 | ```
22 |
23 | To run the example app on Android:
24 |
25 | ```sh
26 | yarn example android
27 | ```
28 |
29 | To run the example app on iOS:
30 |
31 | ```sh
32 | yarn example ios
33 | ```
34 |
35 | To run the example app on Web:
36 |
37 | ```sh
38 | yarn example web
39 | ```
40 |
41 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
42 |
43 | ```sh
44 | yarn typescript
45 | yarn lint
46 | ```
47 |
48 | To fix formatting errors, run the following:
49 |
50 | ```sh
51 | yarn lint --fix
52 | ```
53 |
54 | Remember to add tests for your change if possible. Run the unit tests by:
55 |
56 | ```sh
57 | yarn test
58 | ```
59 |
60 | ### Commit message convention
61 |
62 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
63 |
64 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
65 | - `feat`: new features, e.g. add new method to the module.
66 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
67 | - `docs`: changes into documentation, e.g. add usage example for the module..
68 | - `test`: adding or updating tests, e.g. add integration tests using detox.
69 | - `chore`: tooling changes, e.g. change CI config.
70 |
71 | Our pre-commit hooks verify that your commit message matches this format when committing.
72 |
73 | ### Linting and tests
74 |
75 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
76 |
77 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
78 |
79 | Our pre-commit hooks verify that the linter and tests pass when committing.
80 |
81 | ### Publishing to npm
82 |
83 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc.
84 |
85 | To publish new versions, run the following:
86 |
87 | ```sh
88 | yarn release
89 | ```
90 |
91 | ### Scripts
92 |
93 | The `package.json` file contains various scripts for common tasks:
94 |
95 | - `yarn bootstrap`: setup project by installing all dependencies and pods.
96 | - `yarn typescript`: type-check files with TypeScript.
97 | - `yarn lint`: lint files with ESLint.
98 | - `yarn test`: run unit tests with Jest.
99 | - `yarn example start`: start the Metro server for the example app.
100 | - `yarn example android`: run the example app on Android.
101 | - `yarn example ios`: run the example app on iOS.
102 |
103 | ### Sending a pull request
104 |
105 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github).
106 |
107 | When you're sending a pull request:
108 |
109 | - Prefer small pull requests focused on one change.
110 | - Verify that linters and tests are passing.
111 | - Review the documentation to make sure it looks good.
112 | - Follow the pull request template when opening a pull request.
113 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
114 |
115 | ## Code of Conduct
116 |
117 | ### Our Pledge
118 |
119 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible 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.
120 |
121 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
122 |
123 | ### Our Standards
124 |
125 | Examples of behavior that contributes to a positive environment for our community include:
126 |
127 | - Demonstrating empathy and kindness toward other people
128 | - Being respectful of differing opinions, viewpoints, and experiences
129 | - Giving and gracefully accepting constructive feedback
130 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
131 | - Focusing on what is best not just for us as individuals, but for the overall community
132 |
133 | Examples of unacceptable behavior include:
134 |
135 | - The use of sexualized language or imagery, and sexual attention or
136 | advances of any kind
137 | - Trolling, insulting or derogatory comments, and personal or political attacks
138 | - Public or private harassment
139 | - Publishing others' private information, such as a physical or email
140 | address, without their explicit permission
141 | - Other conduct which could reasonably be considered inappropriate in a
142 | professional setting
143 |
144 | ### Enforcement Responsibilities
145 |
146 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
147 |
148 | Community leaders 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, and will communicate reasons for moderation decisions when appropriate.
149 |
150 | ### Scope
151 |
152 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
153 |
154 | ### Enforcement
155 |
156 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
157 |
158 | All community leaders are obligated to respect the privacy and security of the reporter of any incident.
159 |
160 | ### Enforcement Guidelines
161 |
162 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
163 |
164 | #### 1. Correction
165 |
166 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
167 |
168 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
169 |
170 | #### 2. Warning
171 |
172 | **Community Impact**: A violation through a single incident or series of actions.
173 |
174 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
175 |
176 | #### 3. Temporary Ban
177 |
178 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
179 |
180 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
181 |
182 | #### 4. Permanent Ban
183 |
184 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
185 |
186 | **Consequence**: A permanent ban from any sort of public interaction within the community.
187 |
188 | ### Attribution
189 |
190 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
191 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
192 |
193 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
194 |
195 | [homepage]: https://www.contributor-covenant.org
196 |
197 | For answers to common questions about this code of conduct, see the FAQ at
198 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
199 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Hakan Akin
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 📱 React Native Responsive Pixels
2 |
3 |
4 |
5 |
6 | [](https://www.npmjs.com/package/react-native-responsive-pixels)
7 |
8 | [](https://www.npmjs.com/package/react-native-responsive-pixels) [](https://www.npmjs.com/package/react-native-responsive-pixels)  [](https://opensource.org/licenses/MIT)
9 |
10 | # Contents
11 | * [Description](#description)
12 | * [Installation](#installation)
13 | * [Usage](#usage)
14 | * [Example](#example)
15 | * [Author](#author)
16 | * [License](#license)
17 | * [Contribution](#contribution)
18 |
19 | ## Description
20 | This package is created for responsive UI calculations in React Native. If you are using a base device or dimensions to create UI this package can help you.
21 |
22 | E.g. You are creating the UI based on the desings that created on iPhone X in Figma.
23 | If you wanted to have same look on all devices, you just need to set base device as iPhone X then use the values on your design.
24 | This package is going to help you about responsive calculations.
25 |
26 | ## Installation
27 | This is a pure JS library so you just need to install npm package. To install this package run the command below on Terminal.
28 |
29 | ```bash
30 | npm install react-native-responsive-pixels --save
31 | ```
32 |
33 | ## Usage
34 | ### Sample Usage
35 | You can just import methods and use it with values.
36 | ```jsx
37 | import React from 'react';
38 | import { convertX, convertY, scaleFont } from 'react-native-responsive-pixels';
39 |
40 | const BASE_WIDTH = 375;
41 | const BASE_HEIGHT = 812;
42 |
43 | const App = () => {
44 | return (
45 |
46 |
47 | Lorem ipsum dolor sit amet.
48 |
49 |
50 | );
51 | };
52 |
53 | export default App;
54 | ```
55 |
56 | ### Recommended Usage
57 | Recommended usage is creating an util file and setting base device's dimensions once. Then using methods from utils file.
58 |
59 | `Util.ts` file 👇
60 | ```jsx
61 | import { convertX, convertY, scaleFont, Devices } from 'react-native-responsive-pixels';
62 |
63 | const BASE_WIDTH = 375;
64 | const BASE_HEIGHT = 812;
65 |
66 | export const getXValue = (value: number) => {
67 | return convertX(value, BASE_WIDTH);
68 | }
69 |
70 | export const getYValue = (value: number) => {
71 | return convertY(value, BASE_HEIGHT);
72 | }
73 |
74 | export const getFontSize = (value: number) => {
75 | return scaleFont(value, BASE_WIDTH);
76 | }
77 | ```
78 |
79 | `App.tsx` file 👇
80 | ```jsx
81 | import React from 'react';
82 | import { convertX, convertY, scaleFont } from './utils.ts';
83 |
84 | const App = () => {
85 | return (
86 |
87 |
88 | Lorem ipsum dolor sit amet.
89 |
90 |
91 | );
92 | };
93 |
94 | export default App;
95 | ```
96 |
97 | ### Using "Devices" Enum
98 | If you don't know your base device's width and height, you can select it from "Devices" enum. It automatically gets base width and height for desired device.
99 |
100 | `Util.ts` file 👇
101 | ```jsx
102 | import { convertX, convertY, scaleFont, Devices } from 'react-native-responsive-pixels';
103 |
104 | export const getXValue = (value: number) => {
105 | return convertX(value, Devices.iPhoneX);
106 | }
107 |
108 | export const getYValue = (value: number) => {
109 | return convertY(value, Devices.iPhoneX);
110 | }
111 |
112 | export const getFontSize = (value: number) => {
113 | return scaleFont(value, Devices.iPhoneX);
114 | }
115 | ```
116 |
117 | Then you can import and use this methods.
118 |
119 | ## Example
120 | You can find the an example in [example](https://github.com/hknakn/react-native-responsive-pixels/tree/master/example) folder.
121 |
122 | Here is some looks for same app on different sizes 👇
123 |
124 |
125 |
126 |
127 |
128 |
129 | ## Author
130 | [Hakan Akın](https://github.com/hknakn) - cehakanakin@gmail.com
131 |
132 | ## License
133 | React Native Pixels Library is available under the MIT license. See the LICENSE file for more info.
134 |
135 | ## Contribution
136 | Pull requests are welcome! Please create PR to `development` branch.
137 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/devices.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hknakn/react-native-responsive-pixels/bca05fcc9ce318486d100ac691dcaddc0eb82070/devices.png
--------------------------------------------------------------------------------
/example-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hknakn/react-native-responsive-pixels/bca05fcc9ce318486d100ac691dcaddc0eb82070/example-1.png
--------------------------------------------------------------------------------
/example-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hknakn/react-native-responsive-pixels/bca05fcc9ce318486d100ac691dcaddc0eb82070/example-2.png
--------------------------------------------------------------------------------
/example-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hknakn/react-native-responsive-pixels/bca05fcc9ce318486d100ac691dcaddc0eb82070/example-3.png
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-responsive-pixels-example",
3 | "displayName": "ResponsivePixels Example",
4 | "expo": {
5 | "name": "react-native-responsive-pixels-example",
6 | "slug": "react-native-responsive-pixels-example",
7 | "description": "Example app for react-native-responsive-pixels",
8 | "privacy": "public",
9 | "version": "1.0.0",
10 | "platforms": [
11 | "ios",
12 | "android",
13 | "web"
14 | ],
15 | "ios": {
16 | "supportsTablet": true
17 | },
18 | "assetBundlePatterns": [
19 | "**/*"
20 | ]
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const pak = require('../package.json');
3 |
4 | module.exports = function (api) {
5 | api.cache(true);
6 |
7 | return {
8 | presets: ['babel-preset-expo'],
9 | plugins: [
10 | [
11 | 'module-resolver',
12 | {
13 | extensions: ['.tsx', '.ts', '.js', '.json'],
14 | alias: {
15 | // For development, we want to alias the library to the source
16 | [pak.name]: path.join(__dirname, '..', pak.source),
17 | },
18 | },
19 | ],
20 | ],
21 | };
22 | };
23 |
--------------------------------------------------------------------------------
/example/index.js:
--------------------------------------------------------------------------------
1 | import { registerRootComponent } from 'expo';
2 |
3 | import App from './src/App';
4 |
5 | // registerRootComponent calls AppRegistry.registerComponent('main', () => App);
6 | // It also ensures that whether you load the app in the Expo client or in a native build,
7 | // the environment is set up appropriately
8 | registerRootComponent(App);
9 |
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const blacklist = require('metro-config/src/defaults/blacklist');
3 | const escape = require('escape-string-regexp');
4 | const pak = require('../package.json');
5 |
6 | const root = path.resolve(__dirname, '..');
7 |
8 | const modules = Object.keys({
9 | ...pak.peerDependencies,
10 | });
11 |
12 | module.exports = {
13 | projectRoot: __dirname,
14 | watchFolders: [root],
15 |
16 | // We need to make sure that only one version is loaded for peerDependencies
17 | // So we blacklist them at the root, and alias them to the versions in example's node_modules
18 | resolver: {
19 | blacklistRE: blacklist(
20 | modules.map(
21 | (m) =>
22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
23 | )
24 | ),
25 |
26 | extraNodeModules: modules.reduce((acc, name) => {
27 | acc[name] = path.join(__dirname, 'node_modules', name);
28 | return acc;
29 | }, {}),
30 | },
31 |
32 | transformer: {
33 | getTransformOptions: async () => ({
34 | transform: {
35 | experimentalImportSupport: false,
36 | inlineRequires: true,
37 | },
38 | }),
39 | },
40 | };
41 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-responsive-pixels-example",
3 | "description": "Example app for react-native-responsive-pixels",
4 | "version": "0.0.1",
5 | "private": true,
6 | "main": "index",
7 | "scripts": {
8 | "android": "expo start --android",
9 | "ios": "expo start --ios",
10 | "web": "expo start --web",
11 | "start": "expo start",
12 | "test": "jest"
13 | },
14 | "dependencies": {
15 | "expo": "^42.0.0",
16 | "expo-splash-screen": "~0.11.2",
17 | "react": "16.13.1",
18 | "react-dom": "16.13.1",
19 | "react-native": "0.63.4",
20 | "react-native-unimodules": "~0.14.5",
21 | "react-native-web": "~0.13.12"
22 | },
23 | "devDependencies": {
24 | "@babel/core": "~7.9.0",
25 | "@babel/runtime": "^7.9.6",
26 | "babel-plugin-module-resolver": "^4.0.0",
27 | "babel-preset-expo": "8.3.0",
28 | "expo-cli": "^4.0.13"
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { StyleSheet, View, Text } from 'react-native';
3 | import { convertX, convertY, scaleFont } from 'react-native-responsive-pixels';
4 |
5 | const BASE_WIDTH = 375;
6 | const BASE_HEIGHT = 812;
7 |
8 | const App = () => {
9 | return (
10 |
11 |
12 | Hakan Akin
13 |
14 |
15 | Senior React Native Developer
16 |
17 |
18 | );
19 | }
20 |
21 | const styles = StyleSheet.create({
22 | container: {
23 | width: convertX(375, BASE_WIDTH),
24 | height: convertY(812, BASE_HEIGHT),
25 | backgroundColor: '#123155',
26 | justifyContent: 'center',
27 | alignItems: 'center',
28 | },
29 | title: {
30 | fontSize: scaleFont(22, BASE_WIDTH),
31 | color: 'white',
32 | },
33 | description: {
34 | fontSize: scaleFont(18, BASE_WIDTH),
35 | marginTop: convertY(15),
36 | color: 'white',
37 | }
38 | });
39 |
40 | export default App;
--------------------------------------------------------------------------------
/example/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {},
3 | "extends": "expo/tsconfig.base"
4 | }
5 |
--------------------------------------------------------------------------------
/example/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const createExpoWebpackConfigAsync = require('@expo/webpack-config');
3 | const { resolver } = require('./metro.config');
4 |
5 | const root = path.resolve(__dirname, '..');
6 | const node_modules = path.join(__dirname, 'node_modules');
7 |
8 | module.exports = async function (env, argv) {
9 | const config = await createExpoWebpackConfigAsync(env, argv);
10 |
11 | config.module.rules.push({
12 | test: /\.(js|jsx|ts|tsx)$/,
13 | include: path.resolve(root, 'src'),
14 | use: 'babel-loader',
15 | });
16 |
17 | // We need to make sure that only one version is loaded for peerDependencies
18 | // So we alias them to the versions in example's node_modules
19 | Object.assign(config.resolve.alias, {
20 | ...resolver.extraNodeModules,
21 | 'react-native-web': path.join(node_modules, 'react-native-web'),
22 | });
23 |
24 | return config;
25 | };
26 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-responsive-pixels",
3 | "version": "0.3.0",
4 | "description": "React Native package to make responsive calculations.",
5 | "main": "lib/commonjs/index",
6 | "module": "lib/module/index",
7 | "types": "lib/typescript/index.d.ts",
8 | "react-native": "src/index",
9 | "source": "src/index",
10 | "files": [
11 | "src",
12 | "lib",
13 | "android",
14 | "ios",
15 | "cpp",
16 | "react-native-responsive-pixels.podspec",
17 | "!lib/typescript/example",
18 | "!android/build",
19 | "!ios/build",
20 | "!**/__tests__",
21 | "!**/__fixtures__",
22 | "!**/__mocks__"
23 | ],
24 | "scripts": {
25 | "test": "jest",
26 | "typescript": "tsc --noEmit",
27 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
28 | "prepare": "bob build",
29 | "release": "release-it",
30 | "example": "yarn --cwd example",
31 | "pods": "cd example && pod-install --quiet",
32 | "bootstrap": "yarn example && yarn && yarn pods"
33 | },
34 | "keywords": [
35 | "react-native",
36 | "ios",
37 | "android"
38 | ],
39 | "repository": "https://github.com/hknakn/react-native-responsive-pixels",
40 | "author": "Hakan Akin (https://github.com/hknakn)",
41 | "license": "MIT",
42 | "bugs": {
43 | "url": "https://github.com/hknakn/react-native-responsive-pixels/issues"
44 | },
45 | "homepage": "https://github.com/hknakn/react-native-responsive-pixels#readme",
46 | "publishConfig": {
47 | "registry": "https://registry.npmjs.org/"
48 | },
49 | "devDependencies": {
50 | "@commitlint/config-conventional": "^11.0.0",
51 | "@react-native-community/eslint-config": "^2.0.0",
52 | "@release-it/conventional-changelog": "^2.0.0",
53 | "@types/jest": "^26.0.0",
54 | "@types/react": "^16.9.19",
55 | "@types/react-native": "0.62.13",
56 | "commitlint": "^11.0.0",
57 | "eslint": "^7.2.0",
58 | "eslint-config-prettier": "^7.0.0",
59 | "eslint-plugin-prettier": "^3.1.3",
60 | "husky": "^6.0.0",
61 | "jest": "^26.0.1",
62 | "pod-install": "^0.1.0",
63 | "prettier": "^2.0.5",
64 | "react": "16.13.1",
65 | "react-native": "0.63.4",
66 | "react-native-builder-bob": "^0.18.0",
67 | "release-it": "^14.2.2",
68 | "typescript": "^4.1.3"
69 | },
70 | "peerDependencies": {
71 | "react": "*",
72 | "react-native": "*"
73 | },
74 | "jest": {
75 | "preset": "react-native",
76 | "modulePathIgnorePatterns": [
77 | "/example/node_modules",
78 | "/lib/"
79 | ]
80 | },
81 | "commitlint": {
82 | "extends": [
83 | "@commitlint/config-conventional"
84 | ]
85 | },
86 | "release-it": {
87 | "git": {
88 | "commitMessage": "chore: release ${version}",
89 | "tagName": "v${version}"
90 | },
91 | "npm": {
92 | "publish": true
93 | },
94 | "github": {
95 | "release": true
96 | },
97 | "plugins": {
98 | "@release-it/conventional-changelog": {
99 | "preset": "angular"
100 | }
101 | }
102 | },
103 | "eslintConfig": {
104 | "root": true,
105 | "extends": [
106 | "@react-native-community",
107 | "prettier"
108 | ],
109 | "rules": {
110 | "prettier/prettier": [
111 | "error",
112 | {
113 | "quoteProps": "consistent",
114 | "singleQuote": true,
115 | "tabWidth": 2,
116 | "trailingComma": "es5",
117 | "useTabs": false
118 | }
119 | ]
120 | }
121 | },
122 | "eslintIgnore": [
123 | "node_modules/",
124 | "lib/"
125 | ],
126 | "prettier": {
127 | "quoteProps": "consistent",
128 | "singleQuote": true,
129 | "tabWidth": 2,
130 | "trailingComma": "es5",
131 | "useTabs": false
132 | },
133 | "react-native-builder-bob": {
134 | "source": "src",
135 | "output": "lib",
136 | "targets": [
137 | "commonjs",
138 | "module",
139 | [
140 | "typescript",
141 | {
142 | "project": "tsconfig.build.json"
143 | }
144 | ]
145 | ]
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/scripts/bootstrap.js:
--------------------------------------------------------------------------------
1 | const os = require('os');
2 | const path = require('path');
3 | const child_process = require('child_process');
4 |
5 | const root = path.resolve(__dirname, '..');
6 | const args = process.argv.slice(2);
7 | const options = {
8 | cwd: process.cwd(),
9 | env: process.env,
10 | stdio: 'inherit',
11 | encoding: 'utf-8',
12 | };
13 |
14 | if (os.type() === 'Windows_NT') {
15 | options.shell = true
16 | }
17 |
18 | let result;
19 |
20 | if (process.cwd() !== root || args.length) {
21 | // We're not in the root of the project, or additional arguments were passed
22 | // In this case, forward the command to `yarn`
23 | result = child_process.spawnSync('yarn', args, options);
24 | } else {
25 | // If `yarn` is run without arguments, perform bootstrap
26 | result = child_process.spawnSync('yarn', ['bootstrap'], options);
27 | }
28 |
29 | process.exitCode = result.status;
30 |
--------------------------------------------------------------------------------
/src/__tests__/index.test.tsx:
--------------------------------------------------------------------------------
1 | it.todo('write a test');
2 |
--------------------------------------------------------------------------------
/src/devices.ts:
--------------------------------------------------------------------------------
1 | export enum Devices {
2 | iPhone6 = 'iPhone 6',
3 | iPhone6Plus = 'iPhone 6 Plus',
4 | iPhone6s = 'iPhone 6s',
5 | iPhone6sPlus = 'iPhone 6s Plus',
6 | iPhoneX = 'iPhone X',
7 | iPhoneSE1stGen = 'iPhone SE 1st gen',
8 | iPhone7 = 'iPhone 7',
9 | iPhone7Plus = 'iPhone 7 Plus',
10 | iPhone8 = 'iPhone 8',
11 | iPhone8Plus = 'iPhone 8 Plus',
12 | iPhoneXS = 'iPhone XS',
13 | iPhoneXSMax = 'iPhone XS Max',
14 | iPhoneXR = 'iPhone XR',
15 | iPhone11 = 'iPhone 11',
16 | iPhone11Pro = 'iPhone 11 Pro',
17 | iPhone11ProMax = 'iPhone 11 Pro Max',
18 | iPhoneSE2ndGen = 'iPhone SE 2nd gen',
19 | iPhone12Pro = 'iPhone 12 Pro',
20 | iPhone12ProMax = 'iPhone 12 Pro Max',
21 | iPhone12Mini = 'iPhone 12 mini',
22 | iPhone12 = 'iPhone 12',
23 | iPhone13Pro = 'iPhone 13 Pro',
24 | iPhone13ProMax = 'iPhone 13 Pro Max',
25 | iPhone13Mini = 'iPhone 13 mini',
26 | iPhone13 = 'iPhone 13',
27 | }
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import { Dimensions, PixelRatio, Platform } from 'react-native';
2 | import { Devices } from './devices';
3 | import { getDeviceSize } from './utils';
4 |
5 | const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window');
6 |
7 | // Default guideline sizes are based on iPhone X screen size
8 |
9 | /**
10 | * Calculates value for x axis depends on base device.
11 | * @param {number} "value" parameter represents the number in x axis on your base device.
12 | * @param {number | Devices} "base" parameter can get "number" type or value in "Devices". It represents the width of base device.
13 | * @return {number} Calculated value for x axis depends on base device.
14 | */
15 | export const convertX = (value: number, base: number | Devices = 375): number => {
16 | let calculatedValue: number = value;
17 |
18 | // Checking if base is a number or a device name
19 | if (typeof base === 'number') {
20 | calculatedValue = (SCREEN_WIDTH / base) * value;
21 | } else if (Object.values(Devices).includes(base)) {
22 | calculatedValue = (SCREEN_WIDTH / getDeviceSize(base).width) * value;
23 | }
24 |
25 | return calculatedValue;
26 | };
27 |
28 | /**
29 | * Calculates value for x axis depends on base device.
30 | * @param {number} "value" parameter represents the number in y axis on your base device.
31 | * @param {number | Devices} "base" parameter can get "number" type or value in "Devices". It represents the height of base device.
32 | * @return {number} Calculated value for y axis depends on base device.
33 | */
34 | export const convertY = (value: number, base: number | Devices = 812): number => {
35 | let calculatedValue: number = value;
36 |
37 | // Checking if base is a number or a device name
38 | if (typeof base === 'number') {
39 | calculatedValue = (SCREEN_HEIGHT / base) * value;
40 | } else if (Object.values(Devices).includes(base)) {
41 | calculatedValue = (SCREEN_HEIGHT / getDeviceSize(base).height) * value;
42 | }
43 |
44 | return calculatedValue;
45 | };
46 |
47 | /**
48 | * Calculates value for font size depends on base device.
49 | * @param {number} "size" parameter represents the number in font size on your base device.
50 | * @param {number | Devices} "base" parameter can get "number" type or value in "Devices". It represents the width of base device.
51 | * @return {number} Calculated value for font size depends on base device.
52 | */
53 | export const scaleFont = (size: number, base: number | Devices): number => {
54 | let scale: number = 375;
55 | let newSize: number = size / scale;
56 |
57 | // Checking if base is a number or a device name
58 | if (typeof base === 'number') {
59 | scale = SCREEN_WIDTH / base;
60 | newSize = size * scale;
61 | } else if (Object.values(Devices).includes(base)) {
62 | scale = SCREEN_WIDTH / getDeviceSize(base).width;
63 | newSize = size * scale;
64 | }
65 |
66 | if (Platform.OS === 'ios') {
67 | return Math.round(PixelRatio.roundToNearestPixel(newSize));
68 | } else {
69 | return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2;
70 | }
71 | };
72 |
73 | /**
74 | * Predefined device types.
75 | */
76 | export { Devices as Devices };
77 |
--------------------------------------------------------------------------------
/src/utils.ts:
--------------------------------------------------------------------------------
1 | import { Devices } from "./devices";
2 |
3 | interface DeviceSize {
4 | width: number;
5 | height: number;
6 | }
7 |
8 | export function getDeviceSize(deviceName: Devices): DeviceSize {
9 | let deviceSize: DeviceSize = { width: 375, height: 812 };
10 |
11 | switch (deviceName) {
12 | case Devices.iPhone6:
13 | case Devices.iPhone6s:
14 | case Devices.iPhone7:
15 | case Devices.iPhone8:
16 | case Devices.iPhoneSE2ndGen:
17 | deviceSize = { width: 375, height: 667 };
18 | return deviceSize;
19 | case Devices.iPhone6Plus:
20 | case Devices.iPhone6sPlus:
21 | case Devices.iPhone7Plus:
22 | case Devices.iPhone8Plus:
23 | deviceSize = { width: 476, height: 847 };
24 | return deviceSize;
25 | case Devices.iPhoneSE1stGen:
26 | deviceSize = { width: 320, height: 568 };
27 | return deviceSize;
28 | case Devices.iPhoneX:
29 | case Devices.iPhoneXS:
30 | case Devices.iPhone11Pro:
31 | case Devices.iPhone12Mini:
32 | case Devices.iPhone13Mini:
33 | return deviceSize;
34 | case Devices.iPhoneXSMax:
35 | case Devices.iPhoneXR:
36 | case Devices.iPhone11:
37 | case Devices.iPhone11ProMax:
38 | deviceSize = { width: 414, height: 896 };
39 | return deviceSize;
40 | case Devices.iPhone12Pro:
41 | case Devices.iPhone12:
42 | case Devices.iPhone13Pro:
43 | case Devices.iPhone13:
44 | deviceSize = { width: 390, height: 844 };
45 | return deviceSize;
46 | case Devices.iPhone12ProMax:
47 | case Devices.iPhone13ProMax:
48 | deviceSize = { width: 428, height: 926 };
49 | return deviceSize;
50 | }
51 | }
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 |
2 | {
3 | "extends": "./tsconfig",
4 | "exclude": ["example"]
5 | }
6 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": "./",
4 | "paths": {
5 | "react-native-responsive-pixels": ["./src/index"]
6 | },
7 | "allowUnreachableCode": false,
8 | "allowUnusedLabels": false,
9 | "esModuleInterop": true,
10 | "importsNotUsedAsValues": "error",
11 | "forceConsistentCasingInFileNames": true,
12 | "jsx": "react",
13 | "lib": ["esnext"],
14 | "module": "esnext",
15 | "moduleResolution": "node",
16 | "noFallthroughCasesInSwitch": true,
17 | "noImplicitReturns": true,
18 | "noImplicitUseStrict": false,
19 | "noStrictGenericChecks": false,
20 | "noUnusedLocals": true,
21 | "noUnusedParameters": true,
22 | "resolveJsonModule": true,
23 | "skipLibCheck": true,
24 | "strict": true,
25 | "target": "esnext"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------