├── .eslintrc ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE.md ├── README.md ├── package-lock.json ├── package.json ├── src └── index.js └── test.js /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "rules": { 4 | "strict": 0 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.log 3 | dist 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 6 4 | cache: 5 | directories: 6 | - node_modules 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.3.0 4 | 5 | - Add `setProjection` to `MapActionCreators` 6 | 7 | ## 0.2.0 8 | 9 | - Add `load` to `MapActionTypes` 10 | - Add Code of Conduct and License 11 | - Add build status badge 12 | - Enable tests 13 | - Update dependencies 14 | 15 | ## 0.1.0 16 | 17 | - Initial release 18 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | education, socio-economic status, nationality, personal appearance, race, 10 | religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2018 Mapbox 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | @mapbox/mapbox-gl-redux 2 | --- 3 | 4 | Tools for building Redux applications with Mapbox GL JS 5 | 6 | [![Build Status](https://travis-ci.com/mapbox/mapbox-gl-redux.svg?token=YkkMPyN1R9p9yTUwpzb5&branch=master)](https://travis-ci.com/mapbox/mapbox-gl-redux) 7 | 8 | --- 9 | 10 | Add middleware to your Redux store and a control to your Mapbox GL JS map to 11 | sync your application state with the map's internally managed state, while 12 | maintaining clean one-way data-flow. 13 | 14 | ## API 15 | 16 | - `ReduxMapControl`: Add this to the Mapbox GL JS map. It subscribes to map 17 | events and dispatches corresponding Redux actions. 18 | - `mapMiddleware`: Add this to the Redux store. When `MapActionCreators` 19 | are used, mapMiddleware will translate those actions into method invocations on 20 | the map. 21 | - `MapActionCreators`: Use these to programmatically change the map's state. 22 | - `bindMapActionCreators`: Returns a set of `MapActionCreators` scoped to a 23 | specific map. 24 | - `MapActionTypes`: Use these in your reducer to identify actions triggered by 25 | map events. 26 | 27 | ## Usage 28 | 29 | Let's say you have a button to zoom out and a display of the map's zoom level. 30 | When you click the zoom out button, the data flow will look like this: 31 | 32 | - A click handler invokes `MapActionCreators.zoomOut()` to create a zoomOut 33 | action. 34 | - `mapMiddleware` detects the zoomOut action and tells the map to zoom out. 35 | - While the map zooms, it fires 'zoom' events that `ReduxMapControl` converts 36 | to actions. 37 | - Your reducer hears of these 'zoom' actions and updates the displayed zoom 38 | level accordingly. 39 | 40 | So: `UI -> click -> action -> map -> map event -> action -> reducer -> UI` 41 | 42 | The `MapActionCreators` correspond to Mapbox GL JS methods, with a few special 43 | cases. You can use them with the same function signature documented for the GL 44 | JS methods. 45 | 46 | The `MapActionTypes` correspond to Mapbox GL JS events, with a few special 47 | cases. Actions of these types will include the following properties: 48 | 49 | - `map`: Use this to gather information about the map, e.g. on 50 | `MapActionTypes.zoom`. You probably want to update your zoom state with the 51 | value from `map.getZoom()`. 52 | - `mapId`: You'll want to ignore the action if it doesn't pertain to your map. 53 | - `event`: The Mapbox GL JS map event type. 54 | - `eventData`: The Mapbox GL JS map event data. 55 | - `type`: The action type. 56 | 57 | If you add a new map action creator or type, please also update the relevant tests and this README. 58 | 59 | ### `MapActionCreators` 60 | 61 | These action creators correspond directly with Mapbox GL JS methods: 62 | 63 | - `setCenter` 64 | - `panBy` 65 | - `panTo` 66 | - `setZoom` 67 | - `zoomTo` 68 | - `zoomOut` 69 | - `zoomIn` 70 | - `setBearing` 71 | - `rotateTo` 72 | - `resetNorth` 73 | - `snapToNorth` 74 | - `setPitch` 75 | - `fitBounds` 76 | - `jumpTo` 77 | - `flyTo` 78 | - `easeTo` 79 | - `stop` 80 | - `setProjection` 81 | 82 | ### Special actions 83 | 84 | There are a few special action creators that do not directly correspond to 85 | Mapbox GL JS map methods. 86 | 87 | #### `sync` 88 | 89 | Dispatch a `MapActionCreators.sync(`) action at any time to give your reducer 90 | an opportunity to sync up with map state. 91 | 92 | When the middleware detects this action it dispatches a `MapActionTypes.sync` 93 | action that you can use in your reducer. 94 | 95 | #### `setShowCollisionBoxes` 96 | 97 | Dispatch `MapActionCreators.setShowCollisionBoxes(true)` to turn on collision 98 | boxes, or `MapActionCreators.setShowCollisionBoxes(false)` to turn them off. 99 | 100 | After the middleware has adjusted the map's setting, it dispatches a 101 | `MapActionTypes.setShowCollisionBoxes` action that you can use in your reducer. 102 | 103 | #### `setShowTileBoundaries` 104 | 105 | Dispatch `MapActionCreators.setShowTileBoundaries(true)` to turn on collision 106 | boxes, or `MapActionCreators.setShowTileBoundaries(false)` to turn them off. 107 | 108 | After the middleware has adjusted the map's setting, it dispatches a 109 | `MapActionTypes.setShowTileBoundaries` action that you can use in your reducer. 110 | 111 | 112 | ### `MapActionTypes` 113 | 114 | These action types correspond directly with Mapbox GL JS events: 115 | 116 | - `move` 117 | - `movestart` 118 | - `moveend` 119 | - `zoom` 120 | - `zoomstart` 121 | - `zoomend` 122 | - `rotate` 123 | - `rotatestart` 124 | - `rotateend` 125 | - `pitch` 126 | - `load` 127 | 128 | These ones correspond with the special action creators described above: 129 | 130 | - `sync` 131 | - `setShowTileBoundaries` 132 | - `setShowCollisionBoxes` 133 | 134 | ## Release 135 | 136 | First, create a [CHANGELOG](./CHANGELOG.md) entry for your release. Commit the entry followed by these commands: 137 | 138 | ``` 139 | npm version {major|minor|patch} 140 | git push 141 | git push --tags 142 | mbx npm publish 143 | ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@mapbox/mapbox-gl-redux", 3 | "version": "0.3.0", 4 | "description": "Tools for building Redux applications with Mapbox GL JS", 5 | "main": "dist/index.js", 6 | "files": [ 7 | "dist" 8 | ], 9 | "scripts": { 10 | "precommit": "lint-staged", 11 | "test": "npm run lint && jest", 12 | "lint": "eslint src test.js", 13 | "prepublishOnly": "npm run build", 14 | "build": "rm -rf dist && babel src -d dist" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/mapbox/mapbox-gl-redux.git" 19 | }, 20 | "author": "Mapbox", 21 | "license": "BSD-2-Clause", 22 | "bugs": { 23 | "url": "https://github.com/mapbox/mapbox-gl-redux/issues" 24 | }, 25 | "babel": { 26 | "presets": [ 27 | "stage-0", 28 | "es2015" 29 | ], 30 | "plugins": [ 31 | "transform-object-rest-spread" 32 | ] 33 | }, 34 | "lint-staged": { 35 | "**/*.js": [ 36 | "eslint", 37 | "prettier --single-quote --write", 38 | "git add" 39 | ] 40 | }, 41 | "homepage": "https://github.com/mapbox/mapbox-gl-redux#readme", 42 | "devDependencies": { 43 | "babel-cli": "^6.26.0", 44 | "babel-eslint": "^8.0.0", 45 | "babel-jest": "^21.0.2", 46 | "babel-plugin-transform-object-rest-spread": "^6.26.0", 47 | "babel-preset-es2015": "^6.24.1", 48 | "babel-preset-stage-0": "^6.24.1", 49 | "eslint": "^4.6.1", 50 | "eventemitter3": "^2.0.3", 51 | "husky": "^0.14.3", 52 | "jest-cli": "^21.1.0", 53 | "lint-staged": "^4.1.3", 54 | "prettier": "^1.7.0" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const mapMethods = [ 4 | 'setCenter', 5 | 'panBy', 6 | 'panTo', 7 | 'setZoom', 8 | 'zoomTo', 9 | 'zoomOut', 10 | 'zoomIn', 11 | 'setBearing', 12 | 'rotateTo', 13 | 'resetNorth', 14 | 'snapToNorth', 15 | 'setPitch', 16 | 'fitBounds', 17 | 'jumpTo', 18 | 'flyTo', 19 | 'easeTo', 20 | 'stop', 21 | 'setProjection' 22 | ]; 23 | 24 | const mapEvents = [ 25 | 'move', 26 | 'movestart', 27 | 'moveend', 28 | 'zoom', 29 | 'zoomstart', 30 | 'zoomend', 31 | 'rotate', 32 | 'rotatestart', 33 | 'rotateend', 34 | 'pitch', 35 | 'load' 36 | ]; 37 | 38 | const ACTION_TYPE_PREFIX = 'mapbox-'; 39 | const SYNC = 'sync'; 40 | const SET_SHOW_COLLISION_BOXES = 'setShowCollisionBoxes'; 41 | const SET_SHOW_TILE_BOUNDARIES = 'setShowTileBoundaries'; 42 | const SET_SHOW_OVERDRAW_INSPECTOR = 'setShowOverdrawInspector'; 43 | 44 | const specialCases = [ 45 | SYNC, 46 | SET_SHOW_COLLISION_BOXES, 47 | SET_SHOW_TILE_BOUNDARIES, 48 | SET_SHOW_OVERDRAW_INSPECTOR 49 | ]; 50 | 51 | const prefixOutgoingActionType = actionType => 52 | `${ACTION_TYPE_PREFIX}${actionType}`; 53 | const prefixInternalActionType = actionType => 54 | `internal-${ACTION_TYPE_PREFIX}${actionType}`; 55 | 56 | const mapMethodsByInternalActionType = mapMethods.reduce((memo, mapMethod) => { 57 | return { ...memo, [prefixInternalActionType(mapMethod)]: mapMethod }; 58 | }, {}); 59 | 60 | export const MapActionTypes = mapEvents 61 | .concat(specialCases) 62 | .reduce((memo, mapEvent) => { 63 | return { ...memo, [mapEvent]: prefixOutgoingActionType(mapEvent) }; 64 | }, {}); 65 | 66 | export const MapActionCreators = mapMethods 67 | .concat(specialCases) 68 | .reduce((memo, mapMethod) => { 69 | memo[mapMethod] = (mapId, ...args) => { 70 | return { 71 | mapId, 72 | args, 73 | type: prefixInternalActionType(mapMethod) 74 | }; 75 | }; 76 | return memo; 77 | }, {}); 78 | 79 | export function bindMapActionCreators(mapId) { 80 | const boundActionCreators = {}; 81 | for (let mapMethod in MapActionCreators) { 82 | if (!MapActionCreators.hasOwnProperty(mapMethod)) continue; 83 | boundActionCreators[mapMethod] = MapActionCreators[mapMethod].bind( 84 | null, 85 | mapId 86 | ); 87 | } 88 | return boundActionCreators; 89 | } 90 | 91 | const registeredMaps = {}; 92 | 93 | let registeredDispatch = () => {}; 94 | 95 | export class ReduxMapControl { 96 | constructor(mapId) { 97 | this.mapId = mapId; 98 | this.MapActionCreators = bindMapActionCreators(mapId); 99 | this._listeners = []; 100 | this.div = null; 101 | } 102 | 103 | onAdd(map) { 104 | const { mapId, _listeners } = this; 105 | registeredMaps[mapId] = map; 106 | this.map = map; 107 | 108 | mapEvents.forEach(mapEvent => { 109 | const listener = eventData => { 110 | registeredDispatch({ 111 | map, 112 | mapId, 113 | eventData, 114 | event: mapEvent, 115 | type: prefixOutgoingActionType(mapEvent) 116 | }); 117 | }; 118 | map.on(mapEvent, listener); 119 | _listeners.push([mapEvent, listener]); 120 | }); 121 | 122 | this.div = document.createElement('div'); 123 | return this.div; 124 | } 125 | 126 | onRemove() { 127 | const { map, mapId, _listeners } = this; 128 | if (!map) return this; 129 | 130 | _listeners.forEach(([mapEvent, listener]) => { 131 | map.off(mapEvent, listener); 132 | }); 133 | delete registeredMaps[mapId]; 134 | 135 | if (this.div && this.div.parentNode) { 136 | this.div.parentNode.removeChild(this.div); 137 | } 138 | this.div = null; 139 | 140 | return this; 141 | } 142 | } 143 | 144 | const syncInternalActionType = prefixInternalActionType(SYNC); 145 | const showCollisionBoxesInternalActionType = prefixInternalActionType( 146 | SET_SHOW_COLLISION_BOXES 147 | ); 148 | const showTileBoundariesInternalActionType = prefixInternalActionType( 149 | SET_SHOW_TILE_BOUNDARIES 150 | ); 151 | const showOverdrawInspectorInternalActionType = prefixInternalActionType( 152 | SET_SHOW_OVERDRAW_INSPECTOR 153 | ); 154 | 155 | export function mapMiddleware({ dispatch }) { 156 | registeredDispatch = dispatch; 157 | 158 | return next => action => { 159 | const map = registeredMaps[action.mapId]; 160 | if (!map) return next(action); 161 | 162 | switch (action.type) { 163 | case syncInternalActionType: 164 | registeredDispatch({ 165 | map, 166 | mapId: action.mapId, 167 | type: prefixOutgoingActionType(SYNC) 168 | }); 169 | break; 170 | case showCollisionBoxesInternalActionType: 171 | map.showCollisionBoxes = action.args[0]; 172 | registeredDispatch({ 173 | map, 174 | mapId: action.mapId, 175 | type: prefixOutgoingActionType(SET_SHOW_COLLISION_BOXES) 176 | }); 177 | break; 178 | case showTileBoundariesInternalActionType: 179 | map.showTileBoundaries = action.args[0]; 180 | registeredDispatch({ 181 | map, 182 | mapId: action.mapId, 183 | type: prefixOutgoingActionType(SET_SHOW_TILE_BOUNDARIES) 184 | }); 185 | break; 186 | case showOverdrawInspectorInternalActionType: 187 | map.showOverdrawInspector = action.args[0]; 188 | registeredDispatch({ 189 | map, 190 | mapId: action.mapId, 191 | type: prefixOutgoingActionType(SET_SHOW_OVERDRAW_INSPECTOR) 192 | }); 193 | break; 194 | default: 195 | if (mapMethodsByInternalActionType[action.type]) { 196 | map[mapMethodsByInternalActionType[action.type]].apply( 197 | map, 198 | action.args 199 | ); 200 | } 201 | } 202 | 203 | next(action); 204 | }; 205 | } 206 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import EventEmitter from 'eventemitter3'; 2 | import * as MapboxGLRedux from './src/'; 3 | 4 | // These lists should correspond to the lists in the source code 5 | const mapMethods = [ 6 | 'setCenter', 7 | 'panBy', 8 | 'panTo', 9 | 'setZoom', 10 | 'zoomTo', 11 | 'zoomOut', 12 | 'zoomIn', 13 | 'setBearing', 14 | 'rotateTo', 15 | 'resetNorth', 16 | 'snapToNorth', 17 | 'setPitch', 18 | 'fitBounds', 19 | 'jumpTo', 20 | 'flyTo', 21 | 'easeTo', 22 | 'stop', 23 | 'setProjection' 24 | ]; 25 | 26 | const mapEvents = [ 27 | 'move', 28 | 'movestart', 29 | 'moveend', 30 | 'zoom', 31 | 'zoomstart', 32 | 'zoomend', 33 | 'rotate', 34 | 'rotatestart', 35 | 'rotateend', 36 | 'pitch', 37 | 'load' 38 | ]; 39 | 40 | describe('MapboxGLRedux', () => { 41 | describe('API', () => { 42 | test('only exposes known stuff', () => { 43 | expect(Object.keys(MapboxGLRedux).length).toBe(5); 44 | }); 45 | 46 | test('exposes all the stuff we want exposed', () => { 47 | expect(MapboxGLRedux.ReduxMapControl).toBeTruthy(); 48 | expect(MapboxGLRedux.mapMiddleware).toBeTruthy(); 49 | expect(MapboxGLRedux.MapActionCreators).toBeTruthy(); 50 | expect(MapboxGLRedux.bindMapActionCreators).toBeTruthy(); 51 | expect(MapboxGLRedux.MapActionTypes).toBeTruthy(); 52 | }); 53 | }); 54 | 55 | describe('MapboxGLRedux.MapActionTypes', () => { 56 | test('are correct', () => { 57 | expect(MapboxGLRedux.MapActionTypes).toEqual({ 58 | move: 'mapbox-move', 59 | movestart: 'mapbox-movestart', 60 | moveend: 'mapbox-moveend', 61 | zoom: 'mapbox-zoom', 62 | zoomstart: 'mapbox-zoomstart', 63 | zoomend: 'mapbox-zoomend', 64 | rotate: 'mapbox-rotate', 65 | rotatestart: 'mapbox-rotatestart', 66 | rotateend: 'mapbox-rotateend', 67 | pitch: 'mapbox-pitch', 68 | load: 'mapbox-load', 69 | sync: 'mapbox-sync', 70 | setShowCollisionBoxes: 'mapbox-setShowCollisionBoxes', 71 | setShowTileBoundaries: 'mapbox-setShowTileBoundaries', 72 | setShowOverdrawInspector: 'mapbox-setShowOverdrawInspector' 73 | }); 74 | }); 75 | }); 76 | 77 | describe('MapboxGLRedux.MapActionCreators', () => { 78 | test('are the right ones', () => { 79 | expect(Object.keys(MapboxGLRedux.MapActionCreators).length).toBe(22); 80 | }); 81 | 82 | // They all do the same thing, so can all be tested with the same assertion, 83 | // really 84 | Object.keys(MapboxGLRedux.MapActionCreators).forEach(actionCreatorName => { 85 | const actionCreator = MapboxGLRedux.MapActionCreators[actionCreatorName]; 86 | test(`${actionCreatorName} works`, () => { 87 | expect(actionCreator('foo', 1, 2, 3)).toEqual({ 88 | mapId: 'foo', 89 | args: [1, 2, 3], 90 | type: `internal-mapbox-${actionCreatorName}` 91 | }); 92 | }); 93 | }); 94 | }); 95 | 96 | describe('MapboxGLRedux.bindMapActionCreators', () => { 97 | const boundMapActionCreators = MapboxGLRedux.bindMapActionCreators( 98 | 'walkawalka' 99 | ); 100 | 101 | Object.keys(boundMapActionCreators).forEach(actionCreatorName => { 102 | const actionCreator = boundMapActionCreators[actionCreatorName]; 103 | test(`${actionCreatorName} works`, () => { 104 | expect(actionCreator(1, 2, 3)).toEqual({ 105 | mapId: 'walkawalka', 106 | args: [1, 2, 3], 107 | type: `internal-mapbox-${actionCreatorName}` 108 | }); 109 | }); 110 | }); 111 | }); 112 | 113 | describe('MapboxGLRedux.ReduxMapControl', () => { 114 | let mockMap; 115 | let control; 116 | let mockMapOnSpy; 117 | let mockMapOffSpy; 118 | 119 | beforeEach(() => { 120 | control = new MapboxGLRedux.ReduxMapControl('choo'); 121 | mockMap = new EventEmitter(); 122 | mockMapOnSpy = jest.spyOn(mockMap, 'on'); 123 | mockMapOffSpy = jest.spyOn(mockMap, 'off'); 124 | }); 125 | 126 | test('exposes bound MapActionCreators', () => { 127 | const actionCreators = control.MapActionCreators; 128 | expect(actionCreators.zoomTo(7)).toEqual({ 129 | mapId: 'choo', 130 | args: [7], 131 | type: 'internal-mapbox-zoomTo' 132 | }); 133 | }); 134 | 135 | test('exposes onAdd and onRemove methods for GL JS Control interface', () => { 136 | expect(typeof control.onAdd).toBe('function'); 137 | expect(typeof control.onRemove).toBe('function'); 138 | }); 139 | 140 | describe('adds listeners when added to map', () => { 141 | beforeEach(() => { 142 | control.onAdd(mockMap); 143 | }); 144 | 145 | test('the correct number', () => { 146 | expect(mockMapOnSpy).toHaveBeenCalledTimes(mapEvents.length); 147 | }); 148 | 149 | mapEvents.forEach(eventType => { 150 | test(`adds listener for event ${eventType}`, () => { 151 | const listenerAdded = mockMapOnSpy.mock.calls.find(call => { 152 | return call[0] === eventType; 153 | }); 154 | expect(listenerAdded).toBeTruthy(); 155 | }); 156 | }); 157 | }); 158 | 159 | describe('adds listeners that dispatch actions', () => { 160 | let dispatchSpy; 161 | 162 | beforeEach(() => { 163 | dispatchSpy = jest.fn(); 164 | // Register dispatch by invoking the middleware 165 | MapboxGLRedux.mapMiddleware({ dispatch: dispatchSpy }); 166 | control.onAdd(mockMap); 167 | }); 168 | 169 | mapEvents.forEach(eventType => { 170 | test(`dispatches when event ${eventType} fires`, () => { 171 | mockMap.emit(eventType, { foo: 'bar' }); 172 | const dispatchCall = dispatchSpy.mock.calls.find(call => { 173 | return call[0].event === eventType; 174 | }); 175 | 176 | expect(dispatchCall).toBeTruthy(); 177 | expect(dispatchCall[0]).toEqual({ 178 | map: mockMap, 179 | mapId: 'choo', 180 | eventData: { foo: 'bar' }, 181 | event: eventType, 182 | type: `mapbox-${eventType}` 183 | }); 184 | }); 185 | }); 186 | }); 187 | 188 | describe('removes listeners when removed from map', () => { 189 | beforeEach(() => { 190 | control.onAdd(mockMap); 191 | control.onRemove(mockMap); 192 | }); 193 | 194 | test('the correct number', () => { 195 | expect(mockMapOnSpy).toHaveBeenCalledTimes(mapEvents.length); 196 | }); 197 | 198 | mapEvents.forEach(eventType => { 199 | test(`removes listener for event ${eventType}`, () => { 200 | const listenerAdded = mockMapOffSpy.mock.calls.find(call => { 201 | return call[0] === eventType; 202 | }); 203 | expect(listenerAdded).toBeTruthy(); 204 | }); 205 | }); 206 | }); 207 | }); 208 | 209 | describe('MapboxGLRedux.mapMiddleware', () => { 210 | let dispatchSpy = jest.fn(); 211 | let nextSpy = jest.fn(); 212 | let actionReceiver; 213 | let mockMap; 214 | 215 | beforeEach(() => { 216 | // Register a map 217 | mockMap = new EventEmitter(); 218 | const control = new MapboxGLRedux.ReduxMapControl('pie'); 219 | control.onAdd(mockMap); 220 | 221 | mockMap.showCollisionBoxes = false; 222 | mockMap.showTileBoundaries = false; 223 | mapMethods.forEach(methodName => { 224 | mockMap[methodName] = jest.fn(); 225 | }); 226 | 227 | dispatchSpy.mockClear(); 228 | nextSpy.mockClear(); 229 | 230 | actionReceiver = MapboxGLRedux.mapMiddleware({ dispatch: dispatchSpy })( 231 | nextSpy 232 | ); 233 | }); 234 | 235 | test('does nothing if mapId does not match registered map', () => { 236 | const action = { mapId: 'choo' }; 237 | actionReceiver(action); 238 | expect(dispatchSpy.mock.calls.length).toBe(0); 239 | mapMethods.forEach(methodName => { 240 | expect(mockMap[methodName]).toHaveBeenCalledTimes(0); 241 | }); 242 | expect(nextSpy.mock.calls.length).toBe(1); 243 | expect(nextSpy.mock.calls[0]).toEqual([action]); 244 | }); 245 | 246 | describe('real map methods', () => { 247 | mapMethods.forEach(methodName => { 248 | describe(methodName, () => { 249 | const action = { 250 | mapId: 'pie', 251 | type: `internal-mapbox-${methodName}`, 252 | args: [1, 2, 3] 253 | }; 254 | 255 | beforeEach(() => { 256 | actionReceiver(action); 257 | }); 258 | 259 | test('does not dispatch', () => { 260 | expect(dispatchSpy.mock.calls.length).toBe(0); 261 | }); 262 | 263 | test('invokes method on map with args', () => { 264 | expect(mockMap[methodName]).toHaveBeenCalledTimes(1); 265 | expect(mockMap[methodName].mock.calls[0]).toEqual([1, 2, 3]); 266 | }); 267 | 268 | test('passes action along', () => { 269 | expect(nextSpy).toHaveBeenCalledTimes(1); 270 | expect(nextSpy.mock.calls[0]).toEqual([action]); 271 | }); 272 | }); 273 | }); 274 | }); 275 | 276 | describe('special cases', () => { 277 | test('dispatches sync action', () => { 278 | const action = { 279 | mapId: 'pie', 280 | type: 'internal-mapbox-sync', 281 | foo: 'bar' 282 | }; 283 | 284 | actionReceiver(action); 285 | expect(dispatchSpy.mock.calls.length).toBe(1); 286 | expect(dispatchSpy.mock.calls[0]).toEqual([ 287 | { 288 | map: mockMap, 289 | mapId: 'pie', 290 | type: 'mapbox-sync' 291 | } 292 | ]); 293 | expect(nextSpy).toHaveBeenCalledWith(action); 294 | }); 295 | 296 | test('dispatches showCollisionBoxes action and changes map', () => { 297 | const action = { 298 | mapId: 'pie', 299 | type: 'internal-mapbox-setShowCollisionBoxes', 300 | foo: 'bar', 301 | args: [true] 302 | }; 303 | 304 | actionReceiver(action); 305 | expect(dispatchSpy.mock.calls.length).toBe(1); 306 | expect(dispatchSpy.mock.calls[0]).toEqual([ 307 | { 308 | map: mockMap, 309 | mapId: 'pie', 310 | type: 'mapbox-setShowCollisionBoxes' 311 | } 312 | ]); 313 | expect(mockMap.showCollisionBoxes).toBe(true); 314 | expect(nextSpy).toHaveBeenCalledWith(action); 315 | }); 316 | 317 | test('dispatches showTileBoundaries action and changes map', () => { 318 | const action = { 319 | mapId: 'pie', 320 | type: 'internal-mapbox-setShowTileBoundaries', 321 | foo: 'bar', 322 | args: [true] 323 | }; 324 | 325 | actionReceiver(action); 326 | expect(dispatchSpy.mock.calls.length).toBe(1); 327 | expect(dispatchSpy.mock.calls[0]).toEqual([ 328 | { 329 | map: mockMap, 330 | mapId: 'pie', 331 | type: 'mapbox-setShowTileBoundaries' 332 | } 333 | ]); 334 | expect(mockMap.showTileBoundaries).toBe(true); 335 | expect(nextSpy).toHaveBeenCalledWith(action); 336 | }); 337 | 338 | test('dispatches showOverdrawInspector action and changes map', () => { 339 | const action = { 340 | mapId: 'pie', 341 | type: 'internal-mapbox-setShowOverdrawInspector', 342 | foo: 'bar', 343 | args: [true] 344 | }; 345 | 346 | actionReceiver(action); 347 | expect(dispatchSpy.mock.calls.length).toBe(1); 348 | expect(dispatchSpy.mock.calls[0]).toEqual([ 349 | { 350 | map: mockMap, 351 | mapId: 'pie', 352 | type: 'mapbox-setShowOverdrawInspector' 353 | } 354 | ]); 355 | expect(mockMap.showOverdrawInspector).toBe(true); 356 | expect(nextSpy).toHaveBeenCalledWith(action); 357 | }); 358 | }); 359 | }); 360 | }); 361 | --------------------------------------------------------------------------------