├── .babelrc ├── .circleci └── config.yml ├── .eslintrc ├── .flowconfig ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .hound.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── flow-typed └── npm │ ├── gl.js │ └── sinon.js ├── package.json ├── rollup.config.js ├── src ├── __mocks__ │ └── mapbox-gl.js ├── components │ └── Cluster │ │ ├── README.md │ │ ├── index.js │ │ └── index.test.js ├── index.js ├── setupTests.js └── utils │ ├── point.js │ ├── shallowCompareChildren.js │ └── shallowCompareChildren.test.js ├── styleguide.config.js ├── styleguide.setup.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false, 7 | "loose": true 8 | } 9 | ], 10 | "@babel/preset-react", 11 | "@babel/preset-flow" 12 | ], 13 | "plugins": [ 14 | "@babel/plugin-transform-spread", 15 | "@babel/plugin-proposal-class-properties" 16 | ], 17 | "env": { 18 | "test": { 19 | "presets": [ 20 | "@babel/preset-env", 21 | "@babel/preset-react", 22 | "@babel/preset-flow" 23 | ], 24 | "plugins": [ 25 | "@babel/plugin-transform-spread", 26 | "@babel/plugin-proposal-class-properties" 27 | ] 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Javascript Node CircleCI 2.0 configuration file 2 | # Check https://circleci.com/docs/2.0/language-javascript/ for more details 3 | 4 | version: 2 5 | 6 | jobs: 7 | build: 8 | docker: 9 | - image: circleci/node:10 10 | 11 | working_directory: ~/repo 12 | 13 | steps: 14 | - checkout 15 | 16 | # Download and cache dependencies 17 | - restore_cache: 18 | keys: 19 | - v1-dependencies-{{ checksum "package.json" }} 20 | # fallback to using the latest cache if no exact match is found 21 | - v1-dependencies- 22 | 23 | - run: yarn install 24 | 25 | - save_cache: 26 | paths: 27 | - node_modules 28 | key: v1-dependencies-{{ checksum "package.json" }} 29 | 30 | - run: yarn lint 31 | - run: yarn flow 32 | - run: yarn test 33 | - run: yarn test:coverage 34 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "extends": [ 4 | "airbnb", 5 | "plugin:flowtype/recommended", 6 | "prettier", 7 | "prettier/flowtype" 8 | ], 9 | "plugins": [ 10 | "flowtype", 11 | "import", 12 | "react" 13 | ], 14 | "env": { 15 | "browser": true, 16 | "jest": true 17 | }, 18 | "rules": { 19 | "arrow-parens": [ 20 | "warn", 21 | "as-needed", 22 | { 23 | "requireForBlockBody": true 24 | } 25 | ], 26 | "comma-dangle": [ 27 | "error", 28 | "never" 29 | ], 30 | "max-len": [ 31 | "error", 32 | { 33 | "code": 80, 34 | "ignoreStrings": true, 35 | "ignoreUrls": true 36 | } 37 | ], 38 | "no-return-assign": 0, 39 | "no-underscore-dangle": [ 40 | "error", 41 | { 42 | "allowAfterThis": true 43 | } 44 | ], 45 | "react/default-props-match-prop-types": [ 46 | "error", 47 | { 48 | "allowRequiredDefaults": true 49 | } 50 | ], 51 | "react/destructuring-assignment": 0, 52 | "react/prop-types": [ 53 | 1, 54 | { 55 | "skipUndeclared": true 56 | } 57 | ], 58 | "react/sort-comp": [ 59 | 1, 60 | { 61 | "order": [ 62 | "type-annotations", 63 | "static-methods", 64 | "lifecycle", 65 | "everything-else", 66 | "render" 67 | ] 68 | } 69 | ], 70 | "react/jsx-filename-extension": [ 71 | 1, 72 | { 73 | "extensions": [ 74 | ".js" 75 | ] 76 | } 77 | ], 78 | "react/require-default-props": 0, 79 | "import/no-extraneous-dependencies": [ 80 | "error", 81 | { 82 | "devDependencies": true, 83 | "peerDependencies": true 84 | } 85 | ], 86 | "quotes": [ 87 | "error", 88 | "single" 89 | ], 90 | "react/static-property-placement": [ 91 | "error", 92 | "static public field" 93 | ] 94 | } 95 | } -------------------------------------------------------------------------------- /.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | .*/findup/test/fixture/.* 3 | .*/jsonlint-lines-primitives/test/fails/.* 4 | 5 | [include] 6 | 7 | [libs] 8 | ./flow-typed 9 | ./node_modules/mapbox-gl/flow-typed 10 | ./node_modules/mapbox-gl/dist/mapbox-gl.js.flow 11 | 12 | [options] 13 | esproposal.class_static_fields=enable 14 | esproposal.class_instance_fields=enable 15 | 16 | [lints] 17 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Go to '...' 13 | 2. Click on '....' 14 | 3. Scroll down to '....' 15 | 4. See error 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **Desktop (please complete the following information):** 24 | - OS: [e.g. iOS] 25 | - Browser [e.g. chrome, safari] 26 | - Version [e.g. 22] 27 | 28 | **Smartphone (please complete the following information):** 29 | - Device: [e.g. iPhone6] 30 | - OS: [e.g. iOS8.1] 31 | - Browser [e.g. stock browser, safari] 32 | - Version [e.g. 22] 33 | 34 | **Additional context** 35 | Add any other context about the problem here. 36 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # build 4 | /dist 5 | 6 | # dependencies 7 | /node_modules 8 | 9 | # docs 10 | /styleguide 11 | 12 | # testing 13 | /coverage 14 | /flow-coverage 15 | 16 | # misc 17 | .env 18 | .DS_Store 19 | .env.local 20 | .env.development.local 21 | .env.test.local 22 | .env.production.local 23 | .idea 24 | 25 | npm-debug.log* 26 | yarn-debug.log* 27 | yarn-error.log* 28 | -------------------------------------------------------------------------------- /.hound.yml: -------------------------------------------------------------------------------- 1 | eslint: 2 | enabled: true 3 | config_file: .eslintrc 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ## [0.2.0](https://github.com/urbica/react-map-gl-cluster/compare/v0.1.0...v0.2.0) (2019-10-24) 6 | 7 | 8 | ### Features 9 | 10 | * add map and reduce props according supercluster api ([916a4f0](https://github.com/urbica/react-map-gl-cluster/commit/916a4f08a41148825c53ad507a3a31d45a2cbc39)) 11 | * add map and reduce props according supercluster api [#25](https://github.com/urbica/react-map-gl-cluster/issues/25) (h/t (Akiyamka)[https://github.com/Akiyamka]) ([a6e37d7](https://github.com/urbica/react-map-gl-cluster/commit/a6e37d71e7ad6d4678889a06c9c4980facafaba6)) 12 | 13 | 14 | ### Bug Fixes 15 | 16 | * ClusterReduceFunction type ([b04cefb](https://github.com/urbica/react-map-gl-cluster/commit/b04cefb85e51011fce28aa31bbe91805b7a87cdf)) 17 | 18 | # 0.1.0 (2019-03-11) 19 | 20 | 21 | ### Features 22 | 23 | * initial commit ([6a3414b](https://github.com/urbica/react-map-gl-cluster/commit/6a3414b)) 24 | -------------------------------------------------------------------------------- /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 contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hello@urbica.co. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Urbica Design 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 | # Urbica React Mapbox GL Cluster 2 | 3 | [![Build Status](https://img.shields.io/circleci/project/github/urbica/react-map-gl-cluster.svg?style=popout)](https://circleci.com/gh/urbica/react-map-gl-cluster) 4 | ![npm](https://img.shields.io/npm/dt/@urbica/react-map-gl-cluster.svg) 5 | ![npm](https://img.shields.io/npm/v/@urbica/react-map-gl-cluster.svg) 6 | 7 | Cluster component for [Urbica React Components Library for Mapbox GL JS](https://github.com/urbica/react-map-gl). 8 | 9 | ## Installation 10 | 11 | ```shell 12 | npm install mapbox-gl supercluster @urbica/react-map-gl @urbica/react-map-gl-cluster 13 | ``` 14 | 15 | ...or if you are using yarn: 16 | 17 | ```shell 18 | yarn add mapbox-gl supercluster @urbica/react-map-gl @urbica/react-map-gl-cluster 19 | ``` 20 | 21 | ## Usage 22 | 23 | ```jsx 24 | import { randomPoint } from '@turf/random'; 25 | import MapGL, { Marker } from '@urbica/react-map-gl'; 26 | import Cluster from '@urbica/react-map-gl-cluster'; 27 | import 'mapbox-gl/dist/mapbox-gl.css'; 28 | 29 | const bbox = [-160, -70, 160, 70]; 30 | const points = randomPoint(50, { bbox }).features; 31 | points.forEach((point, index) => (point.id = index)); 32 | 33 | initialState = { 34 | viewport: { 35 | latitude: 0, 36 | longitude: 0, 37 | zoom: 0 38 | } 39 | }; 40 | 41 | const style = { 42 | width: '20px', 43 | height: '20px', 44 | color: '#fff', 45 | background: '#1978c8', 46 | borderRadius: '20px', 47 | textAlign: 'center' 48 | }; 49 | 50 | const ClusterMarker = ({ longitude, latitude, pointCount }) => ( 51 | 52 |
{pointCount}
53 |
54 | ); 55 | 56 | setState({ viewport })} 61 | {...state.viewport} 62 | > 63 | 64 | {points.map(point => ( 65 | 70 |
71 | 72 | ))} 73 | 74 | ; 75 | ``` 76 | -------------------------------------------------------------------------------- /flow-typed/npm/gl.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | declare module 'gl' { 4 | declare export default Function; 5 | } 6 | -------------------------------------------------------------------------------- /flow-typed/npm/sinon.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | declare module 'sinon' { 4 | declare export default Function; 5 | } 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@urbica/react-map-gl-cluster", 3 | "version": "0.2.0", 4 | "description": "React Cluster Component for Mapbox GL JS", 5 | "author": "Stepan Kuzmin (stepankuzmin.com)", 6 | "license": "MIT", 7 | "repository": { 8 | "type": "git", 9 | "url": "git://github.com/urbica/react-map-gl-cluster.git" 10 | }, 11 | "publishConfig": { 12 | "access": "public" 13 | }, 14 | "main": "dist/react-map-gl-cluster.cjs.js", 15 | "module": "dist/react-map-gl-cluster.esm.js", 16 | "files": [ 17 | "dist" 18 | ], 19 | "scripts": { 20 | "start": "styleguidist server", 21 | "lint": "eslint src", 22 | "test": "jest test", 23 | "test:coverage": "jest test --coverage && codecov", 24 | "flow": "flow check", 25 | "flow:coverage": "flow-coverage-report -i 'src/**/*.js' -x 'src/setupTests.js' -x 'src/__mocks__/*' -x 'src/**/*.test.js' -t html", 26 | "build": "rollup -c", 27 | "build:watch": "rollup -c -w", 28 | "format": "prettier-eslint --write \"src/**/*.js\"", 29 | "cz": "git-cz", 30 | "release": "npm run build && standard-version", 31 | "prepublishOnly": "npm run build", 32 | "styleguide:build": "styleguidist build", 33 | "styleguide:deploy": "gh-pages -m 'auto commit [ci skip]' -d styleguide", 34 | "postpublish": "npm run styleguide:build && npm run styleguide:deploy" 35 | }, 36 | "peerDependencies": { 37 | "@urbica/react-map-gl": "^1.0.0-alpha", 38 | "supercluster": "^6.0.0" 39 | }, 40 | "devDependencies": { 41 | "@babel/core": "^7.9.0", 42 | "@babel/plugin-proposal-class-properties": "^7.8.3", 43 | "@babel/plugin-transform-spread": "^7.8.3", 44 | "@babel/preset-env": "^7.9.0", 45 | "@babel/preset-flow": "^7.9.0", 46 | "@babel/preset-react": "^7.9.4", 47 | "@turf/random": "^6.0.2", 48 | "@urbica/react-map-gl": "^1.13.0", 49 | "babel-eslint": "^10.1.0", 50 | "babel-loader": "^8.1.0", 51 | "codecov": "^3.6.1", 52 | "commitizen": "^4.0.3", 53 | "css-loader": "^3.4.2", 54 | "cz-conventional-changelog": "^3.1.0", 55 | "enzyme": "^3.11.0", 56 | "enzyme-adapter-react-16": "^1.15.2", 57 | "eslint": "^6.8.0", 58 | "eslint-config-airbnb": "^18.1.0", 59 | "eslint-config-prettier": "^6.10.1", 60 | "eslint-plugin-flowtype": "^4.7.0", 61 | "eslint-plugin-import": "^2.20.1", 62 | "eslint-plugin-jsx-a11y": "^6.2.3", 63 | "eslint-plugin-react": "^7.19.0", 64 | "flow-bin": "^0.108.0", 65 | "flow-coverage-report": "^0.6.1", 66 | "flow-remove-types": "^2.121.0", 67 | "gh-pages": "^2.2.0", 68 | "husky": "^3.0.9", 69 | "jest": "^24.9.0", 70 | "lint-staged": "^9.4.2", 71 | "mapbox-gl": "^1.9.0", 72 | "prettier": "^1.18.2", 73 | "prettier-eslint": "^9.0.1", 74 | "prettier-eslint-cli": "^5.0.0", 75 | "react": "^16.13.1", 76 | "react-dom": "^16.13.1", 77 | "react-styleguidist": "^9.2.0", 78 | "rollup": "^1.25.2", 79 | "rollup-plugin-babel": "^4.4.0", 80 | "rollup-plugin-commonjs": "^10.1.0", 81 | "rollup-plugin-node-resolve": "^5.2.0", 82 | "rollup-plugin-terser": "^5.3.0", 83 | "standard-version": "^8.0.1", 84 | "style-loader": "^1.1.3", 85 | "supercluster": "^6.0.2", 86 | "webpack": "^4.42.1" 87 | }, 88 | "config": { 89 | "commitizen": { 90 | "path": "cz-conventional-changelog" 91 | } 92 | }, 93 | "husky": { 94 | "hooks": { 95 | "pre-commit": "lint-staged" 96 | } 97 | }, 98 | "jest": { 99 | "setupFiles": [ 100 | "/src/setupTests.js" 101 | ] 102 | }, 103 | "lint-staged": { 104 | "*.js": [ 105 | "prettier-eslint --write", 106 | "npm run lint", 107 | "jest --findRelatedTests", 108 | "git add" 109 | ] 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel'; 2 | import commonjs from 'rollup-plugin-commonjs'; 3 | import resolve from 'rollup-plugin-node-resolve'; 4 | import { terser } from 'rollup-plugin-terser'; 5 | import pkg from './package.json'; 6 | 7 | export default { 8 | input: 'src/index.js', 9 | treeshake: true, 10 | output: [ 11 | { file: pkg.main, exports: 'named', sourcemap: true, format: 'cjs' }, 12 | { file: pkg.module, sourcemap: true, format: 'esm' } 13 | ], 14 | external: ['react', 'react-dom', '@urbica/react-map-gl', 'supercluster'], 15 | plugins: [resolve(), babel(), commonjs(), terser()] 16 | }; 17 | -------------------------------------------------------------------------------- /src/__mocks__/mapbox-gl.js: -------------------------------------------------------------------------------- 1 | // LngLatBounds 2 | function LngLatBounds() {} 3 | LngLatBounds.prototype.toArray = () => [[-180, -90], [180, 90]]; 4 | 5 | // Map 6 | function Map() { 7 | this._sources = {}; 8 | 9 | this.flyTo = jest.fn(); 10 | this.easeTo = jest.fn(); 11 | this.jumpTo = jest.fn(); 12 | 13 | this.getCanvas = jest.fn(() => ({ style: { cursor: 'default' } })); 14 | this.getCenter = jest.fn(() => ({ lat: 0, lng: 0 })); 15 | this.getBearing = jest.fn(() => 0); 16 | this.getPitch = jest.fn(() => 0); 17 | this.getZoom = jest.fn(() => 0); 18 | this.getStyle = jest.fn(() => {}); 19 | this.queryRenderedFeatures = jest.fn(() => []); 20 | this.setFeatureState = jest.fn(); 21 | this.removeFeatureState = jest.fn(); 22 | 23 | return this; 24 | } 25 | 26 | Map.prototype.once = function once(_, listener, fn) { 27 | const handler = typeof listener === 'function' ? listener : fn; 28 | handler({ target: this }); 29 | }; 30 | 31 | Map.prototype.on = function on(_, listener, fn) { 32 | const handler = typeof listener === 'function' ? listener : fn; 33 | handler({ target: this }); 34 | }; 35 | 36 | Map.prototype.addSource = function addSource(name, source) { 37 | this._sources[name] = source; 38 | }; 39 | 40 | Map.prototype.removeSource = function removeSource(name) { 41 | delete this._sources[name]; 42 | }; 43 | 44 | Map.prototype.remove = jest.fn(); 45 | Map.prototype.addLayer = jest.fn(); 46 | Map.prototype.getLayer = jest.fn(); 47 | Map.prototype.removeLayer = jest.fn(); 48 | Map.prototype.addControl = jest.fn(); 49 | Map.prototype.removeControl = jest.fn(); 50 | Map.prototype.fire = jest.fn(); 51 | 52 | Map.prototype.getBounds = () => new LngLatBounds(); 53 | 54 | function Popup() { 55 | this.setLngLat = jest.fn(() => this); 56 | this.addTo = jest.fn(() => this); 57 | this.setDOMContent = jest.fn(() => this); 58 | return this; 59 | } 60 | 61 | function Marker() { 62 | this.setLngLat = jest.fn(() => this); 63 | this.addTo = jest.fn(() => this); 64 | return this; 65 | } 66 | 67 | function AttributionControl() { 68 | return this; 69 | } 70 | 71 | function FullscreenControl() { 72 | return this; 73 | } 74 | 75 | function GeolocateControl() { 76 | return this; 77 | } 78 | 79 | function NavigationControl() { 80 | return this; 81 | } 82 | 83 | function ScaleControl() { 84 | return this; 85 | } 86 | 87 | module.exports = { 88 | Map, 89 | Popup, 90 | Marker, 91 | AttributionControl, 92 | FullscreenControl, 93 | GeolocateControl, 94 | NavigationControl, 95 | ScaleControl, 96 | supported: () => true 97 | }; 98 | -------------------------------------------------------------------------------- /src/components/Cluster/README.md: -------------------------------------------------------------------------------- 1 | ## Installation 2 | 3 | This component is companion for [Urbica React Components Library for Mapbox GL JS](https://github.com/urbica/react-map-gl). 4 | 5 | `@urbica/react-map-gl-cluster` requires `mapbox-gl`, `supercluster`, and `@urbica/react-map-gl` as peer dependencies: 6 | 7 | ```shell 8 | npm install mapbox-gl supercluster @urbica/react-map-gl @urbica/react-map-gl-cluster 9 | ``` 10 | 11 | ...or if you are using yarn: 12 | 13 | ```shell 14 | yarn add mapbox-gl supercluster @urbica/react-map-gl @urbica/react-map-gl-cluster 15 | ``` 16 | 17 | ## Basic usage 18 | 19 | ```jsx 20 | import { randomPoint } from '@turf/random'; 21 | import MapGL, { Marker } from '@urbica/react-map-gl'; 22 | import Cluster from '@urbica/react-map-gl-cluster'; 23 | import 'mapbox-gl/dist/mapbox-gl.css'; 24 | 25 | const bbox = [-160, -70, 160, 70]; 26 | const points = randomPoint(50, { bbox }).features; 27 | points.forEach((point, index) => (point.id = index)); 28 | 29 | initialState = { 30 | viewport: { 31 | latitude: 0, 32 | longitude: 0, 33 | zoom: 0 34 | } 35 | }; 36 | 37 | const style = { 38 | width: '20px', 39 | height: '20px', 40 | color: '#fff', 41 | background: '#1978c8', 42 | borderRadius: '20px', 43 | textAlign: 'center' 44 | }; 45 | 46 | const ClusterMarker = ({ longitude, latitude, pointCount }) => ( 47 | 48 |
{pointCount}
49 |
50 | ); 51 | 52 | setState({ viewport })} 57 | {...state.viewport} 58 | > 59 | 60 | {points.map(point => ( 61 | 66 |
67 | 68 | ))} 69 | 70 | ; 71 | ``` 72 | 73 | ### Accessing Supercluster Instance 74 | 75 | You can call `getCluster()` method on the `Cluster` [ref](https://reactjs.org/docs/refs-and-the-dom.html). 76 | 77 | ```jsx 78 | import React from 'react'; 79 | import ReactDOM from 'react-dom'; 80 | import { randomPoint } from '@turf/random'; 81 | import MapGL, { Marker } from '@urbica/react-map-gl'; 82 | import Cluster from '@urbica/react-map-gl-cluster'; 83 | import 'mapbox-gl/dist/mapbox-gl.css'; 84 | 85 | const bbox = [-160, -70, 160, 70]; 86 | const points = randomPoint(50, { bbox }).features; 87 | points.forEach((point, index) => (point.id = index)); 88 | 89 | const style = { 90 | width: '20px', 91 | height: '20px', 92 | color: '#fff', 93 | background: '#1978c8', 94 | borderRadius: '20px', 95 | textAlign: 'center' 96 | }; 97 | 98 | class ClusterMarker extends React.PureComponent { 99 | constructor(props) { 100 | super(props); 101 | this.onClick = this.onClick.bind(this); 102 | } 103 | 104 | onClick() { 105 | const { onClick, ...cluster } = this.props; 106 | onClick(cluster); 107 | } 108 | 109 | render() { 110 | const { longitude, latitude, pointCount } = this.props; 111 | 112 | return ( 113 | 114 |
115 | {pointCount} 116 |
117 |
118 | ); 119 | } 120 | } 121 | 122 | class App extends React.PureComponent { 123 | constructor(props) { 124 | super(props); 125 | 126 | this.state = { 127 | viewport: { 128 | latitude: 0, 129 | longitude: 0, 130 | zoom: 0 131 | } 132 | }; 133 | 134 | this._cluster = React.createRef(); 135 | 136 | this.onClick = this.onClick.bind(this); 137 | this.onViewportChange = this.onViewportChange.bind(this); 138 | } 139 | 140 | onViewportChange(viewport) { 141 | this.setState({ viewport }); 142 | } 143 | 144 | onClick(cluster) { 145 | const { clusterId, longitude, latitude } = cluster; 146 | 147 | const supercluster = this._cluster.current.getCluster(); 148 | const zoom = supercluster.getClusterExpansionZoom(clusterId); 149 | 150 | this.setState(state => { 151 | const newVewport = { 152 | ...state.viewport, 153 | latitude, 154 | longitude, 155 | zoom 156 | }; 157 | 158 | return { ...state, viewport: newVewport }; 159 | }); 160 | } 161 | 162 | render() { 163 | const { viewport } = this.state; 164 | 165 | return ( 166 | 173 | ( 179 | 180 | )} 181 | > 182 | {points.map(point => ( 183 | 188 |
189 | 190 | ))} 191 | 192 | 193 | ); 194 | } 195 | } 196 | 197 | ; 198 | ``` 199 | -------------------------------------------------------------------------------- /src/components/Cluster/index.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | import Supercluster from 'supercluster'; 4 | import { Children, PureComponent, createElement } from 'react'; 5 | import { MapContext } from '@urbica/react-map-gl'; 6 | import type MapboxMap from 'mapbox-gl/src/ui/map'; 7 | 8 | import point from '../../utils/point'; 9 | import shallowCompareChildren from '../../utils/shallowCompareChildren'; 10 | 11 | export type SuperclusterFeature = { 12 | type: 'Feature', 13 | id: number, 14 | properties: { 15 | cluster: true, 16 | cluster_id: number, 17 | point_count: number, 18 | point_count_abbreviated: string | number 19 | }, 20 | geometry: { 21 | type: 'Point', 22 | coordinates: [number, number] 23 | } 24 | }; 25 | 26 | export type ClusterComponentProps = { 27 | longitude: number, 28 | latitude: number, 29 | clusterId: number, 30 | pointCount: number, 31 | pointCountAbbreviated: string | number 32 | }; 33 | 34 | export type ClusterMapFunction = (props: {}) => any; 35 | 36 | export type ClusterReduceFunction = (accumulated: {}, props: {}) => void; 37 | 38 | export type ClusterComponent = React$Component; 39 | 40 | type Props = { 41 | /** Minimum zoom level at which clusters are generated */ 42 | minZoom?: number, 43 | 44 | /** Maximum zoom level at which clusters are generated */ 45 | maxZoom?: number, 46 | 47 | /** Cluster radius, in pixels */ 48 | radius?: number, 49 | 50 | /** (Tiles) Tile extent. Radius is calculated relative to this value */ 51 | extent?: number, 52 | 53 | /** Size of the KD-tree leaf node. Affects performance */ 54 | nodeSize?: number, 55 | 56 | /** 57 | * A function that returns cluster properties 58 | * corresponding to a single point. 59 | * */ 60 | // eslint-disable-next-line react/no-unused-prop-types 61 | map?: ClusterMapFunction, 62 | 63 | /** A reduce function that merges properties of two clusters into one. */ 64 | // eslint-disable-next-line react/no-unused-prop-types 65 | reduce?: ClusterReduceFunction, 66 | 67 | /** React Component for rendering Cluster */ 68 | component: Class, 69 | 70 | /** List of Markers */ 71 | children: React$Node 72 | }; 73 | 74 | type State = { 75 | clusters: Array 76 | }; 77 | 78 | class Cluster extends PureComponent { 79 | _map: MapboxMap; 80 | 81 | _cluster: Object; 82 | 83 | static displayName = 'Cluster'; 84 | 85 | static defaultProps = { 86 | minZoom: 0, 87 | maxZoom: 16, 88 | radius: 40, 89 | extent: 512, 90 | nodeSize: 64 91 | }; 92 | 93 | constructor(props: Props) { 94 | super(props); 95 | 96 | this.state = { 97 | clusters: [] 98 | }; 99 | } 100 | 101 | componentDidMount() { 102 | this._createCluster(this.props); 103 | this._recalculate(); 104 | 105 | this._map.on('moveend', this._recalculate); 106 | } 107 | 108 | componentDidUpdate(prevProps: Props) { 109 | const shouldUpdate = 110 | prevProps.minZoom !== this.props.minZoom || 111 | prevProps.maxZoom !== this.props.maxZoom || 112 | prevProps.radius !== this.props.radius || 113 | prevProps.extent !== this.props.extent || 114 | prevProps.nodeSize !== this.props.nodeSize || 115 | !shallowCompareChildren(prevProps.children, this.props.children); 116 | 117 | if (shouldUpdate) { 118 | this._createCluster(this.props); 119 | this._recalculate(); 120 | } 121 | } 122 | 123 | componentWillUnmount() { 124 | if (!this._map || !this._map.getStyle()) { 125 | return; 126 | } 127 | 128 | this._map.off('moveend', this._recalculate); 129 | } 130 | 131 | getCluster() { 132 | return this._cluster; 133 | } 134 | 135 | _createCluster = (props: Props) => { 136 | const { 137 | minZoom, 138 | maxZoom, 139 | radius, 140 | extent, 141 | nodeSize, 142 | children, 143 | reduce, 144 | map 145 | } = props; 146 | 147 | const cluster = new Supercluster({ 148 | minZoom, 149 | maxZoom, 150 | radius, 151 | extent, 152 | nodeSize, 153 | reduce, 154 | map 155 | }); 156 | 157 | const points = Children.map(children, child => 158 | point([child.props.longitude, child.props.latitude], child) 159 | ); 160 | 161 | cluster.load(points); 162 | this._cluster = cluster; 163 | }; 164 | 165 | _recalculate = () => { 166 | const zoom = this._map.getZoom(); 167 | const bounds = this._map.getBounds().toArray(); 168 | const bbox = bounds[0].concat(bounds[1]); 169 | 170 | const clusters = this._cluster.getClusters(bbox, Math.round(zoom)); 171 | this.setState(() => ({ clusters })); 172 | }; 173 | 174 | _renderCluster = (cluster: SuperclusterFeature) => { 175 | const [longitude, latitude] = cluster.geometry.coordinates; 176 | const { 177 | cluster_id: clusterId, 178 | point_count: pointCount, 179 | point_count_abbreviated: pointCountAbbreviated 180 | } = cluster.properties; 181 | 182 | return createElement(this.props.component, { 183 | longitude, 184 | latitude, 185 | clusterId, 186 | pointCount, 187 | pointCountAbbreviated, 188 | key: `cluster-${cluster.properties.cluster_id}` 189 | }); 190 | }; 191 | 192 | render() { 193 | return createElement(MapContext.Consumer, {}, (map) => { 194 | if (map) { 195 | this._map = map; 196 | } 197 | 198 | if (this.state.clusters.length === 0) { 199 | return null; 200 | } 201 | 202 | const clusters = this.state.clusters.map((cluster) => { 203 | if (cluster.properties.cluster) { 204 | return this._renderCluster(cluster); 205 | } 206 | const { type, key, props } = cluster.properties; 207 | return createElement(type, { key, ...props }); 208 | }); 209 | 210 | return clusters; 211 | }); 212 | } 213 | } 214 | 215 | export default Cluster; 216 | -------------------------------------------------------------------------------- /src/components/Cluster/index.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { mount } from 'enzyme'; 3 | import MapGL, { Marker } from '@urbica/react-map-gl'; 4 | import Cluster from '../..'; 5 | 6 | test('Cluster#render', () => { 7 | const Element = () =>
ok
; 8 | const ClusterComponent = () =>
ok
; 9 | 10 | const wrapper = mount( 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | ); 25 | 26 | expect(wrapper.find('Cluster').exists()).toBe(true); 27 | expect(wrapper.find('ClusterComponent').exists()).toBe(true); 28 | expect(wrapper.find('ClusterComponent')).toHaveLength(1); 29 | 30 | wrapper.unmount(); 31 | expect(wrapper.find('Cluster').exists()).toBe(false); 32 | expect(wrapper.find('ClusterComponent').exists()).toBe(false); 33 | }); 34 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | export { default } from './components/Cluster'; 4 | -------------------------------------------------------------------------------- /src/setupTests.js: -------------------------------------------------------------------------------- 1 | import { configure } from 'enzyme'; 2 | import Adapter from 'enzyme-adapter-react-16'; 3 | 4 | configure({ adapter: new Adapter() }); 5 | 6 | jest.mock('mapbox-gl'); 7 | 8 | global.process.browser = true; 9 | -------------------------------------------------------------------------------- /src/utils/point.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | const point = ( 4 | coordinates: [number, number], 5 | properties: { [string]: any } = {} 6 | ) => ({ 7 | type: 'Feature', 8 | properties, 9 | geometry: { 10 | type: 'Point', 11 | coordinates 12 | } 13 | }); 14 | 15 | export default point; 16 | -------------------------------------------------------------------------------- /src/utils/shallowCompareChildren.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | 3 | import { Children } from 'react'; 4 | import type { Node } from 'react'; 5 | 6 | const childrenKeys = (children: Node): string[] => 7 | Children.toArray(children).map(child => child.key); 8 | 9 | const shallowCompareChildren = ( 10 | prevChildren: Node, 11 | newChildren: Node 12 | ): boolean => { 13 | if (Children.count(prevChildren) !== Children.count(newChildren)) { 14 | return false; 15 | } 16 | 17 | const prevKeys = childrenKeys(prevChildren); 18 | const newKeys = new Set(childrenKeys(newChildren)); 19 | return prevKeys.every(key => newKeys.has(key)); 20 | }; 21 | 22 | export default shallowCompareChildren; 23 | -------------------------------------------------------------------------------- /src/utils/shallowCompareChildren.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import shallowCompareChildren from './shallowCompareChildren'; 4 | 5 | test('shallowCompareChildren#undefined', () => { 6 | const prevChildren = shallow(
    ) 7 | .find('ul') 8 | .children(); 9 | 10 | const newChildren = shallow(
      ) 11 | .find('ul') 12 | .children(); 13 | 14 | expect(shallowCompareChildren(prevChildren, newChildren)).toEqual(true); 15 | }); 16 | 17 | test('diff#one-1', () => { 18 | const prevChildren = shallow( 19 |
        20 |
      • 21 |
      22 | ) 23 | .find('ul') 24 | .children(); 25 | 26 | const newChildren = shallow( 27 |
        28 |
      • 29 |
      30 | ) 31 | .find('ul') 32 | .children(); 33 | 34 | expect(shallowCompareChildren(prevChildren, newChildren)).toEqual(true); 35 | }); 36 | 37 | test('diff#one-2', () => { 38 | const prevChildren = shallow( 39 |
        40 |
      • 41 |
      42 | ) 43 | .find('ul') 44 | .children(); 45 | 46 | const newChildren = shallow( 47 |
        48 |
      • 49 |
      50 | ) 51 | .find('ul') 52 | .children(); 53 | 54 | expect(shallowCompareChildren(prevChildren, newChildren)).toEqual(false); 55 | }); 56 | 57 | test('diff#multiple-1', () => { 58 | const prevChildren = shallow( 59 |
        60 |
      • 61 |
      • 62 |
      • 63 |
      64 | ) 65 | .find('ul') 66 | .children(); 67 | 68 | const newChildren = shallow( 69 |
        70 |
      • 71 |
      • 72 |
      • 73 |
      74 | ) 75 | .find('ul') 76 | .children(); 77 | 78 | expect(shallowCompareChildren(prevChildren, newChildren)).toEqual(true); 79 | }); 80 | 81 | test('diff#multiple-2', () => { 82 | const prevChildren = shallow( 83 |
        84 |
      • 85 |
      • 86 |
      • 87 |
      88 | ) 89 | .find('ul') 90 | .children(); 91 | 92 | const newChildren = shallow( 93 |
        94 |
      • 95 |
      • 96 |
      • 97 |
      98 | ) 99 | .find('ul') 100 | .children(); 101 | 102 | expect(shallowCompareChildren(prevChildren, newChildren)).toEqual(false); 103 | }); 104 | 105 | test('diff#different-count', () => { 106 | const prevChildren = shallow( 107 |
        108 |
      • 109 |
      110 | ) 111 | .find('ul') 112 | .children(); 113 | 114 | const newChildren = shallow( 115 |
        116 |
      • 117 |
      • 118 |
      119 | ) 120 | .find('ul') 121 | .children(); 122 | 123 | expect(shallowCompareChildren(prevChildren, newChildren)).toEqual(false); 124 | }); 125 | -------------------------------------------------------------------------------- /styleguide.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const webpack = require('webpack'); 3 | 4 | module.exports = { 5 | title: 'Urbica React Map GL Cluster', 6 | usageMode: 'expand', 7 | exampleMode: 'expand', 8 | pagePerSection: true, 9 | require: [path.resolve(__dirname, 'styleguide.setup.js')], 10 | moduleAliases: { 11 | '@urbica/react-map-gl-cluster': path.resolve(__dirname, 'src') 12 | }, 13 | webpackConfig: { 14 | module: { 15 | rules: [ 16 | { 17 | test: /\.jsx?$/, 18 | exclude: /node_modules/, 19 | loader: 'babel-loader' 20 | }, 21 | { 22 | test: /\.css$/, 23 | use: ['style-loader', 'css-loader'] 24 | } 25 | ] 26 | } 27 | }, 28 | dangerouslyUpdateWebpackConfig: (webpackConfig) => { 29 | const envPlugin = new webpack.EnvironmentPlugin(['MAPBOX_ACCESS_TOKEN']); 30 | webpackConfig.plugins.push(envPlugin); 31 | return webpackConfig; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /styleguide.setup.js: -------------------------------------------------------------------------------- 1 | import 'mapbox-gl/dist/mapbox-gl.css'; 2 | 3 | global.MAPBOX_ACCESS_TOKEN = process.env.MAPBOX_ACCESS_TOKEN; 4 | --------------------------------------------------------------------------------