├── .nvmrc
├── .watchmanconfig
├── example
├── App.js
├── assets
│ ├── icon.png
│ ├── favicon.png
│ ├── splash.png
│ └── adaptive-icon.png
├── tsconfig.json
├── babel.config.js
├── package.json
├── app.json
├── src
│ └── App.tsx
├── webpack.config.js
└── metro.config.js
├── src
├── __tests__
│ └── index.test.tsx
├── utils
│ ├── index.tsx
│ └── calculations.ts
├── index.tsx
└── components
│ ├── RulerPickerItem.tsx
│ └── RulerPicker.tsx
├── .gitattributes
├── tsconfig.build.json
├── docs
└── preview.gif
├── babel.config.js
├── .yarnrc
├── .editorconfig
├── lefthook.yml
├── .github
├── actions
│ └── setup
│ │ └── action.yml
└── workflows
│ └── ci.yml
├── tsconfig.json
├── scripts
└── bootstrap.js
├── .gitignore
├── LICENSE
├── README.md
├── CONTRIBUTING.md
├── package.json
└── CODE_OF_CONDUCT.md
/.nvmrc:
--------------------------------------------------------------------------------
1 | 16.18.1
2 |
--------------------------------------------------------------------------------
/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/example/App.js:
--------------------------------------------------------------------------------
1 | export { default } from './src/App';
2 |
--------------------------------------------------------------------------------
/src/__tests__/index.test.tsx:
--------------------------------------------------------------------------------
1 | it.todo('write a test');
2 |
--------------------------------------------------------------------------------
/src/utils/index.tsx:
--------------------------------------------------------------------------------
1 | export * from './calculations';
2 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | export * from './components/RulerPicker';
2 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 |
2 | {
3 | "extends": "./tsconfig",
4 | "exclude": ["example"]
5 | }
6 |
--------------------------------------------------------------------------------
/docs/preview.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rnheroes/react-native-ruler-picker/HEAD/docs/preview.gif
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/example/assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rnheroes/react-native-ruler-picker/HEAD/example/assets/icon.png
--------------------------------------------------------------------------------
/example/assets/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rnheroes/react-native-ruler-picker/HEAD/example/assets/favicon.png
--------------------------------------------------------------------------------
/example/assets/splash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rnheroes/react-native-ruler-picker/HEAD/example/assets/splash.png
--------------------------------------------------------------------------------
/.yarnrc:
--------------------------------------------------------------------------------
1 | # Override Yarn command so we can automatically setup the repo on running `yarn`
2 |
3 | yarn-path "scripts/bootstrap.js"
4 |
--------------------------------------------------------------------------------
/example/assets/adaptive-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rnheroes/react-native-ruler-picker/HEAD/example/assets/adaptive-icon.png
--------------------------------------------------------------------------------
/example/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig",
3 | "compilerOptions": {
4 | // Avoid expo-cli auto-generating a tsconfig
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/lefthook.yml:
--------------------------------------------------------------------------------
1 | pre-commit:
2 | parallel: true
3 | commands:
4 | lint:
5 | files: git diff --name-only @{push}
6 | glob: "*.{js,ts,jsx,tsx}"
7 | run: npx eslint {files}
8 | types:
9 | files: git diff --name-only @{push}
10 | glob: "*.{js,ts, jsx, tsx}"
11 | run: npx tsc --noEmit
12 | commit-msg:
13 | parallel: true
14 | commands:
15 | commitlint:
16 | run: npx commitlint --edit
17 |
--------------------------------------------------------------------------------
/src/utils/calculations.ts:
--------------------------------------------------------------------------------
1 | export const calculateCurrentValue = (
2 | scrollPosition: number,
3 | stepWidth: number,
4 | gapBetweenItems: number,
5 | min: number,
6 | max: number,
7 | step: number,
8 | fractionDigits: number
9 | ) => {
10 | const index = Math.round(scrollPosition / (stepWidth + gapBetweenItems));
11 | return Math.min(Math.max(index * step + min, min), max).toFixed(
12 | fractionDigits
13 | );
14 | };
15 |
--------------------------------------------------------------------------------
/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/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "example",
3 | "version": "1.0.0",
4 | "main": "node_modules/expo/AppEntry.js",
5 | "scripts": {
6 | "start": "expo start",
7 | "android": "expo start --android",
8 | "ios": "expo start --ios",
9 | "web": "expo start --web"
10 | },
11 | "dependencies": {
12 | "expo": "~48.0.6",
13 | "expo-status-bar": "~1.4.4",
14 | "react": "18.2.0",
15 | "react-native": "0.71.3",
16 | "react-dom": "18.2.0",
17 | "react-native-web": "~0.18.10"
18 | },
19 | "devDependencies": {
20 | "@babel/core": "^7.20.0",
21 | "babel-plugin-module-resolver": "^4.1.0",
22 | "@expo/webpack-config": "^0.17.2",
23 | "babel-loader": "^8.1.0"
24 | },
25 | "private": true
26 | }
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "name": "example",
4 | "slug": "example",
5 | "version": "1.0.0",
6 | "orientation": "portrait",
7 | "icon": "./assets/icon.png",
8 | "userInterfaceStyle": "light",
9 | "splash": {
10 | "image": "./assets/splash.png",
11 | "resizeMode": "contain",
12 | "backgroundColor": "#ffffff"
13 | },
14 | "assetBundlePatterns": [
15 | "**/*"
16 | ],
17 | "ios": {
18 | "supportsTablet": true
19 | },
20 | "android": {
21 | "adaptiveIcon": {
22 | "foregroundImage": "./assets/adaptive-icon.png",
23 | "backgroundColor": "#ffffff"
24 | }
25 | },
26 | "web": {
27 | "favicon": "./assets/favicon.png"
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/.github/actions/setup/action.yml:
--------------------------------------------------------------------------------
1 | name: Setup
2 | description: Setup Node.js and install dependencies
3 |
4 | runs:
5 | using: composite
6 | steps:
7 | - name: Setup Node.js
8 | uses: actions/setup-node@v3
9 | with:
10 | node-version-file: .nvmrc
11 |
12 | - name: Cache dependencies
13 | id: yarn-cache
14 | uses: actions/cache@v3
15 | with:
16 | path: |
17 | **/node_modules
18 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
19 | restore-keys: |
20 | ${{ runner.os }}-yarn-
21 |
22 | - name: Install dependencies
23 | if: steps.yarn-cache.outputs.cache-hit != 'true'
24 | run: |
25 | yarn install --cwd example --frozen-lockfile
26 | yarn install --frozen-lockfile
27 | shell: bash
28 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": "./",
4 | "paths": {
5 | "react-native-ruler-picker": ["./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 | "noUncheckedIndexedAccess": true,
21 | "noUnusedLocals": true,
22 | "noUnusedParameters": true,
23 | "resolveJsonModule": true,
24 | "skipLibCheck": true,
25 | "strict": true,
26 | "target": "esnext"
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | import { StyleSheet, View } from 'react-native';
4 | import { RulerPicker } from 'react-native-ruler-picker';
5 |
6 | export default function App() {
7 | return (
8 |
9 | console.log('onValueChange', number)}
17 | onValueChangeEnd={(number) => console.log('onValueChangeEnd', number)}
18 | />
19 |
20 | );
21 | }
22 |
23 | const styles = StyleSheet.create({
24 | container: {
25 | flex: 1,
26 | justifyContent: 'center',
27 | alignItems: 'center',
28 | },
29 | box: {
30 | width: 60,
31 | height: 60,
32 | marginVertical: 20,
33 | },
34 | });
35 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/.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 | # Ruby
48 | example/vendor/
49 |
50 | # node.js
51 | #
52 | node_modules/
53 | npm-debug.log
54 | yarn-debug.log
55 | yarn-error.log
56 |
57 | # BUCK
58 | buck-out/
59 | \.buckd/
60 | android/app/libs
61 | android/keystores/debug.keystore
62 |
63 | # Expo
64 | .expo/
65 |
66 | # Turborepo
67 | .turbo/
68 |
69 | # generated by bob
70 | lib/
71 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request:
7 | branches:
8 | - main
9 |
10 | jobs:
11 | lint:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - name: Checkout
15 | uses: actions/checkout@v3
16 |
17 | - name: Setup
18 | uses: ./.github/actions/setup
19 |
20 | - name: Lint files
21 | run: yarn lint
22 |
23 | - name: Typecheck files
24 | run: yarn typecheck
25 |
26 | test:
27 | runs-on: ubuntu-latest
28 | steps:
29 | - name: Checkout
30 | uses: actions/checkout@v3
31 |
32 | - name: Setup
33 | uses: ./.github/actions/setup
34 |
35 | - name: Run unit tests
36 | run: yarn test --maxWorkers=2 --coverage
37 |
38 | build:
39 | runs-on: ubuntu-latest
40 | steps:
41 | - name: Checkout
42 | uses: actions/checkout@v3
43 |
44 | - name: Setup
45 | uses: ./.github/actions/setup
46 |
47 | - name: Build package
48 | run: yarn prepack
49 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 React Native Heroes
4 | Permission is hereby granted, free of charge, to any person obtaining a copy
5 | of this software and associated documentation files (the "Software"), to deal
6 | in the Software without restriction, including without limitation the rights
7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the Software is
9 | furnished to do so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in all
12 | copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 | SOFTWARE.
21 |
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const escape = require('escape-string-regexp');
3 | const { getDefaultConfig } = require('@expo/metro-config');
4 | const exclusionList = require('metro-config/src/defaults/exclusionList');
5 | const pak = require('../package.json');
6 |
7 | const root = path.resolve(__dirname, '..');
8 |
9 | const modules = Object.keys({
10 | ...pak.peerDependencies,
11 | });
12 |
13 | const defaultConfig = getDefaultConfig(__dirname);
14 |
15 | module.exports = {
16 | ...defaultConfig,
17 |
18 | projectRoot: __dirname,
19 | watchFolders: [root],
20 |
21 | // We need to make sure that only one version is loaded for peerDependencies
22 | // So we block them at the root, and alias them to the versions in example's node_modules
23 | resolver: {
24 | ...defaultConfig.resolver,
25 |
26 | blacklistRE: exclusionList(
27 | modules.map(
28 | (m) =>
29 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
30 | )
31 | ),
32 |
33 | extraNodeModules: modules.reduce((acc, name) => {
34 | acc[name] = path.join(__dirname, 'node_modules', name);
35 | return acc;
36 | }, {}),
37 | },
38 | };
39 |
--------------------------------------------------------------------------------
/src/components/RulerPickerItem.tsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable react-native/no-inline-styles */
2 | import React from 'react';
3 | import { View } from 'react-native';
4 |
5 | export type RulerPickerItemProps = {
6 | /**
7 | * Gap between steps
8 | *
9 | * @default 10
10 | */
11 | gapBetweenSteps: number;
12 | /**
13 | * Height of the short step
14 | *
15 | * @default 20
16 | */
17 | shortStepHeight: number;
18 | /**
19 | * Height of the long step
20 | *
21 | * @default 40
22 | */
23 | longStepHeight: number;
24 | /**
25 | * Width of the steps
26 | *
27 | * @default 2
28 | */
29 | stepWidth: number;
30 | /**
31 | * Color of the short steps
32 | *
33 | * @default 'lightgray'
34 | */
35 | shortStepColor: string;
36 | /**
37 | * Color of the long steps
38 | *
39 | * @default 'gray'
40 | */
41 | longStepColor: string;
42 | };
43 |
44 | type Props = {
45 | index: number;
46 | isLast: boolean;
47 | } & RulerPickerItemProps;
48 |
49 | export const RulerPickerItem = React.memo(
50 | ({
51 | isLast,
52 | index,
53 | gapBetweenSteps,
54 | shortStepHeight,
55 | longStepHeight,
56 | stepWidth,
57 | shortStepColor,
58 | longStepColor,
59 | }: Props) => {
60 | const isLong = index % 10 === 0;
61 | const height = isLong ? longStepHeight : shortStepHeight;
62 |
63 | return (
64 |
75 |
85 |
86 | );
87 | }
88 | );
89 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-native-ruler-picker
2 |
3 | [](https://www.npmjs.com/package/react-native-ruler-picker) [](http://hits.dwyl.com/rnheroes/react-native-ruler-picker)
4 |
5 | ⚡ Lightning-fast and customizable Ruler Picker component for React Native
6 |
7 | 
8 |
9 | ## Installation
10 |
11 | 1. Ensure sure you've installed [flash-list](https://github.com/Shopify/flash-list)
12 | 2. `yarn add react-native-ruler-picker` or `npm install react-native-ruler-picker`
13 |
14 | ## Usage
15 |
16 | ```js
17 | import { RulerPicker } from 'react-native-ruler-picker';
18 |
19 | console.log(number)}
26 | onValueChangeEnd={(number) => console.log(number)}
27 | unit="cm"
28 | />;
29 | ```
30 |
31 | ## Props
32 |
33 | | Name | Type | Required | Default Value | Description |
34 | | ---------------- | ---------------------------- | -------- | ------------- | ---------------------------------------- |
35 | | width | number | No | windowWidth | Width of the ruler picker |
36 | | height | number | No | 500 | Height of the ruler picker |
37 | | min | number | Yes | - | Minimum value of the ruler picker |
38 | | max | number | Yes | - | Maximum value of the ruler picker |
39 | | step | number | No | 1 | Step of the ruler picker |
40 | | initialValue | number | No | min | Initial value of the ruler picker |
41 | | fractionDigits | number | No | 1 | Number of digits after the decimal point |
42 | | unit | string | No | 'cm' | Unit of the ruler picker |
43 | | indicatorHeight | number | No | 80 | Height of the indicator |
44 | | indicatorColor | string | No | 'black' | Color of the center line |
45 | | valueTextStyle | RulerPickerTextProps | No | - | Text style of the value |
46 | | unitTextStyle | RulerPickerTextProps | No | - | Text style of the unit |
47 | | decelerationRate | 'fast' \| 'normal' \| number | No | 'normal' | Deceleration rate of the ruler picker |
48 | | onValueChange | (value: string) => void | No | - | Callback when the value changes |
49 | | onValueChangeEnd | (value: string) => void | No | - | Callback when the value changes end |
50 | | gapBetweenSteps | number | No | 10 | Gap between steps |
51 | | shortStepHeight | number | No | 20 | Height of the short step |
52 | | longStepHeight | number | No | 40 | Height of the long step |
53 | | stepWidth | number | No | 2 | Width of the steps |
54 | | shortStepColor | string | No | 'lightgray' | Color of the short steps |
55 | | longStepColor | string | No | 'darkgray' | Color of the long steps |
56 |
57 | ## Contributing
58 |
59 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
60 |
61 | ## License
62 |
63 | MIT
64 |
65 | ---
66 |
67 | Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
68 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are always welcome, no matter how large or small!
4 |
5 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. Before contributing, please read the [code of conduct](./CODE_OF_CONDUCT.md).
6 |
7 | ## Development workflow
8 |
9 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
10 |
11 | ```sh
12 | yarn
13 | ```
14 |
15 | > 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.
16 |
17 | 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.
18 |
19 | To start the packager:
20 |
21 | ```sh
22 | yarn example start
23 | ```
24 |
25 | To run the example app on Android:
26 |
27 | ```sh
28 | yarn example android
29 | ```
30 |
31 | To run the example app on iOS:
32 |
33 | ```sh
34 | yarn example ios
35 | ```
36 |
37 | To run the example app on Web:
38 |
39 | ```sh
40 | yarn example web
41 | ```
42 |
43 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
44 |
45 | ```sh
46 | yarn typecheck
47 | yarn lint
48 | ```
49 |
50 | To fix formatting errors, run the following:
51 |
52 | ```sh
53 | yarn lint --fix
54 | ```
55 |
56 | Remember to add tests for your change if possible. Run the unit tests by:
57 |
58 | ```sh
59 | yarn test
60 | ```
61 |
62 |
63 | ### Commit message convention
64 |
65 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
66 |
67 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
68 | - `feat`: new features, e.g. add new method to the module.
69 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
70 | - `docs`: changes into documentation, e.g. add usage example for the module..
71 | - `test`: adding or updating tests, e.g. add integration tests using detox.
72 | - `chore`: tooling changes, e.g. change CI config.
73 |
74 | Our pre-commit hooks verify that your commit message matches this format when committing.
75 |
76 | ### Linting and tests
77 |
78 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
79 |
80 | 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.
81 |
82 | Our pre-commit hooks verify that the linter and tests pass when committing.
83 |
84 | ### Publishing to npm
85 |
86 | 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.
87 |
88 | To publish new versions, run the following:
89 |
90 | ```sh
91 | yarn release
92 | ```
93 |
94 | ### Scripts
95 |
96 | The `package.json` file contains various scripts for common tasks:
97 |
98 | - `yarn bootstrap`: setup project by installing all dependencies and pods.
99 | - `yarn typecheck`: type-check files with TypeScript.
100 | - `yarn lint`: lint files with ESLint.
101 | - `yarn test`: run unit tests with Jest.
102 | - `yarn example start`: start the Metro server for the example app.
103 | - `yarn example android`: run the example app on Android.
104 | - `yarn example ios`: run the example app on iOS.
105 |
106 | ### Sending a pull request
107 |
108 | > **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).
109 |
110 | When you're sending a pull request:
111 |
112 | - Prefer small pull requests focused on one change.
113 | - Verify that linters and tests are passing.
114 | - Review the documentation to make sure it looks good.
115 | - Follow the pull request template when opening a pull request.
116 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
117 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-ruler-picker",
3 | "version": "0.2.2",
4 | "description": "⚡ Lightning-fast and customizable Ruler Picker component for React Native",
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 | "*.podspec",
17 | "!lib/typescript/example",
18 | "!ios/build",
19 | "!android/build",
20 | "!android/gradle",
21 | "!android/gradlew",
22 | "!android/gradlew.bat",
23 | "!android/local.properties",
24 | "!**/__tests__",
25 | "!**/__fixtures__",
26 | "!**/__mocks__",
27 | "!**/.*"
28 | ],
29 | "scripts": {
30 | "test": "jest",
31 | "typecheck": "tsc --noEmit",
32 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
33 | "prepack": "bob build",
34 | "release": "release-it",
35 | "example": "yarn --cwd example",
36 | "bootstrap": "yarn example && yarn install"
37 | },
38 | "keywords": [
39 | "react-native",
40 | "ios",
41 | "android",
42 | "ruler",
43 | "picker",
44 | "react-native-ruler-picker",
45 | "react-native-picker",
46 | "react-native-ruler"
47 | ],
48 | "repository": "https://github.com/rnheroes/react-native-ruler-picker",
49 | "author": "React Native Heroes (https://github.com/rnheroes)",
50 | "license": "MIT",
51 | "bugs": {
52 | "url": "https://github.com/rnheroes/react-native-ruler-picker/issues"
53 | },
54 | "homepage": "https://github.com/rnheroes/react-native-ruler-picker#readme",
55 | "publishConfig": {
56 | "registry": "https://registry.npmjs.org/"
57 | },
58 | "devDependencies": {
59 | "@commitlint/config-conventional": "^17.0.2",
60 | "@evilmartians/lefthook": "^1.2.2",
61 | "@react-native-community/eslint-config": "^3.0.2",
62 | "@release-it/conventional-changelog": "^5.0.0",
63 | "@shopify/flash-list": "^1.4.1",
64 | "@types/jest": "^28.1.2",
65 | "@types/react": "~17.0.21",
66 | "@types/react-native": "0.70.0",
67 | "commitlint": "^17.0.2",
68 | "del-cli": "^5.0.0",
69 | "eslint": "^8.4.1",
70 | "eslint-config-prettier": "^8.5.0",
71 | "eslint-plugin-prettier": "^4.0.0",
72 | "jest": "^28.1.1",
73 | "pod-install": "^0.1.0",
74 | "prettier": "^2.0.5",
75 | "react": "18.2.0",
76 | "react-native": "0.71.3",
77 | "react-native-builder-bob": "^0.20.0",
78 | "release-it": "^15.0.0",
79 | "typescript": "^4.5.2"
80 | },
81 | "resolutions": {
82 | "@types/react": "17.0.21"
83 | },
84 | "peerDependencies": {
85 | "react": "*",
86 | "react-native": "*"
87 | },
88 | "engines": {
89 | "node": ">= 16.0.0"
90 | },
91 | "packageManager": "^yarn@1.22.15",
92 | "jest": {
93 | "preset": "react-native",
94 | "modulePathIgnorePatterns": [
95 | "/example/node_modules",
96 | "/lib/"
97 | ]
98 | },
99 | "commitlint": {
100 | "extends": [
101 | "@commitlint/config-conventional"
102 | ]
103 | },
104 | "release-it": {
105 | "git": {
106 | "commitMessage": "chore: release ${version}",
107 | "tagName": "v${version}"
108 | },
109 | "npm": {
110 | "publish": true
111 | },
112 | "github": {
113 | "release": true
114 | },
115 | "plugins": {
116 | "@release-it/conventional-changelog": {
117 | "preset": "angular"
118 | }
119 | }
120 | },
121 | "eslintConfig": {
122 | "root": true,
123 | "extends": [
124 | "@react-native-community",
125 | "prettier"
126 | ],
127 | "rules": {
128 | "prettier/prettier": [
129 | "error",
130 | {
131 | "quoteProps": "consistent",
132 | "singleQuote": true,
133 | "tabWidth": 2,
134 | "trailingComma": "es5",
135 | "useTabs": false
136 | }
137 | ]
138 | }
139 | },
140 | "eslintIgnore": [
141 | "node_modules/",
142 | "lib/"
143 | ],
144 | "prettier": {
145 | "quoteProps": "consistent",
146 | "singleQuote": true,
147 | "tabWidth": 2,
148 | "trailingComma": "es5",
149 | "useTabs": false
150 | },
151 | "react-native-builder-bob": {
152 | "source": "src",
153 | "output": "lib",
154 | "targets": [
155 | "commonjs",
156 | "module",
157 | [
158 | "typescript",
159 | {
160 | "project": "tsconfig.build.json"
161 | }
162 | ]
163 | ]
164 | },
165 | "dependencies": {}
166 | }
167 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
2 | # Contributor Covenant Code of Conduct
3 |
4 | ## Our Pledge
5 |
6 | We as members, contributors, and leaders pledge to make participation in our
7 | community a harassment-free experience for everyone, regardless of age, body
8 | size, visible or invisible disability, ethnicity, sex characteristics, gender
9 | identity and expression, level of experience, education, socio-economic status,
10 | nationality, personal appearance, race, caste, color, religion, or sexual
11 | identity and orientation.
12 |
13 | We pledge to act and interact in ways that contribute to an open, welcoming,
14 | diverse, inclusive, and healthy community.
15 |
16 | ## Our Standards
17 |
18 | Examples of behavior that contributes to a positive environment for our
19 | community include:
20 |
21 | * Demonstrating empathy and kindness toward other people
22 | * Being respectful of differing opinions, viewpoints, and experiences
23 | * Giving and gracefully accepting constructive feedback
24 | * Accepting responsibility and apologizing to those affected by our mistakes,
25 | and learning from the experience
26 | * Focusing on what is best not just for us as individuals, but for the overall
27 | community
28 |
29 | Examples of unacceptable behavior include:
30 |
31 | * The use of sexualized language or imagery, and sexual attention or advances of
32 | any kind
33 | * Trolling, insulting or derogatory comments, and personal or political attacks
34 | * Public or private harassment
35 | * Publishing others' private information, such as a physical or email address,
36 | without their explicit permission
37 | * Other conduct which could reasonably be considered inappropriate in a
38 | professional setting
39 |
40 | ## Enforcement Responsibilities
41 |
42 | Community leaders are responsible for clarifying and enforcing our standards of
43 | acceptable behavior and will take appropriate and fair corrective action in
44 | response to any behavior that they deem inappropriate, threatening, offensive,
45 | or harmful.
46 |
47 | Community leaders have the right and responsibility to remove, edit, or reject
48 | comments, commits, code, wiki edits, issues, and other contributions that are
49 | not aligned to this Code of Conduct, and will communicate reasons for moderation
50 | decisions when appropriate.
51 |
52 | ## Scope
53 |
54 | This Code of Conduct applies within all community spaces, and also applies when
55 | an individual is officially representing the community in public spaces.
56 | Examples of representing our community include using an official e-mail address,
57 | posting via an official social media account, or acting as an appointed
58 | representative at an online or offline event.
59 |
60 | ## Enforcement
61 |
62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
63 | reported to the community leaders responsible for enforcement at
64 | [INSERT CONTACT METHOD].
65 | All complaints will be reviewed and investigated promptly and fairly.
66 |
67 | All community leaders are obligated to respect the privacy and security of the
68 | reporter of any incident.
69 |
70 | ## Enforcement Guidelines
71 |
72 | Community leaders will follow these Community Impact Guidelines in determining
73 | the consequences for any action they deem in violation of this Code of Conduct:
74 |
75 | ### 1. Correction
76 |
77 | **Community Impact**: Use of inappropriate language or other behavior deemed
78 | unprofessional or unwelcome in the community.
79 |
80 | **Consequence**: A private, written warning from community leaders, providing
81 | clarity around the nature of the violation and an explanation of why the
82 | behavior was inappropriate. A public apology may be requested.
83 |
84 | ### 2. Warning
85 |
86 | **Community Impact**: A violation through a single incident or series of
87 | actions.
88 |
89 | **Consequence**: A warning with consequences for continued behavior. No
90 | interaction with the people involved, including unsolicited interaction with
91 | those enforcing the Code of Conduct, for a specified period of time. This
92 | includes avoiding interactions in community spaces as well as external channels
93 | like social media. Violating these terms may lead to a temporary or permanent
94 | ban.
95 |
96 | ### 3. Temporary Ban
97 |
98 | **Community Impact**: A serious violation of community standards, including
99 | sustained inappropriate behavior.
100 |
101 | **Consequence**: A temporary ban from any sort of interaction or public
102 | communication with the community for a specified period of time. No public or
103 | private interaction with the people involved, including unsolicited interaction
104 | with those enforcing the Code of Conduct, is allowed during this period.
105 | Violating these terms may lead to a permanent ban.
106 |
107 | ### 4. Permanent Ban
108 |
109 | **Community Impact**: Demonstrating a pattern of violation of community
110 | standards, including sustained inappropriate behavior, harassment of an
111 | individual, or aggression toward or disparagement of classes of individuals.
112 |
113 | **Consequence**: A permanent ban from any sort of public interaction within the
114 | community.
115 |
116 | ## Attribution
117 |
118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119 | version 2.1, available at
120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121 |
122 | Community Impact Guidelines were inspired by
123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124 |
125 | For answers to common questions about this code of conduct, see the FAQ at
126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127 | [https://www.contributor-covenant.org/translations][translations].
128 |
129 | [homepage]: https://www.contributor-covenant.org
130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131 | [Mozilla CoC]: https://github.com/mozilla/diversity
132 | [FAQ]: https://www.contributor-covenant.org/faq
133 | [translations]: https://www.contributor-covenant.org/translations
134 |
--------------------------------------------------------------------------------
/src/components/RulerPicker.tsx:
--------------------------------------------------------------------------------
1 | import React, { useCallback, useEffect, useRef } from 'react';
2 | import {
3 | Dimensions,
4 | StyleSheet,
5 | TextStyle,
6 | View,
7 | Text,
8 | Animated,
9 | TextInput,
10 | } from 'react-native';
11 | import type { NativeSyntheticEvent, NativeScrollEvent } from 'react-native';
12 |
13 | import {
14 | AnimatedFlashList,
15 | FlashList,
16 | ListRenderItem,
17 | } from '@shopify/flash-list';
18 |
19 | import { RulerPickerItem, RulerPickerItemProps } from './RulerPickerItem';
20 | import { calculateCurrentValue } from '../utils/';
21 |
22 | export type RulerPickerTextProps = Pick<
23 | TextStyle,
24 | 'color' | 'fontSize' | 'fontWeight'
25 | >;
26 |
27 | const { width: windowWidth } = Dimensions.get('window');
28 |
29 | export type RulerPickerProps = {
30 | /**
31 | * Width of the ruler picker
32 | * @default windowWidth
33 | */
34 | width?: number;
35 | /**
36 | * Height of the ruler picker
37 | * @default 500
38 | */
39 | height?: number;
40 | /**
41 | * Minimum value of the ruler picker
42 | *
43 | * @default 0
44 | */
45 | min: number;
46 | /**
47 | * Maximum value of the ruler picker
48 | *
49 | * @default 240
50 | */
51 | max: number;
52 | /**
53 | * Step of the ruler picker
54 | *
55 | * @default 1
56 | */
57 | step?: number;
58 | /**
59 | * Initial value of the ruler picker
60 | *
61 | * @default min
62 | */
63 | initialValue?: number;
64 | /**
65 | * Number of digits after the decimal point
66 | *
67 | * @default 1
68 | */
69 | fractionDigits?: number;
70 | /**
71 | * Unit of the ruler picker
72 | *
73 | * @default 'cm'
74 | */
75 | unit?: string;
76 | /**
77 | * Height of the indicator
78 | *
79 | * @default 80
80 | */
81 | indicatorHeight?: number;
82 | /**
83 | * Color of the center line
84 | *
85 | * @default 'black'
86 | */
87 | indicatorColor?: string;
88 | /**
89 | * Text style of the value
90 | */
91 | valueTextStyle?: RulerPickerTextProps;
92 | /**
93 | * Text style of the unit
94 | */
95 | unitTextStyle?: RulerPickerTextProps;
96 | /**
97 | * A floating-point number that determines how quickly the scroll view
98 | * decelerates after the user lifts their finger. You may also use string
99 | * shortcuts `"normal"` and `"fast"` which match the underlying iOS settings
100 | * for `UIScrollViewDecelerationRateNormal` and
101 | * `UIScrollViewDecelerationRateFast` respectively.
102 | *
103 | * - `'normal'`: 0.998 on iOS, 0.985 on Android (the default)
104 | * - `'fast'`: 0.99 on iOS, 0.9 on Android
105 | *
106 | * @default 'normal'
107 | */
108 | decelerationRate?: 'fast' | 'normal' | number;
109 | /**
110 | * Callback when the value changes
111 | *
112 | * @param value
113 | */
114 | onValueChange?: (value: string) => void;
115 | /**
116 | * Callback when the value changes end
117 | *
118 | * @param value
119 | */
120 | onValueChangeEnd?: (value: string) => void;
121 | } & Partial;
122 |
123 | export const RulerPicker = ({
124 | width = windowWidth,
125 | height = 500,
126 | min,
127 | max,
128 | step = 1,
129 | initialValue = min,
130 | fractionDigits = 1,
131 | unit = 'cm',
132 | indicatorHeight = 80,
133 | gapBetweenSteps = 10,
134 | shortStepHeight = 20,
135 | longStepHeight = 40,
136 | stepWidth = 2,
137 | indicatorColor = 'black',
138 | shortStepColor = 'lightgray',
139 | longStepColor = 'darkgray',
140 | valueTextStyle,
141 | unitTextStyle,
142 | decelerationRate = 'normal',
143 | onValueChange,
144 | onValueChangeEnd,
145 | }: RulerPickerProps) => {
146 | const itemAmount = (max - min) / step;
147 | const arrData = Array.from({ length: itemAmount + 1 }, (_, index) => index);
148 | const listRef = useRef>(null);
149 |
150 | const stepTextRef = useRef(null);
151 | const prevValue = useRef(initialValue.toFixed(fractionDigits));
152 | const prevMomentumValue = useRef(
153 | initialValue.toFixed(fractionDigits)
154 | );
155 | const scrollPosition = useRef(new Animated.Value(0)).current;
156 |
157 | const valueCallback: Animated.ValueListenerCallback = useCallback(
158 | ({ value }) => {
159 | const newStep = calculateCurrentValue(
160 | value,
161 | stepWidth,
162 | gapBetweenSteps,
163 | min,
164 | max,
165 | step,
166 | fractionDigits
167 | );
168 |
169 | if (prevValue.current !== newStep) {
170 | onValueChange?.(newStep);
171 | stepTextRef.current?.setNativeProps({ text: newStep });
172 | }
173 |
174 | prevValue.current = newStep;
175 | },
176 | [fractionDigits, gapBetweenSteps, stepWidth, max, min, onValueChange, step]
177 | );
178 |
179 | useEffect(() => {
180 | scrollPosition.addListener(valueCallback);
181 |
182 | return () => {
183 | scrollPosition.removeAllListeners();
184 | };
185 | }, [scrollPosition, valueCallback]);
186 |
187 | const scrollHandler = Animated.event(
188 | [
189 | {
190 | nativeEvent: {
191 | contentOffset: {
192 | x: scrollPosition,
193 | },
194 | },
195 | },
196 | ],
197 | {
198 | useNativeDriver: true,
199 | }
200 | );
201 |
202 | const renderSeparator = useCallback(
203 | () => ,
204 | [stepWidth, width]
205 | );
206 |
207 | const renderItem: ListRenderItem = useCallback(
208 | ({ index }) => {
209 | return (
210 |
220 | );
221 | },
222 | [
223 | arrData.length,
224 | gapBetweenSteps,
225 | stepWidth,
226 | longStepColor,
227 | longStepHeight,
228 | shortStepColor,
229 | shortStepHeight,
230 | ]
231 | );
232 |
233 | const onMomentumScrollEnd = useCallback(
234 | (event: NativeSyntheticEvent) => {
235 | const newStep = calculateCurrentValue(
236 | event.nativeEvent.contentOffset.x || event.nativeEvent.contentOffset.y,
237 | stepWidth,
238 | gapBetweenSteps,
239 | min,
240 | max,
241 | step,
242 | fractionDigits
243 | );
244 |
245 | if (prevMomentumValue.current !== newStep) {
246 | onValueChangeEnd?.(newStep);
247 | }
248 |
249 | prevMomentumValue.current = newStep;
250 | },
251 | [
252 | fractionDigits,
253 | gapBetweenSteps,
254 | stepWidth,
255 | max,
256 | min,
257 | onValueChangeEnd,
258 | step,
259 | ]
260 | );
261 | function onContentSizeChange() {
262 | const initialIndex = Math.floor((initialValue - min) / step);
263 | listRef.current?.scrollToOffset({
264 | offset: initialIndex * (stepWidth + gapBetweenSteps),
265 | animated: false,
266 | });
267 | }
268 |
269 | return (
270 |
271 | index.toString()}
275 | renderItem={renderItem}
276 | ListHeaderComponent={renderSeparator}
277 | ListFooterComponent={renderSeparator}
278 | onScroll={scrollHandler}
279 | onMomentumScrollEnd={onMomentumScrollEnd}
280 | estimatedItemSize={stepWidth + gapBetweenSteps}
281 | snapToOffsets={arrData.map(
282 | (_, index) => index * (stepWidth + gapBetweenSteps)
283 | )}
284 | onContentSizeChange={onContentSizeChange}
285 | snapToAlignment="start"
286 | decelerationRate={decelerationRate}
287 | estimatedFirstItemOffset={0}
288 | scrollEventThrottle={16}
289 | showsHorizontalScrollIndicator={false}
290 | showsVerticalScrollIndicator={false}
291 | horizontal
292 | />
293 |
310 |
325 |
337 | {unit && (
338 |
348 | {unit}
349 |
350 | )}
351 |
352 |
361 |
362 |
363 | );
364 | };
365 |
366 | const styles = StyleSheet.create({
367 | indicator: {
368 | position: 'absolute',
369 | top: '50%',
370 | width: '100%',
371 | alignItems: 'center',
372 | },
373 | displayTextContainer: {
374 | width: '100%',
375 | flexDirection: 'row',
376 | alignItems: 'center',
377 | justifyContent: 'center',
378 | },
379 | valueText: {
380 | color: 'black',
381 | fontSize: 32,
382 | fontWeight: '800',
383 | margin: 0,
384 | padding: 0,
385 | },
386 | unitText: {
387 | color: 'black',
388 | fontSize: 24,
389 | fontWeight: '400',
390 | marginLeft: 6,
391 | },
392 | });
393 |
--------------------------------------------------------------------------------