From 273a6e246d70d920ea99c5f7ca2d4a2836b643c8 Mon Sep 17 00:00:00 2001 From: Falke Design Date: Tue, 8 Jun 2021 23:59:01 +0200 Subject: [PATCH] Run formatter on codebase (#933) (ignore) * Run formatter * Fix Readme Link --- README.md | 8 +- .../fixtures/FeatureCollectionEventFire.json | 44 +- .../FeatureCollectionWithCircles.json | 168 +- cypress/fixtures/MonsterPolygon.json | 2 +- cypress/fixtures/MultiPolygon.json | 23 +- cypress/fixtures/PolygonIntersects.json | 59 +- cypress/fixtures/PolygonPart1.json | 96 +- cypress/fixtures/PolygonPart2.json | 226 +- cypress/integration/circle.spec.js | 38 +- cypress/integration/circlemarker.spec.js | 45 +- cypress/integration/developing.spec.js | 21 +- cypress/integration/events.spec.js | 904 +++---- cypress/integration/globalmodes.spec.js | 109 +- cypress/integration/imageoverlay.spec.js | 32 +- cypress/integration/layergroup.spec.js | 176 +- cypress/integration/line.spec.js | 68 +- cypress/integration/marker.spec.js | 109 +- cypress/integration/options.spec.js | 96 +- cypress/integration/polygon.spec.js | 287 +-- cypress/integration/rectangle.spec.js | 319 ++- cypress/integration/rotation.spec.js | 59 +- cypress/integration/toolbar.spec.js | 173 +- cypress/integration/tooltips.spec.js | 44 +- cypress/support/commands.js | 77 +- cypress/support/index.js | 111 +- demo/customcontrols.html | 43 +- demo/customcontrols.js | 67 +- demo/demo-canvas.js | 108 +- demo/demo.css | 53 +- demo/demo.js | 118 +- demo/events.html | 30 +- demo/events.js | 122 +- demo/index-canvas.html | 67 +- demo/index.html | 68 +- index.html | 53 +- leaflet-geoman.d.ts | 2267 +++++++++-------- src/assets/translations/da.json | 2 +- src/assets/translations/es.json | 60 +- src/assets/translations/hu.json | 2 +- src/assets/translations/index.js | 2 +- src/assets/translations/pt_br.json | 60 +- src/css/controls.css | 58 +- src/css/layers.css | 2 +- src/js/Draw/L.PM.Draw.Circle.js | 87 +- src/js/Draw/L.PM.Draw.CircleMarker.js | 134 +- src/js/Draw/L.PM.Draw.Cut.js | 133 +- src/js/Draw/L.PM.Draw.Line.js | 44 +- src/js/Draw/L.PM.Draw.Marker.js | 31 +- src/js/Draw/L.PM.Draw.Polygon.js | 24 +- src/js/Draw/L.PM.Draw.Rectangle.js | 50 +- src/js/Draw/L.PM.Draw.js | 103 +- src/js/Edit/L.PM.Edit.Circle.js | 93 +- src/js/Edit/L.PM.Edit.CircleMarker.js | 107 +- src/js/Edit/L.PM.Edit.ImageOverlay.js | 4 +- src/js/Edit/L.PM.Edit.LayerGroup.js | 93 +- src/js/Edit/L.PM.Edit.Line.js | 145 +- src/js/Edit/L.PM.Edit.Marker.js | 9 +- src/js/Edit/L.PM.Edit.Polygon.js | 35 +- src/js/Edit/L.PM.Edit.Rectangle.js | 61 +- src/js/Edit/L.PM.Edit.js | 76 +- src/js/L.PM.Map.js | 70 +- src/js/L.PM.Utils.js | 87 +- src/js/Mixins/Dragging.js | 120 +- src/js/Mixins/Events.js | 729 ++++-- src/js/Mixins/Keyboard.js | 12 +- src/js/Mixins/MarkerLimits.js | 33 +- src/js/Mixins/Modes/Mode.Drag.js | 14 +- src/js/Mixins/Modes/Mode.Edit.js | 18 +- src/js/Mixins/Modes/Mode.Removal.js | 39 +- src/js/Mixins/Modes/Mode.Rotate.js | 41 +- src/js/Mixins/Rotating.js | 158 +- src/js/Mixins/Snapping.js | 90 +- src/js/Toolbar/L.Controls.js | 38 +- src/js/Toolbar/L.PM.Toolbar.js | 179 +- src/js/helpers/Matrix.js | 67 +- src/js/helpers/ModeHelper.js | 4 +- src/js/helpers/index.js | 153 +- src/js/helpers/turfHelper.js | 50 +- src/js/polyfills.js | 15 +- webpack.build.js | 117 +- webpack.dev.js | 89 +- 81 files changed, 5358 insertions(+), 4470 deletions(-) diff --git a/README.md b/README.md index 08f35e65..bd70f4ae 100644 --- a/README.md +++ b/README.md @@ -49,8 +49,8 @@ Features marked with ⭐ in this documentation are available in Leaflet-Geoman P - [Removal Mode](#removal-mode) - [Cut Mode](#cut-mode) - [Rotation Mode](#rotation-mode) -- [Split Mode ⭐](#split-mode) -- [Scale Mode ⭐](#scale-mode) +- [Split Mode ⭐](#split-mode-) +- [Scale Mode ⭐](#scale-mode-) - [Options](#options) - [Snapping](#snapping) - [Pinning ⭐](#pinning-) @@ -393,8 +393,8 @@ See the available options in the table below. | limitMarkersToViewport | `false` | Shows only markers in the viewport. ⭐ | | limitMarkersToClick | `false` | Shows markers only after the layer was clicked. ⭐ | | pinning | `false` | Pin shared vertices/markers together during edit [Details](#pinning-⭐). ⭐ | -| centerScaling | `true` | Scale origin is the center, else it is the opposite corner. If `false` Alt-Key can be used. [Scale Mode](#scale-mode). ⭐ | -| uniformScaling | `true` | Width and height are scaled with the same ratio. If `false` Shift-Key can be used. [Scale Mode](#scale-mode). ⭐ | +| centerScaling | `true` | Scale origin is the center, else it is the opposite corner. If `false` Alt-Key can be used. [Scale Mode](#scale-mode-). ⭐ | +| uniformScaling | `true` | Width and height are scaled with the same ratio. If `false` Shift-Key can be used. [Scale Mode](#scale-mode-). ⭐ | You can listen to events related to editing on events like this: diff --git a/cypress/fixtures/FeatureCollectionEventFire.json b/cypress/fixtures/FeatureCollectionEventFire.json index bdf678de..d8492a7c 100644 --- a/cypress/fixtures/FeatureCollectionEventFire.json +++ b/cypress/fixtures/FeatureCollectionEventFire.json @@ -1,29 +1,19 @@ { - "type":"FeatureCollection", - "features":[ - { - "type":"Feature", - "geometry":{ - "type":"MultiPoint", - "coordinates":[ - [ - 32.83604819, - 40.0169319 - ] - ] - } - }, - { - "type":"Feature", - "geometry":{ - "type":"MultiPoint", - "coordinates":[ - [ - 32.8298979, - 40.02567418 - ] - ] - } - } - ] + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "geometry": { + "type": "MultiPoint", + "coordinates": [[32.83604819, 40.0169319]] + } + }, + { + "type": "Feature", + "geometry": { + "type": "MultiPoint", + "coordinates": [[32.8298979, 40.02567418]] + } + } + ] } diff --git a/cypress/fixtures/FeatureCollectionWithCircles.json b/cypress/fixtures/FeatureCollectionWithCircles.json index 404a7817..14b048e1 100644 --- a/cypress/fixtures/FeatureCollectionWithCircles.json +++ b/cypress/fixtures/FeatureCollectionWithCircles.json @@ -1,86 +1,86 @@ { - "type": "FeatureCollection", - "features": [ - { - "type": "Feature", - "properties": { "customGeometry": { "radius": 50 } }, - "geometry": { - "type": "Point", - "coordinates": [-0.152843, 51.486742, 77] - } - }, - { - "type": "Feature", - "properties": { "customGeometry": { "radius": 20 } }, - "geometry": { - "type": "Point", - "coordinates": [-0.151727, 51.487472, 77] - } - }, - { - "type": "Feature", - "properties": { "customGeometry": { "radius": 80 } }, - "geometry": { - "type": "Point", - "coordinates": [-0.153636, 51.486562, 77] - } - }, - { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Polygon", - "coordinates": [ - [ - [-0.15369, 51.486973, 77], - [-0.153853, 51.48686, 77], - [-0.154183, 51.486968, 77], - [-0.154001, 51.487087, 77], - [-0.15369, 51.486973, 77] - ] - ] - } - }, - { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Polygon", - "coordinates": [ - [ - [-0.15252, 51.487201, 77], - [-0.152789, 51.487281, 77], - [-0.153025, 51.487097, 77], - [-0.152633, 51.487002, 77], - [-0.152448, 51.487088, 77], - [-0.15252, 51.487201, 77] - ] - ] - } - }, - { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Polygon", - "coordinates": [ - [ - [-0.154241, 51.487382, 77], - [-0.1545, 51.487608, 77], - [-0.154905, 51.487384, 77], - [-0.154343, 51.487322, 77], - [-0.154241, 51.487382, 77] - ] - ] - } - }, - { - "type": "Feature", - "properties": { "customGeometry": { "radius": 50 } }, - "geometry": { - "type": "Point", - "coordinates": [-0.153366, 51.487348, 77] - } - } - ] + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": { "customGeometry": { "radius": 50 } }, + "geometry": { + "type": "Point", + "coordinates": [-0.152843, 51.486742, 77] + } + }, + { + "type": "Feature", + "properties": { "customGeometry": { "radius": 20 } }, + "geometry": { + "type": "Point", + "coordinates": [-0.151727, 51.487472, 77] + } + }, + { + "type": "Feature", + "properties": { "customGeometry": { "radius": 80 } }, + "geometry": { + "type": "Point", + "coordinates": [-0.153636, 51.486562, 77] + } + }, + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [-0.15369, 51.486973, 77], + [-0.153853, 51.48686, 77], + [-0.154183, 51.486968, 77], + [-0.154001, 51.487087, 77], + [-0.15369, 51.486973, 77] + ] + ] + } + }, + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [-0.15252, 51.487201, 77], + [-0.152789, 51.487281, 77], + [-0.153025, 51.487097, 77], + [-0.152633, 51.487002, 77], + [-0.152448, 51.487088, 77], + [-0.15252, 51.487201, 77] + ] + ] + } + }, + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [-0.154241, 51.487382, 77], + [-0.1545, 51.487608, 77], + [-0.154905, 51.487384, 77], + [-0.154343, 51.487322, 77], + [-0.154241, 51.487382, 77] + ] + ] + } + }, + { + "type": "Feature", + "properties": { "customGeometry": { "radius": 50 } }, + "geometry": { + "type": "Point", + "coordinates": [-0.153366, 51.487348, 77] + } + } + ] } diff --git a/cypress/fixtures/MonsterPolygon.json b/cypress/fixtures/MonsterPolygon.json index 59b3f398..7dab955c 100644 --- a/cypress/fixtures/MonsterPolygon.json +++ b/cypress/fixtures/MonsterPolygon.json @@ -9951,4 +9951,4 @@ } ] } -} \ No newline at end of file +} diff --git a/cypress/fixtures/MultiPolygon.json b/cypress/fixtures/MultiPolygon.json index ca7dcf5e..79f82ccc 100644 --- a/cypress/fixtures/MultiPolygon.json +++ b/cypress/fixtures/MultiPolygon.json @@ -1,4 +1,23 @@ { - "type": "MultiPolygon", - "coordinates": [[[[107, 7], [108, 7], [108, 8], [107, 8], [107, 7]]], [[[100, 0], [101, 0], [101, 1], [100, 1], [100, 0]]]] + "type": "MultiPolygon", + "coordinates": [ + [ + [ + [107, 7], + [108, 7], + [108, 8], + [107, 8], + [107, 7] + ] + ], + [ + [ + [100, 0], + [101, 0], + [101, 1], + [100, 1], + [100, 0] + ] + ] + ] } diff --git a/cypress/fixtures/PolygonIntersects.json b/cypress/fixtures/PolygonIntersects.json index 06054365..372c1890 100644 --- a/cypress/fixtures/PolygonIntersects.json +++ b/cypress/fixtures/PolygonIntersects.json @@ -2,9 +2,7 @@ "type": "Feature", "properties": { "shape": "Polygon", - "maps": [ - "default-map" - ], + "maps": ["default-map"], "name": "Unnamed Layer", "category": "default", "id": "fa4cf31e-38f2-4b00-b1ff-43ccb3b2439e" @@ -13,50 +11,17 @@ "type": "Polygon", "coordinates": [ [ - [ - 4.677076, - 49.003375 - ], - [ - 4.345093, - 48.770672 - ], - [ - 4.858284, - 48.616297 - ], - [ - 5.286592, - 48.703378 - ], - [ - 5.412889, - 48.529065 - ], - [ - 4.822592, - 48.677995 - ], - [ - 5.168533, - 48.793928 - ], - [ - 5.281101, - 48.886121 - ], - [ - 4.655112, - 48.826486 - ], - [ - 4.333881, - 48.601769 - ], - [ - 4.281715, - 49.019589 - ] + [4.677076, 49.003375], + [4.345093, 48.770672], + [4.858284, 48.616297], + [5.286592, 48.703378], + [5.412889, 48.529065], + [4.822592, 48.677995], + [5.168533, 48.793928], + [5.281101, 48.886121], + [4.655112, 48.826486], + [4.333881, 48.601769], + [4.281715, 49.019589] ] ] } diff --git a/cypress/fixtures/PolygonPart1.json b/cypress/fixtures/PolygonPart1.json index 987a10cc..b5962bb8 100644 --- a/cypress/fixtures/PolygonPart1.json +++ b/cypress/fixtures/PolygonPart1.json @@ -5,9 +5,7 @@ "type": "Feature", "properties": { "shape": "Polygon", - "maps": [ - "default-map" - ], + "maps": ["default-map"], "name": "Unnamed Layer", "category": "default", "id": "fa4cf31e-38f2-4b00-b1ff-43ccb3b2439e" @@ -16,81 +14,27 @@ "type": "Polygon", "coordinates": [ [ - [ - -74.012189, - 40.719713 - ], - [ - -74.012833, - 40.720884 - ], - [ - -74.012704, - 40.7216 - ], - [ - -74.012575, - 40.72238 - ], - [ - -74.012446, - 40.723909 - ], - [ - -74.012918, - 40.72495 - ], - [ - -74.014678, - 40.724527 - ], - [ - -74.015365, - 40.723616 - ], - [ - -74.015365, - 40.721209 - ], - [ - -74.014463, - 40.719323 - ], - [ - -74.013047, - 40.717957 - ], - [ - -74.009914, - 40.7162 - ], - [ - -74.004507, - 40.715745 - ], - [ - -74.001846, - 40.718607 - ], - [ - -74.000773, - 40.720656 - ], - [ - -74.002361, - 40.724137 - ], - [ - -74.011116, - 40.72495 - ], - [ - -74.012189, - 40.719713 - ] + [-74.012189, 40.719713], + [-74.012833, 40.720884], + [-74.012704, 40.7216], + [-74.012575, 40.72238], + [-74.012446, 40.723909], + [-74.012918, 40.72495], + [-74.014678, 40.724527], + [-74.015365, 40.723616], + [-74.015365, 40.721209], + [-74.014463, 40.719323], + [-74.013047, 40.717957], + [-74.009914, 40.7162], + [-74.004507, 40.715745], + [-74.001846, 40.718607], + [-74.000773, 40.720656], + [-74.002361, 40.724137], + [-74.011116, 40.72495], + [-74.012189, 40.719713] ] ] } } ] -} \ No newline at end of file +} diff --git a/cypress/fixtures/PolygonPart2.json b/cypress/fixtures/PolygonPart2.json index 49262eac..a2a7c03f 100644 --- a/cypress/fixtures/PolygonPart2.json +++ b/cypress/fixtures/PolygonPart2.json @@ -5,9 +5,7 @@ "type": "Feature", "properties": { "shape": "Polygon", - "maps": [ - "default-map" - ], + "maps": ["default-map"], "name": "Unnamed Layer", "category": "default", "id": "7af7d4e3-0111-4119-bff6-465c5e004481" @@ -16,185 +14,53 @@ "type": "Polygon", "coordinates": [ [ - [ - -74.011116, - 40.72495 - ], - [ - -74.002361, - 40.724137 - ], - [ - -74.000773, - 40.720656 - ], - [ - -74.001846, - 40.718607 - ], - [ - -74.004507, - 40.715745 - ], - [ - -74.009914, - 40.7162 - ], - [ - -74.013991, - 40.71594 - ], - [ - -74.014163, - 40.715322 - ], - [ - -74.013863, - 40.714574 - ], - [ - -74.012189, - 40.714574 - ], - [ - -74.011588, - 40.715192 - ], - [ - -74.010043, - 40.714867 - ], - [ - -74.009957, - 40.714509 - ], - [ - -74.009957, - 40.714281 - ], - [ - -74.009314, - 40.714021 - ], - [ - -74.008241, - 40.714118 - ], - [ - -74.007125, - 40.714346 - ], - [ - -74.005666, - 40.714216 - ], - [ - -74.00485, - 40.713923 - ], - [ - -74.001846, - 40.713956 - ], - [ - -74.001675, - 40.714346 - ], - [ - -74.001675, - 40.714671 - ], - [ - -74.00146, - 40.715127 - ], - [ - -74.000473, - 40.715712 - ], - [ - -73.998413, - 40.716135 - ], - [ - -73.996267, - 40.716395 - ], - [ - -73.995752, - 40.716818 - ], - [ - -73.995709, - 40.717046 - ], - [ - -73.996568, - 40.718607 - ], - [ - -73.996611, - 40.719388 - ], - [ - -73.996139, - 40.720299 - ], - [ - -73.995709, - 40.721209 - ], - [ - -73.995709, - 40.72264 - ], - [ - -73.998284, - 40.723974 - ], - [ - -73.999443, - 40.724657 - ], - [ - -74.000258, - 40.725437 - ], - [ - -74.000473, - 40.725958 - ], - [ - -74.00043, - 40.726934 - ], - [ - -74.002233, - 40.726836 - ], - [ - -74.003005, - 40.726055 - ], - [ - -74.004722, - 40.72534 - ], - [ - -74.008198, - 40.72612 - ], - [ - -74.008284, - 40.727226 - ], - [ - -74.011116, - 40.72495 - ] + [-74.011116, 40.72495], + [-74.002361, 40.724137], + [-74.000773, 40.720656], + [-74.001846, 40.718607], + [-74.004507, 40.715745], + [-74.009914, 40.7162], + [-74.013991, 40.71594], + [-74.014163, 40.715322], + [-74.013863, 40.714574], + [-74.012189, 40.714574], + [-74.011588, 40.715192], + [-74.010043, 40.714867], + [-74.009957, 40.714509], + [-74.009957, 40.714281], + [-74.009314, 40.714021], + [-74.008241, 40.714118], + [-74.007125, 40.714346], + [-74.005666, 40.714216], + [-74.00485, 40.713923], + [-74.001846, 40.713956], + [-74.001675, 40.714346], + [-74.001675, 40.714671], + [-74.00146, 40.715127], + [-74.000473, 40.715712], + [-73.998413, 40.716135], + [-73.996267, 40.716395], + [-73.995752, 40.716818], + [-73.995709, 40.717046], + [-73.996568, 40.718607], + [-73.996611, 40.719388], + [-73.996139, 40.720299], + [-73.995709, 40.721209], + [-73.995709, 40.72264], + [-73.998284, 40.723974], + [-73.999443, 40.724657], + [-74.000258, 40.725437], + [-74.000473, 40.725958], + [-74.00043, 40.726934], + [-74.002233, 40.726836], + [-74.003005, 40.726055], + [-74.004722, 40.72534], + [-74.008198, 40.72612], + [-74.008284, 40.727226], + [-74.011116, 40.72495] ] ] } } ] -} \ No newline at end of file +} diff --git a/cypress/integration/circle.spec.js b/cypress/integration/circle.spec.js index bd3ce7f7..90579a4c 100644 --- a/cypress/integration/circle.spec.js +++ b/cypress/integration/circle.spec.js @@ -7,9 +7,7 @@ describe('Draw Circle', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(250, 250); + cy.get(mapSelector).click(200, 200).click(250, 250); cy.toolbarButton('edit') .click() @@ -51,7 +49,7 @@ describe('Draw Circle', () => { .click(200, 200) .click(250, 250) .then(() => { - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.Circle) { expect(layer.options.color).to.equal('red'); expect(layer.options.fillColor).to.equal('orange'); @@ -76,7 +74,7 @@ describe('Draw Circle', () => { .click(200, 200) .click(250, 250) .then(() => { - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.Circle) { expect(layer.options.color).to.equal('yellow'); } @@ -87,7 +85,7 @@ describe('Draw Circle', () => { it('enable continueDrawing', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({continueDrawing: true}); + map.pm.setGlobalOptions({ continueDrawing: true }); }); cy.toolbarButton('circle') @@ -96,14 +94,10 @@ describe('Draw Circle', () => { .should('have.class', 'active'); // draw first circle - cy.get(mapSelector) - .click(200, 200) - .click(250, 250); + cy.get(mapSelector).click(200, 200).click(250, 250); // draw with continueDrawing: ture the second circle - cy.get(mapSelector) - .click(300, 200) - .click(350, 250); + cy.get(mapSelector).click(300, 200).click(350, 250); cy.toolbarButton('edit').click(); cy.hasVertexMarkers(4); @@ -126,7 +120,7 @@ describe('Draw Circle', () => { .click(400, 190) .then(() => { const layers = map.pm.getGeomanDrawLayers(); - layers.forEach(layer => { + layers.forEach((layer) => { if (layer instanceof L.Circle) { expect(layer.getRadius()).to.equal(1500); } @@ -147,11 +141,11 @@ describe('Draw Circle', () => { maxRadiusCircle: 3000, }); cy.get(mapSelector) - .click(250,200) - .click(300,190) + .click(250, 200) + .click(300, 190) .then(() => { const layers = map.pm.getGeomanDrawLayers(); - layers.forEach(layer => { + layers.forEach((layer) => { if (layer instanceof L.Circle) { expect(layer.getRadius()).to.equal(1500); } @@ -161,7 +155,10 @@ describe('Draw Circle', () => { }); it('requireSnapToFinish', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({requireSnapToFinish: true, snapSegment: false}); + map.pm.setGlobalOptions({ + requireSnapToFinish: true, + snapSegment: false, + }); }); cy.toolbarButton('polygon').click(); @@ -172,16 +169,13 @@ describe('Draw Circle', () => { .click(150, 250); cy.toolbarButton('circle').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 60); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); }); - cy.get(mapSelector) - .click(250, 50); + cy.get(mapSelector).click(250, 50); cy.window().then(({ map }) => { expect(2).to.eq(map.pm.getGeomanDrawLayers().length); diff --git a/cypress/integration/circlemarker.spec.js b/cypress/integration/circlemarker.spec.js index 5b58f213..e2edcc24 100644 --- a/cypress/integration/circlemarker.spec.js +++ b/cypress/integration/circlemarker.spec.js @@ -1,7 +1,7 @@ describe('Draw Circle Marker', () => { const mapSelector = '#map'; - Cypress.Commands.add('hasCircleLayers', count => { + Cypress.Commands.add('hasCircleLayers', (count) => { cy.window().then(({ map, L }) => { const layerCount = Object.values(map._layers).reduce((total, layer) => { if (layer instanceof L.CircleMarker) { @@ -56,7 +56,7 @@ describe('Draw Circle Marker', () => { createMarkers(); cy.window().then(({ map, L }) => { - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.CircleMarker) { assert.isFalse( L.DomUtil.hasClass(layer._path, 'leaflet-pm-draggable'), @@ -69,7 +69,7 @@ describe('Draw Circle Marker', () => { cy.toolbarButton('edit').click(); cy.window().then(({ map, L }) => { - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.CircleMarker) { assert.isTrue( L.DomUtil.hasClass(layer._path, 'leaflet-pm-draggable'), @@ -82,7 +82,7 @@ describe('Draw Circle Marker', () => { cy.toolbarButton('edit').click(); cy.window().then(({ map, L }) => { - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.CircleMarker) { assert.isFalse( L.DomUtil.hasClass(layer._path, 'leaflet-pm-draggable'), @@ -124,9 +124,7 @@ describe('Draw Circle Marker', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(250, 250); + cy.get(mapSelector).click(200, 200).click(250, 250); cy.hasCircleLayers(1); @@ -147,9 +145,7 @@ describe('Draw Circle Marker', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.toolbarButton('edit') .click() @@ -232,7 +228,7 @@ describe('Draw Circle Marker', () => { .click(410, 190) .then(() => { const layers = map.pm.getGeomanDrawLayers(); - layers.forEach(layer => { + layers.forEach((layer) => { if (layer instanceof L.CircleMarker) { expect(layer.getRadius()).to.equal(150); } @@ -258,7 +254,7 @@ describe('Draw Circle Marker', () => { .click(300, 200) .then(() => { const layers = map.pm.getGeomanDrawLayers(); - layers.forEach(layer => { + layers.forEach((layer) => { if (layer instanceof L.CircleMarker) { expect(layer.getRadius()).to.equal(150); } @@ -268,7 +264,10 @@ describe('Draw Circle Marker', () => { }); it('requireSnapToFinish', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({requireSnapToFinish: true, snapSegment: false}); + map.pm.setGlobalOptions({ + requireSnapToFinish: true, + snapSegment: false, + }); }); cy.toolbarButton('polygon').click(); @@ -279,16 +278,13 @@ describe('Draw Circle Marker', () => { .click(150, 250); cy.toolbarButton('circle-marker').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 60); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); }); - cy.get(mapSelector) - .click(250, 50); + cy.get(mapSelector).click(250, 50); cy.window().then(({ map }) => { expect(2).to.eq(map.pm.getGeomanDrawLayers().length); @@ -296,7 +292,11 @@ describe('Draw Circle Marker', () => { }); it('requireSnapToFinish editable', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({requireSnapToFinish: true, editable: true, snapSegment: false}); + map.pm.setGlobalOptions({ + requireSnapToFinish: true, + editable: true, + snapSegment: false, + }); }); cy.toolbarButton('polygon').click(); @@ -307,16 +307,13 @@ describe('Draw Circle Marker', () => { .click(150, 250); cy.toolbarButton('circle-marker').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 60); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); }); - cy.get(mapSelector) - .click(250, 50); + cy.get(mapSelector).click(250, 50); cy.window().then(({ map }) => { expect(2).to.eq(map.pm.getGeomanDrawLayers().length); diff --git a/cypress/integration/developing.spec.js b/cypress/integration/developing.spec.js index cdb1a42d..775e0758 100644 --- a/cypress/integration/developing.spec.js +++ b/cypress/integration/developing.spec.js @@ -1,13 +1,10 @@ describe('Opens Testing Environment', () => { const mapSelector = '#map'; - it('opens a map in a browser', () => { - - }); + it('opens a map in a browser', () => {}); it('gets all geoman Layers', () => { - cy.toolbarButton('polygon') - .click(); + cy.toolbarButton('polygon').click(); cy.window().then(() => { cy.get(mapSelector) @@ -15,23 +12,21 @@ describe('Opens Testing Environment', () => { .click(100, 50) .click(150, 50) .click(150, 150) - .click(90, 250) + .click(90, 250); }); - cy.window().then(({ map}) => { + cy.window().then(({ map }) => { const count = map.pm.getGeomanLayers().length; expect(count).to.equal(1); }); }); it('gets all drawn geoman Layers', () => { - - cy.window().then(({ map, L}) => { + cy.window().then(({ map, L }) => { L.marker(map.getCenter()).addTo(map); }); - cy.toolbarButton('polygon') - .click(); + cy.toolbarButton('polygon').click(); cy.window().then(() => { cy.get(mapSelector) @@ -39,10 +34,10 @@ describe('Opens Testing Environment', () => { .click(100, 50) .click(150, 50) .click(150, 150) - .click(90, 250) + .click(90, 250); }); - cy.window().then(({ map}) => { + cy.window().then(({ map }) => { const count = map.pm.getGeomanLayers().length; expect(count).to.equal(2); const count2 = map.pm.getGeomanDrawLayers().length; diff --git a/cypress/integration/events.spec.js b/cypress/integration/events.spec.js index a008a4e3..210a112c 100644 --- a/cypress/integration/events.spec.js +++ b/cypress/integration/events.spec.js @@ -2,369 +2,413 @@ describe('Events', () => { const mapSelector = '#map'; it('pm:langchange', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({ map}) => { - map.on("pm:langchange",(e) => { - calledevent = e.type; - }); - - map.pm.setLang('de'); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:langchange"); - calledevent = ""; - }) + cy.window() + .then(({ map }) => { + map.on('pm:langchange', (e) => { + calledevent = e.type; + }); + map.pm.setLang('de'); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:langchange'); + calledevent = ''; + }); }); it('pm:globaleditmodetoggled', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({ map}) => { - map.on("pm:globaleditmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globaleditmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.enableGlobalEditMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globaleditmodetoggled'); + calledevent = ''; }); - map.pm.enableGlobalEditMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globaleditmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globaleditmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globaleditmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.disableGlobalEditMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globaleditmodetoggled'); + calledevent = ''; }); - map.pm.disableGlobalEditMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globaleditmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globaleditmodetoggled",(e) => { - calledevent = e.type; - }); + cy.window() + .then(({ map }) => { + map.on('pm:globaleditmodetoggled', (e) => { + calledevent = e.type; + }); - map.pm.toggleGlobalEditMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globaleditmodetoggled"); - calledevent = ""; - }) + map.pm.toggleGlobalEditMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globaleditmodetoggled'); + calledevent = ''; + }); }); it('pm:globaldragmodetoggled', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({ map}) => { - map.on("pm:globaldragmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globaldragmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.enableGlobalDragMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globaldragmodetoggled'); + calledevent = ''; }); - map.pm.enableGlobalDragMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globaldragmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globaldragmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globaldragmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.disableGlobalDragMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globaldragmodetoggled'); + calledevent = ''; }); - map.pm.disableGlobalDragMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globaldragmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globaldragmodetoggled",(e) => { - calledevent = e.type; - }); + cy.window() + .then(({ map }) => { + map.on('pm:globaldragmodetoggled', (e) => { + calledevent = e.type; + }); - map.pm.toggleGlobalDragMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globaldragmodetoggled"); - calledevent = ""; - }) + map.pm.toggleGlobalDragMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globaldragmodetoggled'); + calledevent = ''; + }); }); it('pm:globalremovalmodetoggled', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({ map}) => { - map.on("pm:globalremovalmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globalremovalmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.enableGlobalRemovalMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globalremovalmodetoggled'); + calledevent = ''; }); - map.pm.enableGlobalRemovalMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globalremovalmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globalremovalmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globalremovalmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.disableGlobalRemovalMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globalremovalmodetoggled'); + calledevent = ''; }); - map.pm.disableGlobalRemovalMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globalremovalmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globalremovalmodetoggled",(e) => { - calledevent = e.type; - }); + cy.window() + .then(({ map }) => { + map.on('pm:globalremovalmodetoggled', (e) => { + calledevent = e.type; + }); - map.pm.toggleGlobalRemovalMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globalremovalmodetoggled"); - calledevent = ""; - }) + map.pm.toggleGlobalRemovalMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globalremovalmodetoggled'); + calledevent = ''; + }); }); it('pm:globaldrawmodetoggled', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({ map}) => { - map.on("pm:globaldrawmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globaldrawmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.enableDraw('Polygon'); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globaldrawmodetoggled'); + calledevent = ''; }); - map.pm.enableDraw("Polygon"); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globaldrawmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globaldrawmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globaldrawmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.disableDraw('Polygon'); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globaldrawmodetoggled'); + calledevent = ''; }); - map.pm.disableDraw("Polygon"); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globaldrawmodetoggled"); - calledevent = ""; - }); }); it('pm:globalcutmodetoggled', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({ map}) => { - map.on("pm:globalcutmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globalcutmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.enableDraw('Cut'); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globalcutmodetoggled'); + calledevent = ''; }); - map.pm.enableDraw("Cut"); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globalcutmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globalcutmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globalcutmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.disableDraw('Cut'); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globalcutmodetoggled'); + calledevent = ''; }); - map.pm.disableDraw("Cut"); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globalcutmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globalcutmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globalcutmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.enableGlobalCutMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globalcutmodetoggled'); + calledevent = ''; }); - map.pm.enableGlobalCutMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globalcutmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globalcutmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globalcutmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.disableGlobalCutMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globalcutmodetoggled'); + calledevent = ''; }); - map.pm.disableGlobalCutMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globalcutmodetoggled"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:globalcutmodetoggled",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:globalcutmodetoggled', (e) => { + calledevent = e.type; + }); + map.pm.toggleGlobalCutMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:globalcutmodetoggled'); + calledevent = ''; }); - map.pm.toggleGlobalCutMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:globalcutmodetoggled"); - calledevent = ""; - }); }); it('pm:drawstart & pm:drawend', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({ map}) => { - map.on("pm:drawstart",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:drawstart', (e) => { + calledevent = e.type; + }); + map.pm.enableDraw('Polygon'); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:drawstart'); + calledevent = ''; }); - map.pm.enableDraw("Polygon"); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:drawstart"); - calledevent = ""; - }); - cy.window().then(({ map}) => { - map.on("pm:drawend",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:drawend', (e) => { + calledevent = e.type; + }); + map.pm.disableDraw('Polygon'); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:drawend'); + calledevent = ''; }); - map.pm.disableDraw("Polygon"); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:drawend"); - calledevent = ""; - }); }); it('pm:create', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({ map}) => { - map.on("pm:create",(e) => { - calledevent = e.type; + cy.window() + .then(({ map }) => { + map.on('pm:create', (e) => { + calledevent = e.type; + }); + map.pm.enableDraw('Circle'); + + cy.get(mapSelector).click(200, 200).click(250, 250); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:create'); + calledevent = ''; }); - map.pm.enableDraw("Circle"); - - cy.get(mapSelector) - .click(200, 200) - .click(250, 250); - - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:create"); - calledevent = ""; - }); }); it('Events while drawing: pm:vertexadded, pm:snapdrag, pm:snap, pm:unsnap, pm:centerplaced', () => { - let calledevent = ""; - - cy.window().then(({ map}) => { + let calledevent = ''; - function logEvent(e){ - calledevent = e.type; - } - - map.on("pm:drawstart",(e) => { - const layer = e.workingLayer; - layer.on('pm:vertexadded', logEvent); - layer.on('pm:snapdrag', logEvent); - layer.on('pm:snap', logEvent); - layer.on('pm:unsnap', logEvent); - layer.on('pm:centerplaced', logEvent); + cy.window() + .then(({ map }) => { + function logEvent(e) { + calledevent = e.type; + } + + map.on('pm:drawstart', (e) => { + const layer = e.workingLayer; + layer.on('pm:vertexadded', logEvent); + layer.on('pm:snapdrag', logEvent); + layer.on('pm:snap', logEvent); + layer.on('pm:unsnap', logEvent); + layer.on('pm:centerplaced', logEvent); + }); + map.pm.enableDraw('Polygon'); + + cy.get(mapSelector).click(200, 300); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:vertexadded'); + calledevent = ''; }); - map.pm.enableDraw("Polygon"); - cy.get(mapSelector) - .click(200, 300); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:vertexadded"); - calledevent = ""; - }); - - cy.window().then(() => { - cy.get(mapSelector) - .click(200, 350) - .trigger('mousemove', { clientX: 200, clientY: 305 }) - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:snap"); - calledevent = ""; - }); + cy.window() + .then(() => { + cy.get(mapSelector) + .click(200, 350) + .trigger('mousemove', { clientX: 200, clientY: 305 }); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:snap'); + calledevent = ''; + }); - cy.window().then(() => { - cy.get(mapSelector) - .trigger('mousemove', { clientX: 300, clientY: 355 }) - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:unsnap"); - calledevent = ""; - }); + cy.window() + .then(() => { + cy.get(mapSelector).trigger('mousemove', { + clientX: 300, + clientY: 355, + }); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:unsnap'); + calledevent = ''; + }); - cy.window().then(() => { - cy.get(mapSelector) - .trigger('mousemove', { clientX: 300, clientY: 385 }) - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:snapdrag"); - calledevent = ""; - }); + cy.window() + .then(() => { + cy.get(mapSelector).trigger('mousemove', { + clientX: 300, + clientY: 385, + }); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:snapdrag'); + calledevent = ''; + }); }); - it(' pm:centerplaced event while drawing', () => { - let calledevent = ""; + let calledevent = ''; - cy.window().then(({map}) => { - function logEvent(e){ - calledevent = e.type; - } + cy.window() + .then(({ map }) => { + function logEvent(e) { + calledevent = e.type; + } - map.on("pm:drawstart",(e) => { - const layer = e.workingLayer; - layer.on('pm:centerplaced', logEvent); + map.on('pm:drawstart', (e) => { + const layer = e.workingLayer; + layer.on('pm:centerplaced', logEvent); + }); + map.pm.enableDraw('Circle'); + cy.get(mapSelector).click(200, 385).click(200, 200); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:centerplaced'); + calledevent = ''; }); - map.pm.enableDraw("Circle"); - cy.get(mapSelector) - .click(200, 385) - .click(200, 200); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:centerplaced"); - calledevent = ""; - }); }); - it('Events while editing: pm:edit,pm:update,pm:enable,pm:disable,pm:vertexadded,pm:vertexremoved', () => { - let calledevent = ""; + let calledevent = ''; let calledeventArr = []; - cy.window().then(({map}) => { - - function logEvent(e){ - console.log(e.type) - calledevent = e.type; - calledeventArr[e.type] = e.type; - } - - map.on("pm:create",({layer}) => { - map.pm.disableDraw(); - - layer.on('pm:edit', logEvent); - layer.on('pm:update', logEvent); - layer.on('pm:enable', logEvent); - layer.on('pm:disable', logEvent); - layer.on('pm:vertexadded', logEvent); - layer.on('pm:vertexremoved', logEvent); - /* + cy.window() + .then(({ map }) => { + function logEvent(e) { + console.log(e.type); + calledevent = e.type; + calledeventArr[e.type] = e.type; + } + + map.on('pm:create', ({ layer }) => { + map.pm.disableDraw(); + + layer.on('pm:edit', logEvent); + layer.on('pm:update', logEvent); + layer.on('pm:enable', logEvent); + layer.on('pm:disable', logEvent); + layer.on('pm:vertexadded', logEvent); + layer.on('pm:vertexremoved', logEvent); + /* TODO Can't tested --> needs dragging layer.on('pm:markerdragstart', logEvent); layer.on('pm:markerdragend', logEvent); @@ -375,197 +419,197 @@ describe('Events', () => { layer.on('pm:centerplaced', logEvent); */ - layer.pm.enable({ - allowSelfIntersection: false, + layer.pm.enable({ + allowSelfIntersection: false, + }); }); - + map.pm.enableDraw('Polygon'); + + cy.get(mapSelector) + + .click(200, 300) + .click(300, 300) + .click(200, 400) + .click(200, 300); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:enable'); + calledevent = ''; }); - map.pm.enableDraw("Polygon"); - cy.get(mapSelector) - - .click(200, 300) - .click(300, 300) - .click(200, 400) - .click(200, 300) - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:enable"); - calledevent = ""; - }); - - cy.window().then(() => { - cy.get(mapSelector) - .click(200, 350); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:vertexadded"); - calledevent = ""; - }); + cy.window() + .then(() => { + cy.get(mapSelector).click(200, 350); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:vertexadded'); + calledevent = ''; + }); - cy.window().then(() => { - cy.get(mapSelector) - .rightclick(200, 350); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:vertexremoved"); - calledevent = ""; - }); + cy.window() + .then(() => { + cy.get(mapSelector).rightclick(200, 350); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:vertexremoved'); + calledevent = ''; + }); - cy.window().then(({map}) => { - map.pm.disableGlobalEditMode(); - }).then(()=>{ - cy.wait(100); - expect(calledeventArr["pm:update"]).to.equal("pm:update"); - calledevent = ""; - calledeventArr = []; - }); + cy.window() + .then(({ map }) => { + map.pm.disableGlobalEditMode(); + }) + .then(() => { + cy.wait(100); + expect(calledeventArr['pm:update']).to.equal('pm:update'); + calledevent = ''; + calledeventArr = []; + }); - cy.window().then(({map}) => { - map.pm.toggleGlobalEditMode(); - map.pm.toggleGlobalEditMode(); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:disable"); - calledevent = ""; - }); + cy.window() + .then(({ map }) => { + map.pm.toggleGlobalEditMode(); + map.pm.toggleGlobalEditMode(); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:disable'); + calledevent = ''; + }); }); - it('pm:cut', () => { - let calledevent = ""; - let calledevent2 = ""; - - cy.window().then(({map}) => { + let calledevent = ''; + let calledevent2 = ''; + + cy.window() + .then(({ map }) => { + map.on('pm:create', ({ layer }) => { + layer.on('pm:cut', (e) => { + calledevent = e.type; + }); + }); - map.on("pm:create",({layer }) => { - layer.on('pm:cut', (e) => { - calledevent = e.type; + map.on('pm:cut', (e) => { + calledevent2 = e.type; }); - }); - map.on('pm:cut',(e) => { - calledevent2 = e.type; + cy.toolbarButton('polygon').click(); + + cy.get(mapSelector) + .click(90, 250) + .click(150, 50) + .click(500, 50) + .click(500, 300) + .click(300, 350) + .click(90, 250); + + cy.toolbarButton('cut').click(); + + // draw a polygon to cut + cy.get(mapSelector) + .click(450, 100) + .click(450, 150) + .click(400, 150) + .click(390, 140) + .click(390, 100) + .click(450, 100); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:cut'); + expect(calledevent2).to.equal('pm:cut'); + calledevent = ''; }); - - cy.toolbarButton('polygon').click(); - - cy.get(mapSelector) - .click(90, 250) - .click(150, 50) - .click(500, 50) - .click(500, 300) - .click(300, 350) - .click(90, 250); - - cy.toolbarButton('cut').click(); - - // draw a polygon to cut - cy.get(mapSelector) - .click(450, 100) - .click(450, 150) - .click(400, 150) - .click(390, 140) - .click(390, 100) - .click(450, 100); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:cut"); - expect(calledevent2).to.equal("pm:cut"); - calledevent = ""; - }); - }); it('pm:remove', () => { - let calledevent = ""; - let calledevent2 = ""; - let calledevent3 = ""; - - cy.window().then(({map}) => { + let calledevent = ''; + let calledevent2 = ''; + let calledevent3 = ''; + + cy.window() + .then(({ map }) => { + map.on('pm:create', ({ layer }) => { + layer.on('pm:remove', (e) => { + calledevent = e.type; + }); + }); - map.on("pm:create",({layer}) => { - layer.on('pm:remove', (e) => { - calledevent = e.type; + map.on('pm:remove', (e) => { + calledevent2 = e.type; + }); + map.on('layerremove', (e) => { + calledevent3 = e.type; }); - }); - map.on('pm:remove',(e) => { - calledevent2 = e.type; + cy.toolbarButton('polygon').click(); + + cy.get(mapSelector) + .click(90, 250) + .click(150, 50) + .click(500, 50) + .click(500, 300) + .click(300, 350) + .click(90, 250); + + cy.toolbarButton('delete').click(); + + cy.get(mapSelector).click(450, 100); + }) + .then(() => { + cy.wait(100); + expect(calledevent).to.equal('pm:remove'); + expect(calledevent2).to.equal('pm:remove'); + expect(calledevent3).to.equal('layerremove'); + calledevent = ''; + calledevent2 = ''; + calledevent3 = ''; }); - map.on('layerremove',(e) => { - calledevent3 = e.type; - }); - - cy.toolbarButton('polygon').click(); - - cy.get(mapSelector) - .click(90, 250) - .click(150, 50) - .click(500, 50) - .click(500, 300) - .click(300, 350) - .click(90, 250); - - cy.toolbarButton('delete').click(); - - cy.get(mapSelector) - .click(450, 100); - }).then(()=>{ - cy.wait(100); - expect(calledevent).to.equal("pm:remove"); - expect(calledevent2).to.equal("pm:remove"); - expect(calledevent3).to.equal("layerremove"); - calledevent = ""; - calledevent2 = ""; - calledevent3 = ""; - }); - }); - it('snappingOrder', () => { - - let event = ""; - cy.window().then(({ map}) => { - map.on('pm:drawstart',(e)=>{ - e.workingLayer.on('pm:snap', (x)=>{event=x}); + let event = ''; + cy.window().then(({ map }) => { + map.on('pm:drawstart', (e) => { + e.workingLayer.on('pm:snap', (x) => { + event = x; + }); }); - map.pm.setGlobalOptions({snappingOrder: ['Marker']}); + map.pm.setGlobalOptions({ snappingOrder: ['Marker'] }); }); cy.window().then(() => { cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(200, 250); + cy.get(mapSelector).click(200, 250); cy.toolbarButton('circle-marker').click(); - cy.get(mapSelector) - .click(200, 250); + cy.get(mapSelector).click(200, 250); cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .trigger("mousemove", 200, 250, { which: 1 }) + cy.get(mapSelector).trigger('mousemove', 200, 250, { which: 1 }); }); cy.window().then(() => { const shape = event.layerInteractedWith.pm._shape; - expect(shape).to.eq("Marker"); + expect(shape).to.eq('Marker'); }); - - cy.window().then(({map}) => { - map.pm.setGlobalOptions({snappingOrder: ['CircleMarker']}); + cy.window().then(({ map }) => { + map.pm.setGlobalOptions({ snappingOrder: ['CircleMarker'] }); map.pm.enableDraw('Marker'); cy.get(mapSelector) - .trigger("mousemove", 200, 150, { which: 1 }) - .trigger("mousemove", 200, 250, { which: 1 }) + .trigger('mousemove', 200, 150, { which: 1 }) + .trigger('mousemove', 200, 250, { which: 1 }); }); cy.window().then(() => { const shape = event.layerInteractedWith.pm._shape; - expect(shape).to.eq("CircleMarker"); + expect(shape).to.eq('CircleMarker'); }); }); }); diff --git a/cypress/integration/globalmodes.spec.js b/cypress/integration/globalmodes.spec.js index a5b71f4a..59bbbd99 100644 --- a/cypress/integration/globalmodes.spec.js +++ b/cypress/integration/globalmodes.spec.js @@ -1,33 +1,27 @@ describe('Modes', () => { const mapSelector = '#map'; it('limits markers in edit mode', () => { - cy.drawShape('MonsterPolygon'); cy.window().then(({ map }) => { map.pm.setGlobalOptions({ - limitMarkersToCount: -1 - }) - }) - + limitMarkersToCount: -1, + }); + }); cy.toolbarButton('edit').click(); cy.hasVertexMarkers(2487); - cy.toolbarButton('edit').click(); - cy.window().then(({ map }) => { map.pm.setGlobalOptions({ - limitMarkersToCount: 20 - }) - }) - + limitMarkersToCount: 20, + }); + }); cy.toolbarButton('edit').click(); cy.hasTotalVertexMarkers(20); - }); it('properly changes markers on vertex removal', () => { @@ -37,8 +31,8 @@ describe('Modes', () => { map.pm.setGlobalOptions({ limitMarkersToCount: 3, limitMarkersToViewport: true, - }) - }) + }); + }); cy.toolbarButton('edit').click(); @@ -49,7 +43,7 @@ describe('Modes', () => { .trigger('contextmenu'); cy.hasTotalVertexMarkers(3); - }) + }); it('respect limits when adding layers mid-edit', () => { cy.drawShape('PolygonPart1'); @@ -58,8 +52,8 @@ describe('Modes', () => { map.pm.setGlobalOptions({ limitMarkersToCount: 3, limitMarkersToViewport: true, - }) - }) + }); + }); cy.toolbarButton('edit').click(); @@ -68,22 +62,18 @@ describe('Modes', () => { cy.drawShape('PolygonPart2'); cy.hasTotalVertexMarkers(6); - }) + }); it('properly removes layers', () => { cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(90, 250) - .click(120, 250); + cy.get(mapSelector).click(90, 250).click(120, 250); cy.toolbarButton('delete').click(); cy.hasLayers(3); - cy.get(mapSelector) - .click(90, 245) - .click(120, 245); + cy.get(mapSelector).click(90, 245).click(120, 245); cy.hasLayers(1); @@ -123,7 +113,7 @@ describe('Modes', () => { const layers = map._layers; expect( - Object.entries(layers).filter(l => l[1] instanceof L.Polygon).length + Object.entries(layers).filter((l) => l[1] instanceof L.Polygon).length ).to.equal(1); }); }); @@ -131,26 +121,22 @@ describe('Modes', () => { it('drag mode enables drag for all layers', () => { cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(90, 250) - .click(120, 250); + cy.get(mapSelector).click(90, 250).click(120, 250); cy.toolbarButton('drag').click(); cy.window().then(({ map, L }) => { - map.eachLayer((layer) => { if (layer instanceof L.Marker) { assert.isTrue(layer.pm.layerDragEnabled()); } - }) + }); }); }); it('drag mode properly disables layers in edit mode', () => { // activate polygon drawing - cy.toolbarButton('polygon') - .click(); + cy.toolbarButton('polygon').click(); // draw a polygon - triggers the event pm:create cy.get(mapSelector) @@ -163,23 +149,20 @@ describe('Modes', () => { cy.window().then(({ map, L }) => { map.eachLayer((l) => { if (l instanceof L.Polygon) { - l.pm.enable() + l.pm.enable(); } - }) + }); map.pm.enableGlobalDragMode(); cy.hasVertexMarkers(0); - }); }); it('reenables drag mode with acceptable performance', () => { - - - cy.toolbarButton('circle-marker').click() - cy.get(mapSelector).click(150, 250) - cy.toolbarButton('drag').click() + cy.toolbarButton('circle-marker').click(); + cy.get(mapSelector).click(150, 250); + cy.toolbarButton('drag').click(); cy.testLayerAdditionPerformance(); }); @@ -212,17 +195,16 @@ describe('Modes', () => { }); it('reenables edit mode with acceptable performance', () => { - - cy.toolbarButton('circle-marker').click() - cy.get(mapSelector).click(150, 250) - cy.toolbarButton('edit').click() + cy.toolbarButton('circle-marker').click(); + cy.get(mapSelector).click(150, 250); + cy.toolbarButton('edit').click(); cy.window().then(({ map, L }) => { map.eachLayer((layer) => { if (layer instanceof L.CircleMarker) { - assert.isTrue(layer.pm.enabled()) + assert.isTrue(layer.pm.enabled()); } - }) + }); }); cy.testLayerAdditionPerformance(); @@ -231,9 +213,7 @@ describe('Modes', () => { it('re-applies removal mode onAdd', () => { cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(90, 250) - .click(120, 250); + cy.get(mapSelector).click(90, 250).click(120, 250); cy.toolbarButton('delete').click(); @@ -251,7 +231,7 @@ describe('Modes', () => { if (l instanceof L.Marker) { cy.wrap(l._icon).click(); } - }) + }); }); cy.hasLayers(1); @@ -268,28 +248,24 @@ describe('Modes', () => { }); it('reenables removal mode with acceptable performance', () => { - - cy.toolbarButton('circle-marker').click() - cy.get(mapSelector).click(150, 250) - cy.toolbarButton('delete').click() + cy.toolbarButton('circle-marker').click(); + cy.get(mapSelector).click(150, 250); + cy.toolbarButton('delete').click(); cy.testLayerAdditionPerformance(); }); - it('Test removal when preventMarkerRremoval is passed to global options', () => { cy.toolbarButton('rectangle') .click() .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.window().then(({ map }) => { map.pm.toggleGlobalEditMode({ - preventMarkerRemoval: true + preventMarkerRemoval: true, }); }); @@ -298,8 +274,7 @@ describe('Modes', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 300); + cy.get(mapSelector).click(200, 300); cy.toolbarButton('delete').click(); @@ -307,17 +282,20 @@ describe('Modes', () => { const layers = map._layers; expect( - Object.entries(layers).filter(l => l[1] instanceof L.Rectangle).length + Object.entries(layers).filter((l) => l[1] instanceof L.Rectangle).length ).to.equal(0); }); }); it('re-enable layers that added while in globaleditmode', () => { - cy.window().then(({ map, L }) => { map.pm.enableGlobalEditMode(); - const json = JSON.parse("{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[-74.058559,40.718564],[-74.058559,40.726045],[-74.03959,40.726045],[-74.03959,40.718564],[-74.058559,40.718564]]]}}"); - const json2 = JSON.parse("{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[-74.035277,40.703719],[-74.035277,40.712633],[-74.017596,40.712633],[-74.017596,40.703719],[-74.035277,40.703719]]]}}"); + const json = JSON.parse( + '{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[-74.058559,40.718564],[-74.058559,40.726045],[-74.03959,40.726045],[-74.03959,40.718564],[-74.058559,40.718564]]]}}' + ); + const json2 = JSON.parse( + '{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[-74.035277,40.703719],[-74.035277,40.712633],[-74.017596,40.712633],[-74.017596,40.703719],[-74.035277,40.703719]]]}}' + ); const p2 = L.geoJson(json).addTo(map); L.geoJson(json2).addTo(map); @@ -325,6 +303,5 @@ describe('Modes', () => { map.setZoom(13); }); cy.hasVertexMarkers(8); - }); }); diff --git a/cypress/integration/imageoverlay.spec.js b/cypress/integration/imageoverlay.spec.js index fdad2769..cd8c773e 100644 --- a/cypress/integration/imageoverlay.spec.js +++ b/cypress/integration/imageoverlay.spec.js @@ -2,31 +2,35 @@ describe('Opens Testing Environment', () => { const mapSelector = '#map'; it('Snap to ImageOverlay', () => { - let eventcalled = ""; + let eventcalled = ''; cy.window().then(({ map, L }) => { - map.setView([18.74469, 72.1258],10); - const icon = 'https://camo.githubusercontent.com/33fa9a94048274f81a806631ca881a55c2aa8f0a/68747470733a2f2f66696c652d6a787a796a67717775742e6e6f772e73682f'; - L.imageOverlay(icon, [[18.74469, 72.1258], [18.94469, 72.3258]], {interactive: true}) - .addTo(map); + map.setView([18.74469, 72.1258], 10); + const icon = + 'https://camo.githubusercontent.com/33fa9a94048274f81a806631ca881a55c2aa8f0a/68747470733a2f2f66696c652d6a787a796a67717775742e6e6f772e73682f'; + L.imageOverlay( + icon, + [ + [18.74469, 72.1258], + [18.94469, 72.3258], + ], + { interactive: true } + ).addTo(map); - map.on('pm:drawstart',(e)=>{ + map.on('pm:drawstart', (e) => { const layer = e.workingLayer; - layer.on('pm:snap', (x)=>eventcalled = x.type); + layer.on('pm:snap', (x) => (eventcalled = x.type)); }); }); - cy.toolbarButton('polygon') - .click(); + cy.toolbarButton('polygon').click(); - cy.window().then(({map}) => { + cy.window().then(({ map }) => { const point = map.latLngToContainerPoint([18.74469, 72.1258]); - cy.get(mapSelector) - .click(point); + cy.get(mapSelector).click(point); }); cy.window().then(({}) => { - expect(eventcalled).to.equal("pm:snap"); + expect(eventcalled).to.equal('pm:snap'); }); - }); }); diff --git a/cypress/integration/layergroup.spec.js b/cypress/integration/layergroup.spec.js index 80a8bc70..478ec7c5 100644 --- a/cypress/integration/layergroup.spec.js +++ b/cypress/integration/layergroup.spec.js @@ -20,34 +20,34 @@ describe('Edit LayerGroup', () => { it('enables all layers of layerGroup', () => { cy.drawShape('FeatureCollectionWithCircles'); - cy.get('@featurecol').then(feature => { + cy.get('@featurecol').then((feature) => { feature.pm.enable(); }); cy.hasVertexMarkers(21); - cy.get('@featurecol').then(feature => { + cy.get('@featurecol').then((feature) => { feature.pm.disable(); }); cy.hasVertexMarkers(0); - cy.get('@featurecol').then(feature => { + cy.get('@featurecol').then((feature) => { feature.pm.toggleEdit(); }); cy.hasVertexMarkers(21); - cy.get('@featurecol').then(feature => { + cy.get('@featurecol').then((feature) => { feature.pm.toggleEdit(); }); cy.hasVertexMarkers(0); }); it('supports clearLayers', () => { - cy.window().then(({L, map}) => { + cy.window().then(({ L, map }) => { const featureGroup = new L.FeatureGroup(); - featureGroup.addTo(map) + featureGroup.addTo(map); featureGroup.addLayer(new L.Marker([19.04469, 72.9258])); - map.fitBounds(featureGroup.getBounds()) + map.fitBounds(featureGroup.getBounds()); featureGroup.clearLayers(); expect(featureGroup.pm._layers).to.have.lengthOf(0); @@ -59,26 +59,24 @@ describe('Edit LayerGroup', () => { let fg2; // Add layer to group - cy.window().then(({L, map}) => { + cy.window().then(({ L, map }) => { fg = L.featureGroup().addTo(map); fg2 = L.featureGroup().addTo(map); - map.pm.setGlobalOptions({layerGroup: fg}); + map.pm.setGlobalOptions({ layerGroup: fg }); cy.toolbarButton('rectangle') .click() .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.hasLayers(5); }); // check if layer is on group and will be removed from map, when group is removed - cy.window().then(({map}) => { + cy.window().then(({ map }) => { fg.removeFrom(map); cy.hasLayers(3); @@ -86,14 +84,12 @@ describe('Edit LayerGroup', () => { expect(count).to.equal(1); }); // delete layer from group and map - cy.window().then(({map}) => { + cy.window().then(({ map }) => { fg.addTo(map); - cy.toolbarButton('delete') - .click(); + cy.toolbarButton('delete').click(); - cy.get(mapSelector) - .click(280, 280); + cy.get(mapSelector).click(280, 280); }); cy.window().then(() => { const count = fg.getLayers().length; @@ -102,30 +98,22 @@ describe('Edit LayerGroup', () => { // add layer and then change group cy.window().then(() => { - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); }); - cy.window().then(({map}) => { - map.pm.setGlobalOptions({layerGroup: fg2}); + cy.window().then(({ map }) => { + map.pm.setGlobalOptions({ layerGroup: fg2 }); cy.hasLayers(5); - cy.toolbarButton('circle') - .click(); - cy.get(mapSelector) - .click(200, 200) - .click(250, 250); + cy.toolbarButton('circle').click(); + cy.get(mapSelector).click(200, 200).click(250, 250); }); // delete layer from another (first) group cy.window().then(() => { - cy.toolbarButton('delete') - .click(); + cy.toolbarButton('delete').click(); - cy.get(mapSelector) - .click(280, 280); + cy.get(mapSelector).click(280, 280); }); cy.window().then(() => { const count = fg.getLayers().length; @@ -136,32 +124,29 @@ describe('Edit LayerGroup', () => { }); // delete circle from second group cy.window().then(() => { - cy.get(mapSelector) - .click(180, 180); - cy.toolbarButton('delete') - .click(); + cy.get(mapSelector).click(180, 180); + cy.toolbarButton('delete').click(); }); cy.window().then(() => { const count2 = fg2.getLayers().length; expect(count2).to.equal(0); cy.hasLayers(4); }); - }) - + }); it('pass the fired event of the layer to group', () => { let fg; - let firedEvent = ""; + let firedEvent = ''; - cy.window().then(({map, L}) => { + cy.window().then(({ map, L }) => { fg = L.featureGroup(); - fg.on("pm:cut", (e) => { + fg.on('pm:cut', (e) => { firedEvent = e.type; }); map.on('pm:create', (e) => { e.layer.addTo(fg); - }) + }); }); // activate polygon drawing cy.toolbarButton('polygon') @@ -199,17 +184,19 @@ describe('Edit LayerGroup', () => { }); it('event is fired only once if group has multiple sub-groups with the same layer', () => { - let firedEventCount = 0; - cy.window().then(({map, L}) => { + cy.window().then(({ map, L }) => { const group = L.featureGroup().addTo(map); const layers = L.featureGroup().addTo(group); const markers = L.featureGroup().addTo(group); const markersChild = L.featureGroup().addTo(markers); - L.marker(map.getCenter()).addTo(layers).addTo(markers).addTo(markersChild); + L.marker(map.getCenter()) + .addTo(layers) + .addTo(markers) + .addTo(markersChild); group.on('pm:enable', () => { - firedEventCount += 1 + firedEventCount += 1; }); }); @@ -223,26 +210,28 @@ describe('Edit LayerGroup', () => { }); it('event is fired on every parent group of a layer (once)', () => { - let firedEventCount = 0; - cy.window().then(({map, L}) => { + cy.window().then(({ map, L }) => { const group = L.featureGroup().addTo(map); const layers = L.featureGroup().addTo(group); const markers = L.featureGroup().addTo(group); const markersChild = L.featureGroup().addTo(markers); - L.marker(map.getCenter()).addTo(layers).addTo(markers).addTo(markersChild); + L.marker(map.getCenter()) + .addTo(layers) + .addTo(markers) + .addTo(markersChild); group.on('pm:enable', () => { - firedEventCount += 1 + firedEventCount += 1; }); layers.on('pm:enable', () => { - firedEventCount += 1 + firedEventCount += 1; }); markers.on('pm:enable', () => { - firedEventCount += 1 + firedEventCount += 1; }); markersChild.on('pm:enable', () => { - firedEventCount += 1 + firedEventCount += 1; }); }); @@ -259,9 +248,9 @@ describe('Edit LayerGroup', () => { cy.drawShape('FeatureCollectionEventFire'); let firedEventCount = 0; - cy.get('@feature').then(feature => { + cy.get('@feature').then((feature) => { feature.on('pm:enable', () => { - firedEventCount += 1 + firedEventCount += 1; }); }); @@ -275,21 +264,18 @@ describe('Edit LayerGroup', () => { }); it('new added layers will be changed to edit mode if editmode is enabled', () => { - cy.window().then(({map, L}) => { - map.setView([4.009783550466563,104.00000000000006],8); + cy.window().then(({ map, L }) => { + map.setView([4.009783550466563, 104.00000000000006], 8); const fg = L.featureGroup().addTo(map); - map.on('pm:create layeradd',(e)=>{ + map.on('pm:create layeradd', (e) => { e.layer.addTo(fg); - }) + }); }); - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.toolbarButton('edit').click(); @@ -298,79 +284,67 @@ describe('Edit LayerGroup', () => { cy.hasVertexMarkers(12); }); - it('new drawn markers not enable other layers in the same layergroup', () => { - cy.window().then(({map, L}) => { - map.setView([4.009783550466563,104.00000000000006],8); + cy.window().then(({ map, L }) => { + map.setView([4.009783550466563, 104.00000000000006], 8); const fg = L.featureGroup().addTo(map); - map.on('pm:create layeradd',(e)=>{ + map.on('pm:create layeradd', (e) => { e.layer.addTo(fg); - }) + }); }); - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); - cy.toolbarButton('marker') - .click(); + cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(450, 350); + cy.get(mapSelector).click(450, 350); cy.hasVertexMarkers(0); }); - it("re-init GeoJSON OptIn", ()=>{ + it('re-init GeoJSON OptIn', () => { let layerGroup; cy.window().then(({ map, L }) => { - cy.fixture("LineString") + cy.fixture('LineString') .as('poly') - .then(json => { - layerGroup = L.geoJson(json, {pmIgnore: true}).addTo(map); + .then((json) => { + layerGroup = L.geoJson(json, { pmIgnore: true }).addTo(map); const bounds = layerGroup.getBounds(); map.fitBounds(bounds); }); }); - cy.window().then(({map, L}) => { + cy.window().then(({ map, L }) => { expect(map.pm.getGeomanLayers().length).to.eq(0); // enable all child layers of the group - layerGroup.setStyle({pmIgnore:false}); + layerGroup.setStyle({ pmIgnore: false }); // enable the group self layerGroup.options.pmIgnore = false; L.PM.reInitLayer(layerGroup); expect(layerGroup.pm).to.not.eq(undefined); expect(map.pm.getGeomanLayers().length).to.eq(6); - }) + }); }); it('adds options to layers before throlle is fired', () => { - cy.toolbarButton('rectangle') - .click(); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.toolbarButton('rectangle').click(); + cy.get(mapSelector).click(200, 200).click(400, 350); - cy.toolbarButton('rectangle') - .click(); - cy.get(mapSelector) - .click(350, 200) - .click(400, 400); + cy.toolbarButton('rectangle').click(); + cy.get(mapSelector).click(350, 200).click(400, 400); - cy.window().then(({map, L}) => { + cy.window().then(({ map, L }) => { const fg = L.featureGroup().addTo(map); - var layers = map.pm.getGeomanDrawLayers(); - layers.forEach((layer)=>{ + const layers = map.pm.getGeomanDrawLayers(); + layers.forEach((layer) => { fg.addLayer(layer); }); - fg.pm.setOptions({syncLayersOnDrag: true}); + fg.pm.setOptions({ syncLayersOnDrag: true }); expect(layers[1].pm.options.syncLayersOnDrag).to.eq(true); }); diff --git a/cypress/integration/line.spec.js b/cypress/integration/line.spec.js index cf45ad3f..2df98a51 100644 --- a/cypress/integration/line.spec.js +++ b/cypress/integration/line.spec.js @@ -6,9 +6,7 @@ describe('Draw & Edit Line', () => { it('doesnt finish single point lines', () => { cy.toolbarButton('polyline').click(); - cy.get(mapSelector) - .click(90, 250) - .click(90, 250); + cy.get(mapSelector).click(90, 250).click(90, 250); cy.toolbarButton('edit').click(); @@ -36,17 +34,16 @@ describe('Draw & Edit Line', () => { }); it('respects custom style', () => { - cy.window().then(({ map }) => { map.on('pm:create', (e) => { e.layer.pm.enable({ allowSelfIntersection: false, snappable: false, - snapDistance: 20 + snapDistance: 20, }); e.layer.setStyle({ color: 'black' }); - }) + }); map.pm.enableDraw('Polygon', { snappable: false, @@ -56,7 +53,7 @@ describe('Draw & Edit Line', () => { templineStyle: { color: 'orange', dashArray: [10, 10], - weight: 5 + weight: 5, }, hintlineStyle: { color: 'orange', @@ -69,8 +66,8 @@ describe('Draw & Edit Line', () => { dashArray: [10, 10], weight: 5, fillOpacity: 1, - opacity: 1 - } + opacity: 1, + }, }); }); @@ -81,7 +78,7 @@ describe('Draw & Edit Line', () => { .click(300, 200) .click(120, 150); - cy.toolbarButton('polygon').click() + cy.toolbarButton('polygon').click(); cy.get(mapSelector) .click(320, 150) @@ -90,18 +87,15 @@ describe('Draw & Edit Line', () => { .click(400, 200) .click(320, 150); - cy.toolbarButton('edit').click() + cy.toolbarButton('edit').click(); cy.window().then(({ map, L }) => { map.eachLayer((l) => { - if (l instanceof L.Polygon) - expect(l.options.color).to.equal('black'); - }) + if (l instanceof L.Polygon) expect(l.options.color).to.equal('black'); + }); }); }); - - it('draws and edits a line', () => { cy.hasLayers(1); @@ -133,9 +127,7 @@ describe('Draw & Edit Line', () => { cy.hasMiddleMarkers(3); // press a middle marker - cy.get('.marker-icon-middle') - .first() - .click(); + cy.get('.marker-icon-middle').first().click(); // now there should be one more vertex cy.hasVertexMarkers(5); @@ -175,18 +167,17 @@ describe('Draw & Edit Line', () => { .click(150, 250); cy.window().then(({ map }) => { - map.pm.setGlobalOptions({hideMiddleMarkers: true}); + map.pm.setGlobalOptions({ hideMiddleMarkers: true }); }); - cy.toolbarButton('edit') - .click(); + cy.toolbarButton('edit').click(); cy.hasMiddleMarkers(0); }); it('enable continueDrawing', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({continueDrawing: true}); + map.pm.setGlobalOptions({ continueDrawing: true }); }); cy.toolbarButton('polyline').click(); @@ -198,11 +189,7 @@ describe('Draw & Edit Line', () => { .click(250, 50) .click(250, 50); - cy.get(mapSelector) - .click(200, 200) - .click(250, 250) - .click(250, 250); - + cy.get(mapSelector).click(200, 200).click(250, 250).click(250, 250); cy.toolbarButton('edit').click(); cy.hasVertexMarkers(5); @@ -213,9 +200,7 @@ describe('Draw & Edit Line', () => { cy.toolbarButton('edit').click(); - cy.get(mapSelector) - .rightclick(641,462) - .rightclick(702,267); + cy.get(mapSelector).rightclick(641, 462).rightclick(702, 267); cy.hasVertexMarkers(3); cy.hasMiddleMarkers(2); @@ -226,10 +211,10 @@ describe('Draw & Edit Line', () => { cy.toolbarButton('cut').click(); cy.get(mapSelector) - .click(394,203) - .click(333,77) - .click(607,112) - .click(394,203); + .click(394, 203) + .click(333, 77) + .click(607, 112) + .click(394, 203); cy.toolbarButton('edit').click(); cy.hasVertexMarkers(10); @@ -244,7 +229,10 @@ describe('Draw & Edit Line', () => { it('requireSnapToFinish', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({requireSnapToFinish: true, snapSegment: false}); + map.pm.setGlobalOptions({ + requireSnapToFinish: true, + snapSegment: false, + }); }); cy.toolbarButton('polygon').click(); @@ -255,18 +243,14 @@ describe('Draw & Edit Line', () => { .click(150, 250); cy.toolbarButton('polyline').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 160) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 160).click(190, 60); cy.window().then(({ map }) => { map.pm.Draw.Line._finishShape(); expect(1).to.eq(map.pm.getGeomanDrawLayers().length); }); - cy.get(mapSelector) - .click(250, 50); + cy.get(mapSelector).click(250, 50); cy.window().then(({ map }) => { map.pm.Draw.Line._finishShape(); diff --git a/cypress/integration/marker.spec.js b/cypress/integration/marker.spec.js index fb027753..7ababde1 100644 --- a/cypress/integration/marker.spec.js +++ b/cypress/integration/marker.spec.js @@ -2,26 +2,23 @@ describe('Draw Marker', () => { const mapSelector = '#map'; it('enables drag in programatic global edit mode', () => { - cy.toolbarButton('marker').click(); - cy.wait(1000) + cy.wait(1000); - cy.get(mapSelector) - .click(150, 250) + cy.get(mapSelector).click(150, 250); - cy.wait(1000) + cy.wait(1000); cy.window().then(({ map, L }) => { - map.pm.enableGlobalEditMode() + map.pm.enableGlobalEditMode(); map.eachLayer((layer) => { if (layer instanceof L.Marker) { - assert.isTrue(layer.pm.layerDragEnabled()) + assert.isTrue(layer.pm.layerDragEnabled()); } - }) + }); }); - }); it('removes markers without error', () => { @@ -37,7 +34,7 @@ describe('Draw Marker', () => { .then(() => { let l; let m; - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer._leaflet_id === markerLayer._leaflet_id) { l = layer; } else if (layer instanceof L.Marker) { @@ -54,7 +51,7 @@ describe('Draw Marker', () => { .as('markerLayer'); }); - cy.get('@markerLayer').then(markerLayer => { + cy.get('@markerLayer').then((markerLayer) => { markerLayer.pm.disable(); }); }); @@ -68,21 +65,24 @@ describe('Draw Marker', () => { .click(500, 50) .click(500, 300); - cy.get('.leaflet-marker-icon').should($p => { + cy.get('.leaflet-marker-icon').should(($p) => { expect($p).to.have.length(5); }); cy.toolbarButton('marker').click(); - cy.get('.leaflet-marker-icon').should($p => { + cy.get('.leaflet-marker-icon').should(($p) => { expect($p).to.have.length(4); }); }); - it('add interactive:false marker to the map and enable edit', () => { // Adds a interactive Marker to the map and enable / disable the edit mode to check if a error is thrown because it is not draggable - cy.window().then(({ map, L }) => L.marker([51.505, -0.09], { interactive: false }).addTo(map)).as('marker'); + cy.window() + .then(({ map, L }) => + L.marker([51.505, -0.09], { interactive: false }).addTo(map) + ) + .as('marker'); cy.toolbarButton('edit').click(); @@ -90,8 +90,8 @@ describe('Draw Marker', () => { cy.toolbarButton('edit').click(); - cy.get('@marker').then( marker => { - marker.removeFrom(marker._map); + cy.get('@marker').then((marker) => { + marker.removeFrom(marker._map); }); }); @@ -101,26 +101,24 @@ describe('Draw Marker', () => { let drag = false; let dragend = false; - cy.window().then(({map}) =>{ - map.on('pm:create',(e)=>{ - e.layer.on('pm:dragstart',()=>{ + cy.window().then(({ map }) => { + map.on('pm:create', (e) => { + e.layer.on('pm:dragstart', () => { dragstart = true; }); - e.layer.on('pm:drag',()=>{ + e.layer.on('pm:drag', () => { drag = true; }); - e.layer.on('pm:dragend',()=>{ + e.layer.on('pm:dragend', () => { dragend = true; }); - }) - + }); }); cy.toolbarButton('marker').click(); - cy.wait(1000) - cy.get(mapSelector) - .click(150, 250) - cy.wait(1000) + cy.wait(1000); + cy.get(mapSelector).click(150, 250); + cy.wait(1000); cy.toolbarButton('marker').click(); cy.toolbarButton('drag').click(); @@ -132,24 +130,28 @@ describe('Draw Marker', () => { expect(drag).to.equal(true); expect(dragend).to.equal(true); handFinish = true; - } + }, }); const toucherMarker = handMarker.growFinger('mouse'); - toucherMarker.wait(100).moveTo(150, 240, 100).down().wait(500).moveTo(170, 290, 400).up().wait(100) // Not allowed - + toucherMarker + .wait(100) + .moveTo(150, 240, 100) + .down() + .wait(500) + .moveTo(170, 290, 400) + .up() + .wait(100); // Not allowed }); // wait until hand is finished - cy.waitUntil(() => cy.window().then(() => handFinish)).then( ()=> { + cy.waitUntil(() => cy.window().then(() => handFinish)).then(() => { expect(handFinish).to.equal(true); }); }); - it('enabled of Marker is true in edit-mode', () => { cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(150, 250); + cy.get(mapSelector).click(150, 250); cy.toolbarButton('edit').click(); cy.window().then(({ map }) => { @@ -161,16 +163,13 @@ describe('Draw Marker', () => { it('disable continueDrawing', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({continueDrawing: false}); + map.pm.setGlobalOptions({ continueDrawing: false }); }); cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(191,216); - - cy.get(mapSelector) - .click(350, 350); + cy.get(mapSelector).click(191, 216); + cy.get(mapSelector).click(350, 350); cy.toolbarButton('edit').click(); cy.hasLayers(2); @@ -178,12 +177,11 @@ describe('Draw Marker', () => { it('disable markerEditable', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({markerEditable: false}); + map.pm.setGlobalOptions({ markerEditable: false }); }); cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(191,216); + cy.get(mapSelector).click(191, 216); cy.window().then(({ map }) => { const marker = map.pm.getGeomanDrawLayers()[0]; @@ -194,12 +192,14 @@ describe('Draw Marker', () => { it('enable markerEditable but disable MarkerRemoval', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({markerEditable: true, preventMarkerRemoval: true}); + map.pm.setGlobalOptions({ + markerEditable: true, + preventMarkerRemoval: true, + }); }); cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(191,216); + cy.get(mapSelector).click(191, 216); cy.window().then(({ map }) => { const marker = map.pm.getGeomanDrawLayers()[0]; @@ -207,14 +207,16 @@ describe('Draw Marker', () => { expect(enabled).to.equal(true); }); - cy.get(mapSelector) - .rightclick(191,214); + cy.get(mapSelector).rightclick(191, 214); cy.hasLayers(4); }); it('requireSnapToFinish', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({requireSnapToFinish: true, snapSegment: false}); + map.pm.setGlobalOptions({ + requireSnapToFinish: true, + snapSegment: false, + }); }); cy.toolbarButton('polygon').click(); @@ -225,16 +227,13 @@ describe('Draw Marker', () => { .click(150, 250); cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 60); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); }); - cy.get(mapSelector) - .click(250, 50); + cy.get(mapSelector).click(250, 50); cy.window().then(({ map }) => { expect(2).to.eq(map.pm.getGeomanDrawLayers().length); diff --git a/cypress/integration/options.spec.js b/cypress/integration/options.spec.js index cfbc6228..60ded48e 100644 --- a/cypress/integration/options.spec.js +++ b/cypress/integration/options.spec.js @@ -1,13 +1,10 @@ describe('Options', () => { // Trying to test options requires drag and drop but I cant make it work with cypress yet - - const mapSelector = '#map'; it('Pinning fires pm:edit', () => { - cy.toolbarButton('polygon') - .click() + cy.toolbarButton('polygon').click(); cy.window().then(({ map, L }) => { cy.get(mapSelector) @@ -18,7 +15,7 @@ describe('Options', () => { .click(90, 250) .then(() => { let l; - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.Polygon) { layer.pm.enable(); l = layer; @@ -26,26 +23,23 @@ describe('Options', () => { }); return l; }) - .as('poly') + .as('poly'); }); - cy.get('@poly').then(poly => { + cy.get('@poly').then((poly) => { poly.on('pm:edit', (e) => { - console.log(e) - }) + console.log(e); + }); }); - cy.toolbarButton('marker').click() - cy.get(mapSelector).click(150, 150) - - - cy.toolbarButton('edit').click() + cy.toolbarButton('marker').click(); + cy.get(mapSelector).click(150, 150); + cy.toolbarButton('edit').click(); }); it('sets global options', () => { - cy.toolbarButton('polygon') - .click() + cy.toolbarButton('polygon').click(); cy.window().then(({ map, L }) => { cy.get(mapSelector) @@ -56,7 +50,7 @@ describe('Options', () => { .click(90, 250) .then(() => { let l; - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.Polygon) { layer.pm.enable(); l = layer; @@ -64,57 +58,52 @@ describe('Options', () => { }); return l; }) - .as('poly') + .as('poly'); }); cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(300, 100) + cy.get(mapSelector).click(300, 100); - cy.toolbarButton('edit') - .click() + cy.toolbarButton('edit').click(); cy.window().then(({ map }) => { map.pm.setGlobalOptions({ pinning: false, - snappable: false - }) - }) + snappable: false, + }); + }); - cy.get('@poly').then(poly => { + cy.get('@poly').then((poly) => { expect(poly.pm.options.snappable).to.equal(false); }); cy.window().then(({ map }) => { map.pm.setGlobalOptions({ pinning: true, - snappable: true - }) - }) + snappable: true, + }); + }); - cy.get('@poly').then(poly => { + cy.get('@poly').then((poly) => { expect(poly.pm.options.snappable).to.equal(true); }); - - }); it('global options work on Draw', () => { cy.window().then(({ map }) => { map.pm.setGlobalOptions({ - snappable: false - }) - }) + snappable: false, + }); + }); cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(300, 100) + cy.get(mapSelector).click(300, 100); cy.window().then(({ map }) => { expect(map.pm.Draw.Marker.options.snappable).to.equal(false); - }) + }); // cy.get(mapSelector) // .click(120, 150) @@ -144,29 +133,36 @@ describe('Options', () => { // cy.toolbarButton('pinning').click(); // cy.toolbarButton('edit').click(); - }); it('merge PathOptions', () => { - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.setPathOptions({ - color: 'red' + color: 'red', }); expect(map.pm.Draw.Line.options.pathOptions.color).to.equal('red'); - expect(map.pm.Draw.Line.options.pathOptions.borderColor).to.equal(undefined); + expect(map.pm.Draw.Line.options.pathOptions.borderColor).to.equal( + undefined + ); map.pm.setPathOptions({ - borderColor: 'green' + borderColor: 'green', }); expect(map.pm.Draw.Line.options.pathOptions.color).to.equal(undefined); - expect(map.pm.Draw.Line.options.pathOptions.borderColor).to.equal('green'); - - - map.pm.setPathOptions({ - color: 'red' - },{merge: true}); + expect(map.pm.Draw.Line.options.pathOptions.borderColor).to.equal( + 'green' + ); + + map.pm.setPathOptions( + { + color: 'red', + }, + { merge: true } + ); expect(map.pm.Draw.Line.options.pathOptions.color).to.equal('red'); - expect(map.pm.Draw.Line.options.pathOptions.borderColor).to.equal('green'); + expect(map.pm.Draw.Line.options.pathOptions.borderColor).to.equal( + 'green' + ); }); }); }); diff --git a/cypress/integration/polygon.spec.js b/cypress/integration/polygon.spec.js index bfc76976..8c428662 100644 --- a/cypress/integration/polygon.spec.js +++ b/cypress/integration/polygon.spec.js @@ -13,11 +13,9 @@ describe('Draw & Edit Poly', () => { cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(300, 100) + cy.get(mapSelector).click(300, 100); cy.toolbarButton('edit').click(); - }); it('works without pmIgnore', () => { @@ -70,9 +68,9 @@ describe('Draw & Edit Poly', () => { it('pmIgnore:true disable editing', () => { cy.window().then(({ map }) => { - map.on('pm:create',(e)=> { + map.on('pm:create', (e) => { e.layer.options.pmIgnore = true; - }) + }); }); cy.toolbarButton('polygon').click(); @@ -88,12 +86,11 @@ describe('Draw & Edit Poly', () => { cy.hasVertexMarkers(0); }); - it('pmIgnore:true disable deleting', () => { cy.window().then(({ map }) => { - map.on('pm:create',(e)=> { + map.on('pm:create', (e) => { e.layer.options.pmIgnore = true; - }) + }); }); cy.toolbarButton('polygon').click(); @@ -106,8 +103,7 @@ describe('Draw & Edit Poly', () => { cy.hasDrawnLayers(1); cy.toolbarButton('delete').click(); - cy.get(mapSelector) - .click(220, 160); + cy.get(mapSelector).click(220, 160); cy.hasDrawnLayers(1); }); @@ -125,11 +121,11 @@ describe('Draw & Edit Poly', () => { it('respects optIn and reinit layer', () => { cy.window().then(({ L }) => { L.PM.setOptIn(true); - cy.drawShape('MultiPolygon').then((poly)=>{ + cy.drawShape('MultiPolygon').then((poly) => { cy.hasVertexMarkers(0); // Not allowed because optIn L.PM.setOptIn(false); L.PM.reInitLayer(poly); - }) + }); }); cy.toolbarButton('edit').click(); @@ -139,19 +135,19 @@ describe('Draw & Edit Poly', () => { it('respects optIn and reinit layer with pmIgnore', () => { cy.window().then(({ L }) => { L.PM.setOptIn(true); - cy.drawShape('MultiPolygon',true).then((poly)=>{ + cy.drawShape('MultiPolygon', true).then((poly) => { cy.hasVertexMarkers(0); // Not allowed because optIn - L.PM.reInitLayer(poly);// Not allowed because pmIgnore is not false + L.PM.reInitLayer(poly); // Not allowed because pmIgnore is not false cy.hasVertexMarkers(0); L.PM.setOptIn(false); - L.PM.reInitLayer(poly);// Not allowed because pmIgnore is true + L.PM.reInitLayer(poly); // Not allowed because pmIgnore is true cy.hasVertexMarkers(0); poly.options.pmIgnore = false; - poly.eachLayer((layer)=>{ + poly.eachLayer((layer) => { layer.options.pmIgnore = false; }); - L.PM.reInitLayer(poly);// Allowed because pmIgnore is not true - }) + L.PM.reInitLayer(poly); // Allowed because pmIgnore is not true + }); }); cy.toolbarButton('edit').click(); @@ -162,10 +158,10 @@ describe('Draw & Edit Poly', () => { cy.window().then(({ L }) => { L.PM.setOptIn(true); cy.drawShape('MultiPolygon'); - cy.drawShape('MultiPolygon',false).then(()=>{ + cy.drawShape('MultiPolygon', false).then(() => { L.PM.setOptIn(false); cy.drawShape('MultiPolygon'); - }) + }); }); cy.toolbarButton('edit').click(); @@ -176,9 +172,7 @@ describe('Draw & Edit Poly', () => { it('doesnt finish single point polys', () => { cy.toolbarButton('polygon').click(); - cy.get(mapSelector) - .click(90, 250) - .click(90, 250); + cy.get(mapSelector).click(90, 250).click(90, 250); cy.toolbarButton('edit').click(); @@ -190,10 +184,9 @@ describe('Draw & Edit Poly', () => { it('handles polygon additions mid-drawing', () => { // for manual testing cy.toolbarButton('polygon').click(); - cy.get(mapSelector) - .click(90, 250); + cy.get(mapSelector).click(90, 250); - cy.wait(2000) + cy.wait(2000); cy.drawShape('LineString', true); // manual test if snapping works here @@ -202,9 +195,7 @@ describe('Draw & Edit Poly', () => { it('doesnt finish two point polys', () => { cy.toolbarButton('polygon').click(); - cy.get(mapSelector) - .click(90, 250) - .click(100, 350); + cy.get(mapSelector).click(90, 250).click(100, 350); cy.get('.active .action-finish').click(); @@ -343,7 +334,6 @@ describe('Draw & Edit Poly', () => { }); it('prevent creation while self intersection', () => { - cy.window().then(({ map }) => { map.pm.enableDraw('Polygon', { allowSelfIntersection: false, @@ -351,11 +341,11 @@ describe('Draw & Edit Poly', () => { }); cy.get(mapSelector) - .click(470,100) - .click(320,220) - .click(600,220) + .click(470, 100) + .click(320, 220) + .click(600, 220) .click(470, 350) - .click(470,100); + .click(470, 100); cy.toolbarButton('polygon').click(); @@ -407,7 +397,7 @@ describe('Draw & Edit Poly', () => { .click(90, 250) .then(() => { let l; - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.Polygon) { layer.pm.enable(); l = layer; @@ -416,11 +406,11 @@ describe('Draw & Edit Poly', () => { return l; }) .as('poly') - .then(poly => poly._latlngs[0][0]) + .then((poly) => poly._latlngs[0][0]) .as('firstLatLng'); }); - cy.get('@poly').then(poly => { + cy.get('@poly').then((poly) => { Cypress.$(poly).on('pm:vertexadded', ({ originalEvent: event }) => { const { layer, indexPath, latlng } = event; const newLatLng = Cypress._.get(layer._latlngs, indexPath); @@ -431,8 +421,8 @@ describe('Draw & Edit Poly', () => { cy.get('.marker-icon-middle').click({ multiple: true }); - cy.get('@poly').then(poly => { - cy.get('@firstLatLng').then(oldFirst => { + cy.get('@poly').then((poly) => { + cy.get('@firstLatLng').then((oldFirst) => { const newFirst = poly._latlngs[0][0]; expect(oldFirst.lat).to.equal(newFirst.lat); expect(oldFirst.lng).to.equal(newFirst.lng); @@ -510,9 +500,7 @@ describe('Draw & Edit Poly', () => { cy.hasMiddleMarkers(5); // press a middle marker - cy.get('.marker-icon-middle') - .first() - .click(); + cy.get('.marker-icon-middle').first().click(); // now there should be one more vertex cy.hasVertexMarkers(6); @@ -548,22 +536,20 @@ describe('Draw & Edit Poly', () => { it('fire pm:cut AFTER the actual cut is visible on the map', () => { cy.window().then(({ map, L }) => { - Cypress.$(map).on('pm:cut', () => { const layers = []; map.eachLayer((layer) => { if (layer instanceof L.Polygon) { - layers.push(layer) + layers.push(layer); } - }) + }); expect(layers).to.have.lengthOf(1); }); }); - cy.toolbarButton('polygon') - .click() + cy.toolbarButton('polygon').click(); cy.get(mapSelector) .click(90, 250) @@ -573,9 +559,7 @@ describe('Draw & Edit Poly', () => { .click(300, 350) .click(90, 250); - - cy.toolbarButton('cut') - .click(); + cy.toolbarButton('cut').click(); // draw a polygon to cut cy.get(mapSelector) @@ -585,9 +569,7 @@ describe('Draw & Edit Poly', () => { .click(390, 140) .click(390, 100) .click(450, 100); - - - }) + }); it('draws a polygon with a hole', () => { // activate polygon drawing @@ -689,12 +671,10 @@ describe('Draw & Edit Poly', () => { cy.toolbarButton('edit').click(); }); - it('allowSelfIntersectionEdit on polygon', () => { - - cy.window().then(({ map, L,Hand }) => { - cy.fixture("PolygonIntersects") - .then(json => { + cy.window().then(({ map, L, Hand }) => { + cy.fixture('PolygonIntersects') + .then((json) => { const layer = L.geoJSON(json).getLayers()[0].addTo(map); const bounds = layer.getBounds(); map.fitBounds(bounds); @@ -702,13 +682,13 @@ describe('Draw & Edit Poly', () => { }) .as('poly'); - cy.get("@poly").then((poly)=>{ + cy.get('@poly').then((poly) => { let handFinish = false; expect(poly.pm.hasSelfIntersection()).to.equal(true); const handSelfIntersectionFalse = new Hand({ timing: 'frame', - onStop () { + onStop() { expect(poly.pm.hasSelfIntersection()).to.equal(false); // Map shouldn't be dragged @@ -716,37 +696,71 @@ describe('Draw & Edit Poly', () => { expect(center.lat).to.equal(48.77492609799526); expect(center.lng).to.equal(4.847301999999988); handFinish = true; - } + }, }); const handSelfIntersectionTrue = new Hand({ timing: 'frame', - onStop () { + onStop() { expect(poly.pm.hasSelfIntersection()).to.equal(true); - const toucherSelfIntersectionFalse = handSelfIntersectionFalse.growFinger('mouse'); - toucherSelfIntersectionFalse.wait(100).moveTo(504, 337, 100).down().wait(500).moveTo(780, 259, 400).up().wait(100) // allowed - // No intersection anymore - .moveTo(294, 114, 100).down().wait(500).moveTo(752, 327, 800).up().wait(500) // Not allowed - } + const toucherSelfIntersectionFalse = handSelfIntersectionFalse.growFinger( + 'mouse' + ); + toucherSelfIntersectionFalse + .wait(100) + .moveTo(504, 337, 100) + .down() + .wait(500) + .moveTo(780, 259, 400) + .up() + .wait(100) // allowed + // No intersection anymore + .moveTo(294, 114, 100) + .down() + .wait(500) + .moveTo(752, 327, 800) + .up() + .wait(500); // Not allowed + }, }); cy.wait(1000); - map.pm.enableGlobalEditMode({ allowSelfIntersection: false, allowSelfIntersectionEdit: true, }); - - const toucherSelfIntersectionTrue = handSelfIntersectionTrue.growFinger('mouse'); - toucherSelfIntersectionTrue.wait(100).moveTo(294, 114, 100).down().wait(500).moveTo(782, 127, 400).up().wait(100) // Not allowed - .moveTo(313, 345, 100).down().wait(500).moveTo(256, 311, 400).up().wait(100) // allowed - .moveTo(317, 252, 100).down().wait(500).moveTo(782, 127, 400).up().wait(500); // allowed + map.pm.enableGlobalEditMode({ + allowSelfIntersection: false, + allowSelfIntersectionEdit: true, + }); + const toucherSelfIntersectionTrue = handSelfIntersectionTrue.growFinger( + 'mouse' + ); + toucherSelfIntersectionTrue + .wait(100) + .moveTo(294, 114, 100) + .down() + .wait(500) + .moveTo(782, 127, 400) + .up() + .wait(100) // Not allowed + .moveTo(313, 345, 100) + .down() + .wait(500) + .moveTo(256, 311, 400) + .up() + .wait(100) // allowed + .moveTo(317, 252, 100) + .down() + .wait(500) + .moveTo(782, 127, 400) + .up() + .wait(500); // allowed // wait until hand is finished - cy.waitUntil(() => cy.window().then(() => handFinish),{ + cy.waitUntil(() => cy.window().then(() => handFinish), { timeout: 9000, - }).then( ()=> { + }).then(() => { expect(handFinish).to.equal(true); }); - }); }); }); @@ -763,21 +777,15 @@ describe('Draw & Edit Poly', () => { .should('have.class', 'active'); // draw a line - cy.get(mapSelector) - .click(150, 250) - .click(160, 50) - .click(160, 50); + cy.get(mapSelector).click(150, 250).click(160, 50).click(160, 50); - - cy.toolbarButton('edit') - .click(); + cy.toolbarButton('edit').click(); cy.hasVertexMarkers(2); }); - it('don\'t Cut if it has selfIntersection on finish', () => { - cy.toolbarButton('polygon') - .click(); + it("don't Cut if it has selfIntersection on finish", () => { + cy.toolbarButton('polygon').click(); cy.get(mapSelector) .click(90, 250) @@ -787,9 +795,7 @@ describe('Draw & Edit Poly', () => { .click(300, 350) .click(90, 250); - - cy.toolbarButton('cut') - .click(); + cy.toolbarButton('cut').click(); // draw a polygon to cut cy.get(mapSelector) @@ -799,15 +805,14 @@ describe('Draw & Edit Poly', () => { .click(450, 200) .click(200, 100); - cy.toolbarButton('edit') - .click(); + cy.toolbarButton('edit').click(); cy.hasVertexMarkers(5); }); it('enable continueDrawing', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({continueDrawing: true}); + map.pm.setGlobalOptions({ continueDrawing: true }); }); cy.toolbarButton('polygon').click(); @@ -832,7 +837,9 @@ describe('Draw & Edit Poly', () => { it('pane support', () => { cy.window().then(({ map }) => { map.createPane('draw'); - map.pm.setGlobalOptions({panes: {layerPane: 'draw', vertexPane: 'draw'}}) + map.pm.setGlobalOptions({ + panes: { layerPane: 'draw', vertexPane: 'draw' }, + }); }); cy.toolbarButton('polygon').click(); @@ -853,7 +860,7 @@ describe('Draw & Edit Poly', () => { it('disable snapping on segment', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({snapSegment: false}); + map.pm.setGlobalOptions({ snapSegment: false }); }); cy.toolbarButton('polygon').click(); @@ -865,9 +872,7 @@ describe('Draw & Edit Poly', () => { // if snapping is not disabled, the point will be placed at 190|50 cy.toolbarButton('polygon').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 60); cy.window().then(({ map }) => { const lastLatLng = map.pm.Draw.Polygon._layer.getLatLngs()[1]; @@ -878,7 +883,7 @@ describe('Draw & Edit Poly', () => { it('finishOn snap', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({finishOn: 'snap'}); + map.pm.setGlobalOptions({ finishOn: 'snap' }); }); cy.toolbarButton('polygon').click(); @@ -890,10 +895,7 @@ describe('Draw & Edit Poly', () => { // if snapping is not disabled, the point will be placed at 190|50 cy.toolbarButton('polygon').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 90) - .click(250, 50); + cy.get(mapSelector).click(350, 250).click(190, 90).click(250, 50); cy.window().then(({ map }) => { expect(2).to.eq(map.pm.getGeomanDrawLayers().length); @@ -902,7 +904,10 @@ describe('Draw & Edit Poly', () => { it('requireSnapToFinish', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({requireSnapToFinish: true, snapSegment: false}); + map.pm.setGlobalOptions({ + requireSnapToFinish: true, + snapSegment: false, + }); }); cy.toolbarButton('polygon').click(); @@ -913,18 +918,14 @@ describe('Draw & Edit Poly', () => { .click(150, 250); cy.toolbarButton('polygon').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 160) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 160).click(190, 60); cy.window().then(({ map }) => { map.pm.Draw.Polygon._finishShape(); expect(1).to.eq(map.pm.getGeomanDrawLayers().length); }); - cy.get(mapSelector) - .click(250, 50); + cy.get(mapSelector).click(250, 50); cy.window().then(({ map }) => { map.pm.Draw.Polygon._finishShape(); @@ -941,12 +942,11 @@ describe('Draw & Edit Poly', () => { .click(150, 250); cy.window().then(({ map }) => { - map.pm.setGlobalOptions({allowEditing: false}); + map.pm.setGlobalOptions({ allowEditing: false }); }); cy.toolbarButton('edit').click(); - cy.get(mapSelector) - .rightclick(160, 50); + cy.get(mapSelector).rightclick(160, 50); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); @@ -962,12 +962,11 @@ describe('Draw & Edit Poly', () => { .click(150, 250); cy.window().then(({ map }) => { - map.pm.setGlobalOptions({allowRemoval: false}); + map.pm.setGlobalOptions({ allowRemoval: false }); }); cy.toolbarButton('delete').click(); - cy.get(mapSelector) - .click(160, 50); + cy.get(mapSelector).click(160, 50); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); @@ -983,12 +982,11 @@ describe('Draw & Edit Poly', () => { .click(150, 250); cy.window().then(({ map }) => { - map.pm.setGlobalOptions({draggable: false}); + map.pm.setGlobalOptions({ draggable: false }); }); cy.toolbarButton('drag').click(); - cy.get(mapSelector) - .click(160, 50); + cy.get(mapSelector).click(160, 50); cy.window().then(({ map }) => { const layer = map.pm.getGeomanDrawLayers()[0]; @@ -1007,7 +1005,7 @@ describe('Draw & Edit Poly', () => { let layer; cy.window().then(({ map }) => { layer = map.pm.getGeomanDrawLayers()[0]; - map.pm.setGlobalOptions({allowCutting: false}); + map.pm.setGlobalOptions({ allowCutting: false }); }); cy.toolbarButton('cut').click(); @@ -1032,7 +1030,7 @@ describe('Draw & Edit Poly', () => { .click(150, 250); cy.window().then(({ map }) => { - map.pm.setGlobalOptions({allowRotation: false}); + map.pm.setGlobalOptions({ allowRotation: false }); }); cy.toolbarButton('rotate').click(); @@ -1042,20 +1040,16 @@ describe('Draw & Edit Poly', () => { it('cut only certain layers', () => { cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(450, 250) - .click(390, 60); + cy.get(mapSelector).click(450, 250).click(390, 60); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(250, 250) - .click(390, 60); + cy.get(mapSelector).click(250, 250).click(390, 60); let layer; cy.window().then(({ map }) => { const cutlayer = map.pm.getGeomanDrawLayers()[0]; layer = map.pm.getGeomanDrawLayers()[1]; - map.pm.enableDraw('Cut',{layersToCut: [cutlayer]}); + map.pm.enableDraw('Cut', { layersToCut: [cutlayer] }); }); cy.get(mapSelector) @@ -1082,7 +1076,10 @@ describe('Draw & Edit Poly', () => { }); it('addVertexOn contextmenu / removeVertexOn click', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({addVertexOn: 'contextmenu', removeVertexOn: 'click'}); + map.pm.setGlobalOptions({ + addVertexOn: 'contextmenu', + removeVertexOn: 'click', + }); }); cy.toolbarButton('polygon').click(); @@ -1095,29 +1092,27 @@ describe('Draw & Edit Poly', () => { cy.toolbarButton('edit').click(); // Add Vertex - cy.get(mapSelector) - .click(205, 50); + cy.get(mapSelector).click(205, 50); cy.hasVertexMarkers(3); - cy.get(mapSelector) - .rightclick(205, 50); + cy.get(mapSelector).rightclick(205, 50); cy.hasVertexMarkers(4); // Remove Vertex - cy.get(mapSelector) - .rightclick(205, 50); + cy.get(mapSelector).rightclick(205, 50); cy.hasVertexMarkers(4); - cy.get(mapSelector) - .click(205, 50); + cy.get(mapSelector).click(205, 50); cy.hasVertexMarkers(3); - }); it('addVertexValidation / removeVertexValidation', () => { cy.window().then(({ map }) => { - const check = ({layer})=>layer._valid; - map.pm.setGlobalOptions({addVertexValidation: check, removeVertexValidation: check}); + const check = ({ layer }) => layer._valid; + map.pm.setGlobalOptions({ + addVertexValidation: check, + removeVertexValidation: check, + }); }); cy.toolbarButton('polygon').click(); @@ -1130,13 +1125,11 @@ describe('Draw & Edit Poly', () => { cy.toolbarButton('edit').click(); // Add Vertex - cy.get(mapSelector) - .click(205, 50); + cy.get(mapSelector).click(205, 50); cy.hasVertexMarkers(3); // Remove Vertex - cy.get(mapSelector) - .rightclick(150, 250); + cy.get(mapSelector).rightclick(150, 250); cy.hasVertexMarkers(3); cy.window().then(({ map }) => { @@ -1145,15 +1138,11 @@ describe('Draw & Edit Poly', () => { }); // Add Vertex - cy.get(mapSelector) - .click(205, 50); + cy.get(mapSelector).click(205, 50); cy.hasVertexMarkers(4); // Remove Vertex - cy.get(mapSelector) - .rightclick(205, 50); + cy.get(mapSelector).rightclick(205, 50); cy.hasVertexMarkers(3); - }); - }); diff --git a/cypress/integration/rectangle.spec.js b/cypress/integration/rectangle.spec.js index e3299774..7e25bfc2 100644 --- a/cypress/integration/rectangle.spec.js +++ b/cypress/integration/rectangle.spec.js @@ -7,9 +7,7 @@ describe('Draw Rectangle', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.toolbarButton('edit') .click() @@ -26,14 +24,11 @@ describe('Draw Rectangle', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(600, 250) + cy.get(mapSelector).click(600, 250); // manual testing // clicking close to the other rectangle should finish the rectangle @@ -41,20 +36,17 @@ describe('Draw Rectangle', () => { }); it('makes rectangle edge non-draggable during draw', () => { - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(200, 200) + cy.get(mapSelector).click(200, 200); cy.window().then(({ map, L }) => { cy.get(mapSelector) .then(() => { let l; - map.eachLayer(layer => { + map.eachLayer((layer) => { if (layer instanceof L.Marker) { l = layer; - } }); return l; @@ -62,171 +54,152 @@ describe('Draw Rectangle', () => { .as('marker'); }); - cy.get('@marker').then(marker => { + cy.get('@marker').then((marker) => { expect(marker._pmTempLayer).to.equal(true); expect(marker.options.draggable).to.equal(false); }); }); - it('Multiple Cuts', ()=>{ + it('Multiple Cuts', () => { cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(191,216) - .click(608,323); + cy.get(mapSelector).click(191, 216).click(608, 323); cy.toolbarButton('cut').click(); cy.get(mapSelector) - .click(226,389) - .click(230,105) - .click(270,396) - .click(226,389); + .click(226, 389) + .click(230, 105) + .click(270, 396) + .click(226, 389); cy.toolbarButton('cut').click(); cy.get(mapSelector) - .click(293,356) - .click(293,122) - .click(340,367) - .click(293,356); + .click(293, 356) + .click(293, 122) + .click(340, 367) + .click(293, 356); cy.toolbarButton('cut').click(); cy.get(mapSelector) - .click(364,345) - .click(363,138) - .click(414,368) - .click(364,345); + .click(364, 345) + .click(363, 138) + .click(414, 368) + .click(364, 345); cy.toolbarButton('edit').click(); cy.hasVertexMarkers(16); }); - it('goes back to blue after self-intersection removed', ()=>{ + it('goes back to blue after self-intersection removed', () => { cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(100,50) - .click(700,400); + cy.get(mapSelector).click(100, 50).click(700, 400); cy.toolbarButton('cut').click(); cy.get(mapSelector) - .click(200,200) - .click(250,230) - .click(300,250) - .click(370,200) - .click(200,200); + .click(200, 200) + .click(250, 230) + .click(300, 250) + .click(370, 200) + .click(200, 200); cy.toolbarButton('cut').click(); cy.get(mapSelector) - .click(200,300) - .click(250,270) - .click(300,250) - .click(370,300) - .click(200,300); + .click(200, 300) + .click(250, 270) + .click(300, 250) + .click(370, 300) + .click(200, 300); cy.toolbarButton('edit').click(); cy.hasVertexMarkers(12); - cy.get(mapSelector).rightclick(300,250); + cy.get(mapSelector).rightclick(300, 250); cy.window().then(({ map, L }) => { const rect = map.pm.getGeomanDrawLayers()[0]; expect(rect.options.color).to.not.equal('#f00000ff'); - - }) + }); }); - it('remove empty coord rings', ()=>{ + it('remove empty coord rings', () => { cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(100,50) - .click(700,400); + cy.get(mapSelector).click(100, 50).click(700, 400); cy.toolbarButton('cut').click(); cy.get(mapSelector) - .click(200,200) - .click(300,250) - .click(370,200) - .click(200,200); - + .click(200, 200) + .click(300, 250) + .click(370, 200) + .click(200, 200); cy.toolbarButton('edit').click(); cy.hasVertexMarkers(7); - cy.get(mapSelector).rightclick(300,250); + cy.get(mapSelector).rightclick(300, 250); - cy.window().then(({ map}) => { + cy.window().then(({ map }) => { const rect = map.pm.getGeomanDrawLayers()[0]; const geojson = rect.toGeoJSON(); const coords = geojson.geometry.coordinates; expect(coords.length).to.equal(1); - }) + }); }); it('enable continueDrawing', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({continueDrawing: true}); + map.pm.setGlobalOptions({ continueDrawing: true }); }); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(191,216) - .click(608,323); - - cy.get(mapSelector) - .click(230, 230) - .click(350, 350); + cy.get(mapSelector).click(191, 216).click(608, 323); + cy.get(mapSelector).click(230, 230).click(350, 350); cy.toolbarButton('edit').click(); cy.hasVertexMarkers(8); }); - it('disable popup on layer while drawing', ()=>{ + it('disable popup on layer while drawing', () => { let rect = null; cy.window().then(({ map, L }) => { - map.on("pm:create",(e)=>{ + map.on('pm:create', (e) => { e.layer.bindPopup('Popup test'); - if(e.layer instanceof L.Rectangle){ + if (e.layer instanceof L.Rectangle) { rect = e.layer; } }); }); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(100,50) - .click(700,400); + cy.get(mapSelector).click(100, 50).click(700, 400); cy.toolbarButton('marker').click(); - cy.get(mapSelector) - .click(300,250); + cy.get(mapSelector).click(300, 250); cy.toolbarButton('edit').click(); - cy.window().then(({ map}) => { + cy.window().then(({ map }) => { const len = map.pm.getGeomanDrawLayers().length; expect(len).to.equal(2); const text = rect.getPopup().getContent(); expect(text).to.equal('Popup test'); - }) + }); }); it('prevent not correct created snaplist', () => { cy.window().then(({ map }) => { - map.on("pm:create",(e)=>{ + map.on('pm:create', (e) => { map.removeLayer(e.layer); map.addLayer(e.layer); }); }); - cy.toolbarButton('rectangle') .click() .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.window().then(({ map }) => { expect(map.pm.Draw.Rectangle._snapList).to.equal(undefined); @@ -240,16 +213,12 @@ describe('Draw Rectangle', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); // test 1: snapIgnore: undefined, pmIgnore: undefined, optIn: false --> snappable - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); // click or mousemove is needed to init snapList - cy.get(mapSelector) - .click(200, 100); + cy.get(mapSelector).click(200, 100); let layer; cy.window().then(({ map }) => { @@ -262,11 +231,9 @@ describe('Draw Rectangle', () => { cy.window().then(() => { layer.options.snapIgnore = true; }); - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); // click or mousemove is needed to init snapList - cy.get(mapSelector) - .click(200, 100); + cy.get(mapSelector).click(200, 100); cy.window().then(({ map }) => { expect(map.pm.Draw.Rectangle._snapList.length).to.equal(0); @@ -278,11 +245,9 @@ describe('Draw Rectangle', () => { layer.options.snapIgnore = false; layer.options.pmIgnore = true; }); - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); // click or mousemove is needed to init snapList - cy.get(mapSelector) - .click(200, 100); + cy.get(mapSelector).click(200, 100); cy.window().then(({ map }) => { expect(map.pm.Draw.Rectangle._snapList.length).to.equal(1); @@ -294,29 +259,24 @@ describe('Draw Rectangle', () => { delete layer.options.snapIgnore; layer.options.pmIgnore = true; }); - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); // click or mousemove is needed to init snapList - cy.get(mapSelector) - .click(200, 100); + cy.get(mapSelector).click(200, 100); cy.window().then(({ map }) => { expect(map.pm.Draw.Rectangle._snapList.length).to.equal(0); map.pm.disableDraw(); }); - // test 5: snapIgnore: undefined, pmIgnore: false, optIn: true --> snappable - cy.window().then(({L}) => { + cy.window().then(({ L }) => { delete layer.options.snapIgnore; layer.options.pmIgnore = false; - L.PM.setOptIn(true) + L.PM.setOptIn(true); }); - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); // click or mousemove is needed to init snapList - cy.get(mapSelector) - .click(200, 100); + cy.get(mapSelector).click(200, 100); cy.window().then(({ map }) => { expect(map.pm.Draw.Rectangle._snapList.length).to.equal(1); @@ -324,31 +284,26 @@ describe('Draw Rectangle', () => { }); // test 6: snapIgnore: undefined, pmIgnore: true, optIn: true --> not snappable - cy.window().then(({L}) => { + cy.window().then(({ L }) => { layer.options.pmIgnore = true; - L.PM.setOptIn(true) + L.PM.setOptIn(true); }); - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); // click or mousemove is needed to init snapList - cy.get(mapSelector) - .click(200, 100); + cy.get(mapSelector).click(200, 100); cy.window().then(({ map }) => { expect(map.pm.Draw.Rectangle._snapList.length).to.equal(0); map.pm.disableDraw(); }); - // test 7: snapIgnore: false, pmIgnore: true, optIn: true --> snappable cy.window().then(() => { layer.options.snapIgnore = false; }); - cy.toolbarButton('rectangle') - .click(); + cy.toolbarButton('rectangle').click(); // click or mousemove is needed to init snapList - cy.get(mapSelector) - .click(200, 100); + cy.get(mapSelector).click(200, 100); cy.window().then(({ map }) => { expect(map.pm.Draw.Rectangle._snapList.length).to.equal(1); @@ -358,7 +313,10 @@ describe('Draw Rectangle', () => { it('requireSnapToFinish', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({requireSnapToFinish: true, snapSegment: false}); + map.pm.setGlobalOptions({ + requireSnapToFinish: true, + snapSegment: false, + }); }); cy.toolbarButton('polygon').click(); @@ -369,16 +327,13 @@ describe('Draw Rectangle', () => { .click(150, 250); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 60); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); }); - cy.get(mapSelector) - .click(250, 50); + cy.get(mapSelector).click(250, 50); cy.window().then(({ map }) => { expect(2).to.eq(map.pm.getGeomanDrawLayers().length); @@ -387,22 +342,21 @@ describe('Draw Rectangle', () => { it('requireSnapToFinish not applied for first layer', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({requireSnapToFinish: true, snapSegment: false}); + map.pm.setGlobalOptions({ + requireSnapToFinish: true, + snapSegment: false, + }); }); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 60); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); }); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(450, 250) - .click(390, 60); + cy.get(mapSelector).click(450, 250).click(390, 60); cy.window().then(({ map }) => { expect(1).to.eq(map.pm.getGeomanDrawLayers().length); @@ -411,9 +365,7 @@ describe('Draw Rectangle', () => { it('map property is added after creation', () => { cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(350, 250) - .click(190, 60); + cy.get(mapSelector).click(350, 250).click(190, 60); cy.window().then(({ map }) => { const layer = map.pm.getGeomanDrawLayers()[0]; @@ -424,18 +376,14 @@ describe('Draw Rectangle', () => { it('drags a whole LayerGroup', () => { cy.window().then(({ map, L }) => { const fg = L.featureGroup().addTo(map); - map.pm.setGlobalOptions({layerGroup: fg, syncLayersOnDrag: true}); + map.pm.setGlobalOptions({ layerGroup: fg, syncLayersOnDrag: true }); }); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(191,216) - .click(608,323); + cy.get(mapSelector).click(191, 216).click(608, 323); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(230, 230) - .click(350, 350); + cy.get(mapSelector).click(230, 230).click(350, 350); cy.toolbarButton('drag').click(); @@ -445,9 +393,21 @@ describe('Draw Rectangle', () => { const center2 = layers[1].getCenter(); const layer = layers[0]; - layer.pm._dragMixinOnMouseDown({originalEvent: {button: 0}, target: layer, latlng: map.containerPointToLatLng([290,290]) }); - layer.pm._dragMixinOnMouseMove({originalEvent: {button: 0}, target: layer, latlng: map.containerPointToLatLng([500,320]) }); - layer.pm._dragMixinOnMouseUp({originalEvent: {button: 0}, target: layer, latlng: map.containerPointToLatLng([320,320]) }); + layer.pm._dragMixinOnMouseDown({ + originalEvent: { button: 0 }, + target: layer, + latlng: map.containerPointToLatLng([290, 290]), + }); + layer.pm._dragMixinOnMouseMove({ + originalEvent: { button: 0 }, + target: layer, + latlng: map.containerPointToLatLng([500, 320]), + }); + layer.pm._dragMixinOnMouseUp({ + originalEvent: { button: 0 }, + target: layer, + latlng: map.containerPointToLatLng([320, 320]), + }); expect(center1.equals(layers[0].getCenter())).to.eq(false); expect(center2.equals(layers[1].getCenter())).to.eq(false); @@ -456,18 +416,14 @@ describe('Draw Rectangle', () => { it('drags syncLayers', () => { cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(191,216) - .click(608,323); + cy.get(mapSelector).click(191, 216).click(608, 323); cy.toolbarButton('rectangle').click(); - cy.get(mapSelector) - .click(230, 230) - .click(350, 350); + cy.get(mapSelector).click(230, 230).click(350, 350); cy.toolbarButton('drag').click(); - cy.window().then(({ map}) => { + cy.window().then(({ map }) => { const layers = map.pm.getGeomanDrawLayers(); let center1 = layers[0].getCenter(); let center2 = layers[1].getCenter(); @@ -477,39 +433,58 @@ describe('Draw Rectangle', () => { layer.pm.options.syncLayersOnDrag = layers; // Drag both layers - layer.pm._dragMixinOnMouseDown({originalEvent: {button: 0}, target: layer, latlng: map.containerPointToLatLng([290,290]) }); - layer.pm._dragMixinOnMouseMove({originalEvent: {button: 0}, target: layer, latlng: map.containerPointToLatLng([500,320]) }); - layer.pm._dragMixinOnMouseUp({originalEvent: {button: 0}, target: layer, latlng: map.containerPointToLatLng([320,320]) }); + layer.pm._dragMixinOnMouseDown({ + originalEvent: { button: 0 }, + target: layer, + latlng: map.containerPointToLatLng([290, 290]), + }); + layer.pm._dragMixinOnMouseMove({ + originalEvent: { button: 0 }, + target: layer, + latlng: map.containerPointToLatLng([500, 320]), + }); + layer.pm._dragMixinOnMouseUp({ + originalEvent: { button: 0 }, + target: layer, + latlng: map.containerPointToLatLng([320, 320]), + }); expect(center1.equals(layers[0].getCenter())).to.eq(false); expect(center2.equals(layers[1].getCenter())).to.eq(false); - center1 = layers[0].getCenter(); center2 = layers[1].getCenter(); const layer2 = layers[1]; // Drag only layer2 - layer2.pm._dragMixinOnMouseDown({originalEvent: {button: 0}, target: layer2, latlng: map.containerPointToLatLng([290,290]) }); - layer2.pm._dragMixinOnMouseMove({originalEvent: {button: 0}, target: layer2, latlng: map.containerPointToLatLng([500,320]) }); - layer2.pm._dragMixinOnMouseUp({originalEvent: {button: 0}, target: layer2, latlng: map.containerPointToLatLng([320,320]) }); + layer2.pm._dragMixinOnMouseDown({ + originalEvent: { button: 0 }, + target: layer2, + latlng: map.containerPointToLatLng([290, 290]), + }); + layer2.pm._dragMixinOnMouseMove({ + originalEvent: { button: 0 }, + target: layer2, + latlng: map.containerPointToLatLng([500, 320]), + }); + layer2.pm._dragMixinOnMouseUp({ + originalEvent: { button: 0 }, + target: layer2, + latlng: map.containerPointToLatLng([320, 320]), + }); expect(center1.equals(layers[0].getCenter())).to.eq(true); expect(center2.equals(layers[1].getCenter())).to.eq(false); }); }); - it('allows only one of two rectangles to be editable', () => { cy.toolbarButton('rectangle') .click() .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); - + cy.get(mapSelector).click(200, 200).click(400, 350); cy.window().then(({ map }) => { map.pm.getGeomanDrawLayers()[0].pm.options.allowEditing = false; @@ -520,9 +495,7 @@ describe('Draw Rectangle', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(500, 200) - .click(400, 350); + cy.get(mapSelector).click(500, 200).click(400, 350); cy.toolbarButton('edit') .click() @@ -533,17 +506,13 @@ describe('Draw Rectangle', () => { cy.hasMiddleMarkers(0); }); - it('allows only one of two rectangles to be rotateable', () => { cy.toolbarButton('rectangle') .click() .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); - + cy.get(mapSelector).click(200, 200).click(400, 350); cy.window().then(({ map }) => { map.pm.getGeomanDrawLayers()[0].pm.options.allowRotation = false; @@ -554,9 +523,7 @@ describe('Draw Rectangle', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(500, 200) - .click(400, 350); + cy.get(mapSelector).click(500, 200).click(400, 350); cy.toolbarButton('rotate') .click() diff --git a/cypress/integration/rotation.spec.js b/cypress/integration/rotation.spec.js index 05e914c3..6f91648b 100644 --- a/cypress/integration/rotation.spec.js +++ b/cypress/integration/rotation.spec.js @@ -7,9 +7,7 @@ describe('Rotation', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.window().then(({ map }) => { const layer = map.pm.getGeomanDrawLayers()[0]; @@ -35,9 +33,7 @@ describe('Rotation', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.window().then(({ map }) => { const layer = map.pm.getGeomanDrawLayers()[0]; @@ -63,9 +59,7 @@ describe('Rotation', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.window().then(({ map }) => { const layer = map.pm.getGeomanDrawLayers()[0]; @@ -107,9 +101,7 @@ describe('Rotation', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.toolbarButton('rotate') .click() @@ -124,13 +116,15 @@ describe('Rotation', () => { expect(layer.pm.getAngle()).to.equal(30); // Marker is on the correct position - expect(layer.getLatLngs()[0][0].equals(layer.pm._rotatePoly.getLatLngs()[0][0])).to.equal(true); + expect( + layer.getLatLngs()[0][0].equals(layer.pm._rotatePoly.getLatLngs()[0][0]) + ).to.equal(true); }); }); it('draw rotated rectangle', () => { cy.window().then(({ map }) => { - map.pm.setGlobalOptions({rectangleAngle: 40}); + map.pm.setGlobalOptions({ rectangleAngle: 40 }); }); cy.toolbarButton('rectangle') @@ -138,14 +132,16 @@ describe('Rotation', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(600, 350); + cy.get(mapSelector).click(200, 200).click(600, 350); cy.window().then(({ map, L }) => { const layer = map.pm.getGeomanDrawLayers()[0]; expect(layer.pm.getAngle()).to.equal(40); - expect(layer.getLatLngs()[0][1].equals(L.latLng([51.48267237710426, -0.08847595304329439]))).to.equal(true); + expect( + layer + .getLatLngs()[0][1] + .equals(L.latLng([51.48267237710426, -0.08847595304329439])) + ).to.equal(true); }); }); @@ -155,18 +151,16 @@ describe('Rotation', () => { .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(400, 350); + cy.get(mapSelector).click(200, 200).click(400, 350); cy.window().then(({ map }) => { const layer = map.pm.getGeomanDrawLayers()[0]; layer.pm.enableRotate(); const marker1 = layer.pm._rotatePoly.pm._markers[0][0]; - marker1.fire('dragstart',{target: marker1}); - marker1.setLatLng(map.containerPointToLatLng([200,210])); - marker1.fire('drag',{target: marker1}); - marker1.fire('dragend',{target: marker1}); + marker1.fire('dragstart', { target: marker1 }); + marker1.setLatLng(map.containerPointToLatLng([200, 210])); + marker1.fire('drag', { target: marker1 }); + marker1.fire('dragend', { target: marker1 }); expect(Math.ceil(layer.pm.getAngle())).to.eq(70); }); @@ -177,12 +171,9 @@ describe('Rotation', () => { .click() .closest('.button-container') .should('have.class', 'active'); - cy.get(mapSelector) - .click(200, 200) - .click(600, 350); + cy.get(mapSelector).click(200, 200).click(600, 350); - cy.toolbarButton('cut') - .click(); + cy.toolbarButton('cut').click(); cy.get(mapSelector) .click(400, 150) .click(450, 400) @@ -193,10 +184,10 @@ describe('Rotation', () => { const layer = map.pm.getGeomanDrawLayers()[0]; layer.pm.enableRotate(); const marker1 = layer.pm._rotatePoly.pm._markers[0][0][0]; - marker1.fire('dragstart',{target: marker1}); - marker1.setLatLng(map.containerPointToLatLng([200,210])); - marker1.fire('drag',{target: marker1}); - marker1.fire('dragend',{target: marker1}); + marker1.fire('dragstart', { target: marker1 }); + marker1.setLatLng(map.containerPointToLatLng([200, 210])); + marker1.fire('drag', { target: marker1 }); + marker1.fire('dragend', { target: marker1 }); expect(Math.ceil(layer.pm.getAngle())).to.eq(64); }); }); diff --git a/cypress/integration/toolbar.spec.js b/cypress/integration/toolbar.spec.js index cf3bc101..6d4096ad 100644 --- a/cypress/integration/toolbar.spec.js +++ b/cypress/integration/toolbar.spec.js @@ -6,7 +6,7 @@ describe('Testing the Toolbar', () => { .parent('.leaflet-top.leaflet-left') .should('exist'); - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.addControls({ position: 'topright', }); @@ -24,7 +24,7 @@ describe('Testing the Toolbar', () => { cy.get('.button-container.active .action-cancel').click(); - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.addControls({ position: 'bottomright', }); @@ -34,7 +34,7 @@ describe('Testing the Toolbar', () => { .parent('.leaflet-bottom.leaflet-right') .should('exist'); - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.addControls({ position: 'bottomleft', }); @@ -44,7 +44,7 @@ describe('Testing the Toolbar', () => { .parent('.leaflet-bottom.leaflet-left') .should('exist'); - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.addControls({ position: 'topleft', }); @@ -95,7 +95,7 @@ describe('Testing the Toolbar', () => { }); it('Reacts to programmatic state change', () => { - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.enableGlobalEditMode(); }); @@ -103,7 +103,7 @@ describe('Testing the Toolbar', () => { .closest('.button-container') .should('have.class', 'active'); - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.toggleGlobalRemovalMode(); }); @@ -114,7 +114,7 @@ describe('Testing the Toolbar', () => { .closest('.button-container') .should('have.class', 'active'); - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.toggleGlobalRemovalMode(); map.pm.toggleGlobalRemovalMode(); map.pm.toggleGlobalRemovalMode(); @@ -124,7 +124,7 @@ describe('Testing the Toolbar', () => { .closest('.button-container') .should('have.not.class', 'active'); - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.toggleGlobalEditMode(); map.pm.toggleGlobalRemovalMode(); @@ -147,12 +147,13 @@ describe('Testing the Toolbar', () => { }); it('Has Working translation for circle marker toolbar button', () => { - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.setLang('es'); }); cy.get('.leaflet-buttons-control-button .leaflet-pm-icon-circle-marker') - .should('have.attr', 'title').and('include', 'Dibujar Marcador de Circulo'); + .should('have.attr', 'title') + .and('include', 'Dibujar Marcador de Circulo'); }); it('has functioning actions', () => { @@ -188,74 +189,81 @@ describe('Testing the Toolbar', () => { cy.hasVertexMarkers(0); }); - it('Custom Controls - new button', () => { cy.get('.leaflet-pm-toolbar') .parent('.leaflet-top.leaflet-left') .should('exist'); - - cy.window().then(({map, L}) => { - let testresult = ""; + cy.window().then(({ map, L }) => { + let testresult = ''; // Click button -> toggle disabled map.pm.Toolbar.createCustomControl({ - name: "clickButton", - block: "custom", - className: "leaflet-pm-icon-marker", - title: "Count layers", + name: 'clickButton', + block: 'custom', + className: 'leaflet-pm-icon-marker', + title: 'Count layers', onClick: () => { - testresult = "clickButton clicked"; + testresult = 'clickButton clicked'; }, - toggle: false + toggle: false, }); cy.toolbarButtonContainer('clickButton', map).then((container) => { - cy.get(container[0].children[0].children[0]).should('have.attr', 'title').and('include', 'Count layers'); + cy.get(container[0].children[0].children[0]) + .should('have.attr', 'title') + .and('include', 'Count layers'); container[0].children[0].click(); // button - expect(testresult).to.equal("clickButton clicked"); + expect(testresult).to.equal('clickButton clicked'); cy.get(container).should('not.have.class', 'active'); }); }); }); - it('Custom Controls - new draw instance', () => { cy.get('.leaflet-pm-toolbar') .parent('.leaflet-top.leaflet-left') .should('exist'); - - cy.window().then(({map}) => { - let testresult = ""; + cy.window().then(({ map }) => { + let testresult = ''; let testlayer; // Copy of Polygon Button - const actions = ['cancel', {text: 'Custom text, no click'}, { - text: 'Click event', onClick: () => { - testresult = 'click'; - } - }]; - map.pm.Toolbar.copyDrawControl("Polygon", { - name: "PolygonCopy", - block: "custom", - className: "leaflet-pm-icon-polygon", - title: "Display text on hover button", - actions + const actions = [ + 'cancel', + { text: 'Custom text, no click' }, + { + text: 'Click event', + onClick: () => { + testresult = 'click'; + }, + }, + ]; + map.pm.Toolbar.copyDrawControl('Polygon', { + name: 'PolygonCopy', + block: 'custom', + className: 'leaflet-pm-icon-polygon', + title: 'Display text on hover button', + actions, }); - map.pm.Draw.PolygonCopy.setPathOptions({color :'red'}); + map.pm.Draw.PolygonCopy.setPathOptions({ color: 'red' }); cy.toolbarButtonContainer('PolygonCopy', map).then((container) => { - cy.get(container[0].children[0].children[0]).should('have.attr', 'title').and('include', 'Display text on hover button'); + cy.get(container[0].children[0].children[0]) + .should('have.attr', 'title') + .and('include', 'Display text on hover button'); cy.get(container[0].children[0]).click(); // button cy.get(container).should('have.class', 'active'); const actions = container[0].children[1].children; const actioncount = actions.length; expect(actioncount).to.equal(3); - cy.get(actions[2]).click().then(() => { - expect(testresult).to.equal("click"); - expect(actions[1].innerHTML).to.equal("Custom text, no click"); - }); + cy.get(actions[2]) + .click() + .then(() => { + expect(testresult).to.equal('click'); + expect(actions[1].innerHTML).to.equal('Custom text, no click'); + }); cy.get(actions[0]).click(); cy.get(container).should('not.have.class', 'active'); @@ -263,8 +271,8 @@ describe('Testing the Toolbar', () => { map.pm.enableDraw('PolygonCopy'); map.on('pm:create', (e) => { expect(e.shape).to.equal('PolygonCopy'); - e.layer.on('click', (l) => testlayer = l.target) - }) + e.layer.on('click', (l) => (testlayer = l.target)); + }); }); cy.get(container).should('have.class', 'active'); // draw a polygon @@ -276,46 +284,47 @@ describe('Testing the Toolbar', () => { .click(390, 100) .click(450, 100); - - cy.get(mapSelector).click(390, 140).then(() => { - expect(testlayer.options.color).to.equal("red"); - }) - }) + cy.get(mapSelector) + .click(390, 140) + .then(() => { + expect(testlayer.options.color).to.equal('red'); + }); + }); }); }); - it('Custom Controls - Custom order', () => { - cy.window().then(({map}) => { - map.pm.Toolbar.changeControlOrder(["Rectangle"]); + cy.window().then(({ map }) => { + map.pm.Toolbar.changeControlOrder(['Rectangle']); cy.get('.leaflet-pm-toolbar.leaflet-pm-draw').then((container) => { cy.get(container[0].children[0]).then((e) => { - cy.get(e[0].children[0].children[0]).should('have.class', 'leaflet-pm-icon-rectangle'); - }) - }) - + cy.get(e[0].children[0].children[0]).should( + 'have.class', + 'leaflet-pm-icon-rectangle' + ); + }); + }); }); }); - it('Custom Controls - One Block', () => { - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.addControls({ - oneBlock: true + oneBlock: true, }); cy.get('.leaflet-pm-toolbar.leaflet-pm-topleft').then((container) => { expect(container[0].children.length).to.equal(11); - }) + }); }); }); it('Different block positions', () => { - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.addControls({ positions: { draw: 'topright', - edit: 'topleft' - } + edit: 'topleft', + }, }); cy.get('.leaflet-pm-toolbar.leaflet-pm-edit') .parent('.leaflet-top.leaflet-left') @@ -327,21 +336,21 @@ describe('Testing the Toolbar', () => { }); it('Different block positions - One Block', () => { - cy.window().then(({map}) => { + cy.window().then(({ map }) => { map.pm.addControls({ oneBlock: true, positions: { draw: 'topright', edit: 'topleft', custom: 'topleft', - } + }, }); - map.pm.Toolbar.copyDrawControl("Polygon", { - name: "PolygonCopy", - block: "custom", - className: "leaflet-pm-icon-polygon", - title: "Display text on hover button", + map.pm.Toolbar.copyDrawControl('Polygon', { + name: 'PolygonCopy', + block: 'custom', + className: 'leaflet-pm-icon-polygon', + title: 'Display text on hover button', }); cy.get('.leaflet-pm-toolbar.leaflet-pm-topright').then((container) => { expect(container[0].children.length).to.equal(6); @@ -352,10 +361,14 @@ describe('Testing the Toolbar', () => { }); }); it('Listen on pm:buttonclick and pm:actionclick', () => { - let eventFired = ""; - cy.window().then(({map}) => { - map.on('pm:buttonclick', ({btnName})=>{eventFired = btnName}); - map.on('pm:actionclick', ({text})=>{eventFired = text}); + let eventFired = ''; + cy.window().then(({ map }) => { + map.on('pm:buttonclick', ({ btnName }) => { + eventFired = btnName; + }); + map.on('pm:actionclick', ({ text }) => { + eventFired = text; + }); }); cy.toolbarButton('polygon').click(); @@ -371,10 +384,12 @@ describe('Testing the Toolbar', () => { }); }); it('Disable button', () => { - let eventFired = ""; - cy.window().then(({map}) => { - map.on('pm:buttonclick', ({btnName})=>{eventFired = btnName}); - map.pm.Toolbar.setButtonDisabled('drawPolygon',true); + let eventFired = ''; + cy.window().then(({ map }) => { + map.on('pm:buttonclick', ({ btnName }) => { + eventFired = btnName; + }); + map.pm.Toolbar.setButtonDisabled('drawPolygon', true); }); cy.toolbarButton('polygon').click(); diff --git a/cypress/integration/tooltips.spec.js b/cypress/integration/tooltips.spec.js index 9e891bdf..489ddaa6 100644 --- a/cypress/integration/tooltips.spec.js +++ b/cypress/integration/tooltips.spec.js @@ -9,7 +9,7 @@ describe('Shows Tooltips', () => { }); cy.toolbarButton('polygon').click(); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Platziere den ersten Marker mit Klick'); }); }); @@ -25,7 +25,7 @@ describe('Shows Tooltips', () => { }); cy.toolbarButton('marker').click(); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Custom Marker Translation'); }); }); @@ -36,13 +36,13 @@ describe('Shows Tooltips', () => { cy.get('.leaflet-tooltip-bottom').should('exist'); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to place marker'); }); cy.get(mapSelector).click(290, 250); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to place marker'); }); @@ -57,13 +57,13 @@ describe('Shows Tooltips', () => { cy.get('.leaflet-tooltip-bottom').should('exist'); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to place first vertex'); }); cy.get(mapSelector).click(290, 250); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to finish'); }); @@ -78,13 +78,13 @@ describe('Shows Tooltips', () => { cy.get('.leaflet-tooltip-bottom').should('exist'); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to place circle center'); }); cy.get(mapSelector).click(290, 250); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to finish circle'); }); @@ -101,20 +101,20 @@ describe('Shows Tooltips', () => { cy.get('.leaflet-tooltip-bottom').should('exist'); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to place first vertex'); }); // draw a polygon cy.get(mapSelector).click(290, 250); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to continue drawing'); }); cy.get(mapSelector).click(300, 50); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click any existing marker to finish'); }); @@ -131,7 +131,7 @@ describe('Shows Tooltips', () => { cy.get('.leaflet-tooltip-bottom').should('exist'); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to place first vertex'); }); @@ -143,7 +143,7 @@ describe('Shows Tooltips', () => { .click(350, 150) .click(400, 150); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click first marker to finish'); }); @@ -198,13 +198,13 @@ describe('Shows Tooltips', () => { cy.get('.leaflet-tooltip-bottom').should('exist'); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Presiona para colocar un marcador de circulo'); }); cy.get(mapSelector).click(290, 250); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Presiona para colocar un marcador de circulo'); }); @@ -216,12 +216,9 @@ describe('Shows Tooltips', () => { it('Reset tooltip after remove vertex', () => { cy.toolbarButton('polygon').click(); - cy.get(mapSelector) - .click(90, 250) - .click(100, 350) - .click(200, 350); + cy.get(mapSelector).click(90, 250).click(100, 350).click(200, 350); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click first marker to finish'); }); @@ -229,14 +226,13 @@ describe('Shows Tooltips', () => { map.pm.Draw.Polygon._removeLastVertex(); }); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click to continue drawing'); }); - cy.get(mapSelector) - .click(200, 350); + cy.get(mapSelector).click(200, 350); - cy.get('.leaflet-tooltip-bottom').then(el => { + cy.get('.leaflet-tooltip-bottom').then((el) => { expect(el).to.have.text('Click first marker to finish'); }); }); diff --git a/cypress/support/commands.js b/cypress/support/commands.js index 4e0f2717..d4fe5dbe 100644 --- a/cypress/support/commands.js +++ b/cypress/support/commands.js @@ -25,16 +25,18 @@ import 'cypress-wait-until'; // -- This is will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) -Cypress.Commands.add('hasLayers', count => { +Cypress.Commands.add('hasLayers', (count) => { cy.window().then(({ map }) => { const layerCount = Object.keys(map._layers).length; cy.wrap(layerCount).should('eq', count); }); }); -Cypress.Commands.add('hasDrawnLayers', count => { +Cypress.Commands.add('hasDrawnLayers', (count) => { cy.window().then(({ map }) => { - const layerCount = Object.keys(map._layers).filter(l => map._layers[l]._drawnByGeoman).length; + const layerCount = Object.keys(map._layers).filter( + (l) => map._layers[l]._drawnByGeoman + ).length; cy.wrap(layerCount).should('eq', count); }); }); @@ -46,15 +48,16 @@ Cypress.Commands.add('testLayerAdditionPerformance', () => { t0 = performance.now(); function getRandomLatLng() { - const bounds = map.getBounds() - const southWest = bounds.getSouthWest() - const northEast = bounds.getNorthEast() - const lngSpan = northEast.lng - southWest.lng + const bounds = map.getBounds(); + const southWest = bounds.getSouthWest(); + const northEast = bounds.getNorthEast(); + const lngSpan = northEast.lng - southWest.lng; const latSpan = northEast.lat - southWest.lat; return new L.LatLng( southWest.lat + latSpan * Math.random(), - southWest.lng + lngSpan * Math.random()); + southWest.lng + lngSpan * Math.random() + ); } const terminals = []; @@ -62,24 +65,23 @@ Cypress.Commands.add('testLayerAdditionPerformance', () => { for (let i = 0; i < 3500; i += 1) { locations.push(L.circleMarker(getRandomLatLng(map))); - } for (let i = 0; i < 2500; i += 1) { terminals.push(L.circleMarker(getRandomLatLng(map))); } - const t = L.layerGroup(terminals).addTo(map) - const l = L.layerGroup(locations).addTo(map) + const t = L.layerGroup(terminals).addTo(map); + const l = L.layerGroup(locations).addTo(map); - const base = {} + const base = {}; const overlays = { - "Locations": t, - "Terminals": l - } + Locations: t, + Terminals: l, + }; - L.control.layers(base, overlays).addTo(map) + L.control.layers(base, overlays).addTo(map); }); cy.window().then(() => { @@ -91,30 +93,30 @@ Cypress.Commands.add('testLayerAdditionPerformance', () => { }); }); -Cypress.Commands.add('hasMiddleMarkers', count => { - cy.get('.marker-icon-middle').should($p => { +Cypress.Commands.add('hasMiddleMarkers', (count) => { + cy.get('.marker-icon-middle').should(($p) => { expect($p).to.have.length(count); }); }); -Cypress.Commands.add('hasVertexMarkers', count => { - cy.get('.marker-icon:not(.marker-icon-middle)').should($p => { +Cypress.Commands.add('hasVertexMarkers', (count) => { + cy.get('.marker-icon:not(.marker-icon-middle)').should(($p) => { expect($p).to.have.length(count); }); }); -Cypress.Commands.add('hasTotalVertexMarkers', count => { - cy.get('.marker-icon').should($p => { +Cypress.Commands.add('hasTotalVertexMarkers', (count) => { + cy.get('.marker-icon').should(($p) => { expect($p).to.have.length(count); }); }); -Cypress.Commands.add('toolbarButton', name => +Cypress.Commands.add('toolbarButton', (name) => cy.get(`.leaflet-pm-icon-${name}`) ); Cypress.Commands.add('toolbarButtonContainer', (name, map) => { - cy.get(map.pm.Toolbar.buttons[name]._container.children[0]) + cy.get(map.pm.Toolbar.buttons[name]._container.children[0]); }); Cypress.Commands.add('drawShape', (shape, ignore) => { @@ -122,7 +124,7 @@ Cypress.Commands.add('drawShape', (shape, ignore) => { if (shape === 'PolygonPart1') { cy.fixture(shape) .as('poly') - .then(json => { + .then((json) => { const layer = L.geoJson(json, { pmIgnore: ignore }).addTo(map); const bounds = layer.getBounds(); map.fitBounds(bounds); @@ -131,7 +133,7 @@ Cypress.Commands.add('drawShape', (shape, ignore) => { if (shape === 'PolygonPart2') { cy.fixture(shape) .as('poly') - .then(json => { + .then((json) => { const layer = L.geoJson(json, { pmIgnore: ignore }).addTo(map); const bounds = layer.getBounds(); map.fitBounds(bounds); @@ -140,7 +142,7 @@ Cypress.Commands.add('drawShape', (shape, ignore) => { if (shape === 'MultiPolygon') { cy.fixture(shape) .as('poly') - .then(json => { + .then((json) => { const layer = L.geoJson(json, { pmIgnore: ignore }).addTo(map); const bounds = layer.getBounds(); map.fitBounds(bounds); @@ -151,18 +153,17 @@ Cypress.Commands.add('drawShape', (shape, ignore) => { if (shape === 'LineString') { cy.fixture(shape) .as('poly') - .then(json => { + .then((json) => { const layer = L.geoJson(json, { pmIgnore: ignore }).addTo(map); const bounds = layer.getBounds(); map.fitBounds(bounds); }); } - if (shape === 'MultiLineString') { cy.fixture(shape) .as('poly') - .then(json => { + .then((json) => { const layer = L.geoJson(json, { pmIgnore: ignore }).addTo(map); const bounds = layer.getBounds(); map.fitBounds(bounds); @@ -172,18 +173,19 @@ Cypress.Commands.add('drawShape', (shape, ignore) => { if (shape === 'MonsterPolygon') { cy.fixture(shape) .as('poly') - .then(json => { - const layer = L.polygon(json.data.points, { pmIgnore: ignore }).addTo(map); + .then((json) => { + const layer = L.polygon(json.data.points, { pmIgnore: ignore }).addTo( + map + ); const bounds = layer.getBounds(); map.fitBounds(bounds); }); } - if (shape === 'PolygonIntersects') { cy.fixture(shape) .as('poly') - .then(json => { + .then((json) => { // const layer = L.geoJSON(json).addTo(map); const bounds = layer.getBounds(); @@ -193,7 +195,7 @@ Cypress.Commands.add('drawShape', (shape, ignore) => { if (shape === 'FeatureCollectionEventFire') { cy.fixture(shape) - .then(json => { + .then((json) => { // const layer = L.geoJSON(json).addTo(map); const bounds = layer.getBounds(); @@ -206,7 +208,7 @@ Cypress.Commands.add('drawShape', (shape, ignore) => { if (shape === 'FeatureCollectionWithCircles') { cy.fixture(shape, ignore) - .then(json => { + .then((json) => { const layer = L.geoJson(json, { pmIgnore: ignore, pointToLayer: (feature, latlng) => { @@ -232,6 +234,3 @@ Cypress.Commands.add('drawShape', (shape, ignore) => { } }); }); - - - diff --git a/cypress/support/index.js b/cypress/support/index.js index 56d511ab..ab855c4c 100644 --- a/cypress/support/index.js +++ b/cypress/support/index.js @@ -20,62 +20,69 @@ import './commands'; // require('./commands') beforeEach(() => { - // create the map - cy.visit('/index.html', { - onLoad: (contentWindow) => { - const { L } = contentWindow; + // create the map + cy.visit('/index.html', { + onLoad: (contentWindow) => { + const { L } = contentWindow; - const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - attribution: '© OpenStreetMap contributors' - }); + const tiles = L.tileLayer( + 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', + { + attribution: + '© OpenStreetMap contributors', + } + ); - // create the map - const map = L.map('map', { - preferCanvas: false - }) - .setView([51.505, -0.09], 13) - .addLayer(tiles); + // create the map + const map = L.map('map', { + preferCanvas: false, + }) + .setView([51.505, -0.09], 13) + .addLayer(tiles); - contentWindow.map = map; + contentWindow.map = map; - // add leaflet-geoman toolbar - map.pm.addControls(); - } - }); + // add leaflet-geoman toolbar + map.pm.addControls(); + }, + }); + // because of this issue: https://github.com/Leaflet/prosthetic-hand/issues/16 + // this._onStop not detected by default as instance of Function. -> Replaced with typeof this._onStop === "function" + cy.window().then(({ Hand }) => { + Hand.prototype.fingerIsIdle = function () { + if (this._fingers.every((f) => f.isIdle())) { + if (!this._fingersAreIdle) { + // 🖑event prostheticHandStop: CustomEvent + // Fired when all movements are complete. + document.dispatchEvent( + new CustomEvent('prostheticHandStop', { target: this }) + ); + if (this._onStop && typeof this._onStop === 'function') { + this._onStop(this); + } + } + this._fingersAreIdle = true; + } + }; - // because of this issue: https://github.com/Leaflet/prosthetic-hand/issues/16 - // this._onStop not detected by default as instance of Function. -> Replaced with typeof this._onStop === "function" - cy.window().then(({ Hand }) => { - Hand.prototype.fingerIsIdle = function () { - if (this._fingers.every(f => f.isIdle())) { - if (!this._fingersAreIdle) { - // 🖑event prostheticHandStop: CustomEvent - // Fired when all movements are complete. - document.dispatchEvent(new CustomEvent('prostheticHandStop', {target: this})); - if (this._onStop && typeof this._onStop === "function") { - this._onStop(this); - } - } - this._fingersAreIdle = true; - } - }; - - Hand.prototype.fingerIsBusy = function() { - if (this._fingersAreIdle) { - // 🖑section - // Use `document.addEventListener('prostheticHandStop', fn)` to - // do stuff with it. - // 🖑event prostheticHandStart: CustomEvent - // Fired when all movements are complete. - document.dispatchEvent(new CustomEvent('prostheticHandStart', { target: this })); - if (this._onStart && typeof this._onStart === "function") { - this._onStart(this); - } - this._fingersAreIdle = false; - this._scheduleNextDispatch(); - } - return this; - } - }); + Hand.prototype.fingerIsBusy = function () { + if (this._fingersAreIdle) { + // 🖑section + // Use `document.addEventListener('prostheticHandStop', fn)` to + // do stuff with it. + // 🖑event prostheticHandStart: CustomEvent + // Fired when all movements are complete. + document.dispatchEvent( + new CustomEvent('prostheticHandStart', { target: this }) + ); + if (this._onStart && typeof this._onStart === 'function') { + this._onStart(this); + } + this._fingersAreIdle = false; + this._scheduleNextDispatch(); + } + return this; + }; + }); }); diff --git a/demo/customcontrols.html b/demo/customcontrols.html index 4bd8d0c8..e3aad608 100644 --- a/demo/customcontrols.html +++ b/demo/customcontrols.html @@ -1,35 +1,36 @@ - + - - - + + Leaflet Geoman Demo - - + + - - - + +
- -
-

Leaflet Geoman

-

An Open Source Leaflet Plugin for editing polygons, specifically made for Leaflet 1.0

-
-
-

Custom Controls in the Toolbar

-
- -
+
+

Leaflet Geoman

+

+ An Open Source Leaflet Plugin for editing polygons, specifically made + for Leaflet 1.0 +

+
+
+

Custom Controls in the Toolbar

+
+
- - + diff --git a/demo/customcontrols.js b/demo/customcontrols.js index e50ef5e1..237ca14b 100644 --- a/demo/customcontrols.js +++ b/demo/customcontrols.js @@ -1,34 +1,57 @@ -var map = L.map('map').setView([40.0269319,32.83604819], 13); +var map = L.map('map').setView([40.0269319, 32.83604819], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: '© OpenStreetMap contributors' + maxZoom: 19, + attribution: + '© OpenStreetMap contributors', }).addTo(map); map.pm.addControls({ - position: 'topleft', - drawControls: false, - editControls: true, - optionsControls: true, - customControls: true, - oneBlock: false + position: 'topleft', + drawControls: false, + editControls: true, + optionsControls: true, + customControls: true, + oneBlock: false, }); // Click button -> toggle disabled -map.pm.Toolbar.createCustomControl({name:"alertBox",block: "custom",className: "leaflet-pm-icon-marker xyz-class",title: "Count layers",onClick: ()=>{alert("There are "+L.PM.Utils.findLayers(map).length+" layers on the map")},toggle: false}); - +map.pm.Toolbar.createCustomControl({ + name: 'alertBox', + block: 'custom', + className: 'leaflet-pm-icon-marker xyz-class', + title: 'Count layers', + onClick: () => { + alert( + 'There are ' + L.PM.Utils.findLayers(map).length + ' layers on the map' + ); + }, + toggle: false, +}); // Copy Geoman Draw Control -const _actions = [{text: "Custom message, with click event",onClick(e){alert('click');}, name: 'actionName'}]; -map.pm.Toolbar.copyDrawControl("Rectangle", {name:"RectangleCopy",block: "custom",title: "Display text on hover button",actions: _actions}); -map.pm.Draw.RectangleCopy.setPathOptions({color :'green'}); - -map.pm.Toolbar.changeControlOrder(["RectangleCopy"]) +const _actions = [ + { + text: 'Custom message, with click event', + onClick(e) { + alert('click'); + }, + name: 'actionName', + }, +]; +map.pm.Toolbar.copyDrawControl('Rectangle', { + name: 'RectangleCopy', + block: 'custom', + title: 'Display text on hover button', + actions: _actions, +}); +map.pm.Draw.RectangleCopy.setPathOptions({ color: 'green' }); +map.pm.Toolbar.changeControlOrder(['RectangleCopy']); -map.on('pm:actionclick',function (e) { - console.log(e) -}) -map.on('pm:buttonclick',function (e) { - console.log(e) -}) +map.on('pm:actionclick', function (e) { + console.log(e); +}); +map.on('pm:buttonclick', function (e) { + console.log(e); +}); diff --git a/demo/demo-canvas.js b/demo/demo-canvas.js index c070a240..d5ac1fca 100644 --- a/demo/demo-canvas.js +++ b/demo/demo-canvas.js @@ -1,17 +1,29 @@ -const tiles1 = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: '© OpenStreetMap contributors' -}); - -const tiles2 = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: '© OpenStreetMap contributors' -}); - -const tiles3 = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: '© OpenStreetMap contributors' -}); +const tiles1 = L.tileLayer( + 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', + { + maxZoom: 19, + attribution: + '© OpenStreetMap contributors', + } +); + +const tiles2 = L.tileLayer( + 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', + { + maxZoom: 19, + attribution: + '© OpenStreetMap contributors', + } +); + +const tiles3 = L.tileLayer( + 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', + { + maxZoom: 19, + attribution: + '© OpenStreetMap contributors', + } +); const map2 = L.map('example2', { preferCanvas: true }) .setView([51.505, -0.09], 13) @@ -93,7 +105,7 @@ map2.pm.disableDraw('Polygon'); map2.pm.enableDraw('Line', { allowSelfIntersection: false }); map2.pm.enableDraw('Polygon', { allowSelfIntersection: false }); -map2.on('pm:globaleditmodetoggled', function(e) { +map2.on('pm:globaleditmodetoggled', function (e) { // console.log(e); }); @@ -166,8 +178,18 @@ map3.pm.enableDraw('Polygon', { }); var scotland = L.polygon([ - [[60, -13], [60, 0], [50, 4], [50, -13]], - [[55.7, -4.5], [56, -4.5], [56, -4], [55.7, -4]], + [ + [60, -13], + [60, 0], + [50, 4], + [50, -13], + ], + [ + [55.7, -4.5], + [56, -4.5], + [56, -4], + [55.7, -4], + ], ]); scotland.addTo(map3); @@ -175,35 +197,35 @@ const bounds = scotland.getBounds(); map3.fitBounds(bounds); -geoJsonLayer.addEventListener('click', function(e) { +geoJsonLayer.addEventListener('click', function (e) { geoJsonLayer.pm.toggleEdit(); }); -geoJsonLayer.on('pm:edit', function(e) { +geoJsonLayer.on('pm:edit', function (e) { console.log(e); }); -geoJsonLayer.on('pm:dragstart', function(e) { +geoJsonLayer.on('pm:dragstart', function (e) { console.log(e); }); // geoJsonLayer.on('pm:drag', function(e) { // console.log(e); // }); -geoJsonLayer.on('pm:dragend', function(e) { +geoJsonLayer.on('pm:dragend', function (e) { console.log(e); }); -map2.on('pm:drawstart', function(e) { +map2.on('pm:drawstart', function (e) { var layer = e.workingLayer; // console.log(layer); - layer.on('pm:centerplaced', function(e) { + layer.on('pm:centerplaced', function (e) { // console.log(e); }); }); -map2.on('pm:create', function(e) { +map2.on('pm:create', function (e) { var layer = e.layer; // console.log(layer); - layer.on('pm:centerplaced', function(e) { + layer.on('pm:centerplaced', function (e) { // console.log(e); }); }); @@ -221,11 +243,11 @@ polygonLayer.pm.toggleEdit({ allowSelfIntersection: false, }); -polygonLayer.on('pm:update', function(e) { +polygonLayer.on('pm:update', function (e) { console.log(e); }); -polygonLayer.on('pm:intersect', function(e) { +polygonLayer.on('pm:intersect', function (e) { console.log(e); }); @@ -234,40 +256,40 @@ map2.pm.toggleGlobalEditMode({ }); map2.pm.disableGlobalEditMode(); -map2.on('pm:create', function(e) { +map2.on('pm:create', function (e) { e.layer.pm.enable({ allowSelfIntersection: false }); // e.layer.pm.disable(); // console.log(e.layer.pm.hasSelfIntersection()); - e.layer.on('pm:markerdragend', function(e) { + e.layer.on('pm:markerdragend', function (e) { // console.log(e); }); - e.layer.on('pm:update', function(e) { + e.layer.on('pm:update', function (e) { console.log(e); }); - e.layer.on('pm:cut', function(e) { + e.layer.on('pm:cut', function (e) { console.log(e); }); }); -map2.on('pm:drawstart', function(e) { +map2.on('pm:drawstart', function (e) { var layer = e.workingLayer; - layer.on('pm:vertexadded', function(e) { + layer.on('pm:vertexadded', function (e) { // console.log(e); // console.log(e.workingLayer.pm.hasSelfIntersection()); }); }); -polygonLayer.on('pm:vertexadded', function(e) { +polygonLayer.on('pm:vertexadded', function (e) { // console.log(e); }); -polygonLayer.on('pm:vertexremoved', function(e) { +polygonLayer.on('pm:vertexremoved', function (e) { // console.log(e); }); -polygonLayer.on('pm:markerdragstart', function(e) { +polygonLayer.on('pm:markerdragstart', function (e) { // console.log(e); }); @@ -320,11 +342,11 @@ layerGroup.addLayer(someLayer); someLayer.addData(feature); console.log(layerGroup); -layerGroup.on('pm:snap', function(e) { +layerGroup.on('pm:snap', function (e) { console.log('snap'); console.log(e); }); -layerGroup.on('pm:unsnap', function(e) { +layerGroup.on('pm:unsnap', function (e) { console.log('unsnap'); console.log(e); }); @@ -354,19 +376,19 @@ layerGroup.addLayer(layerGroupItem3); // layerGroup.addLayer(layerGroupItem4); // layerGroup.addLayer(layerGroupItem5); -layerGroup.on('pm:dragstart', function(e) { +layerGroup.on('pm:dragstart', function (e) { console.log(e); }); -layerGroup.on('pm:drag', function(e) { +layerGroup.on('pm:drag', function (e) { console.log(e); }); -layerGroup.on('pm:dragend', function(e) { +layerGroup.on('pm:dragend', function (e) { console.log(e); }); -layerGroup.on('pm:markerdragstart', function(e) { +layerGroup.on('pm:markerdragstart', function (e) { console.log(e); }); -layerGroup.on('pm:markerdragend', function(e) { +layerGroup.on('pm:markerdragend', function (e) { console.log(e); }); diff --git a/demo/demo.css b/demo/demo.css index 80a9dfd3..4f690cec 100644 --- a/demo/demo.css +++ b/demo/demo.css @@ -1,43 +1,48 @@ -html, body { - font-family: Arial, Verdana; - background-color: #EEF1EF; - font-size: 16px; +html, +body { + font-family: Arial, Verdana; + background-color: #eef1ef; + font-size: 16px; } -html, body { - width: 100%; - height: 100%; - margin: 0; +html, +body { + width: 100%; + height: 100%; + margin: 0; } -h1, h2, h3, h4, h5 { - font-weight: normal; +h1, +h2, +h3, +h4, +h5 { + font-weight: normal; } h1 { - margin-top: 2em; - font-size: 2em; - border-bottom: 1px solid #ccc; + margin-top: 2em; + font-size: 2em; + border-bottom: 1px solid #ccc; } h2 { - margin-top: 1.5em; - font-size: 1.8em; - border-bottom: 1px solid #ccc; + margin-top: 1.5em; + font-size: 1.8em; + border-bottom: 1px solid #ccc; } h3 { - font-size: 1.5em; + font-size: 1.5em; } .wrapper { - box-sizing: border-box; - width: 100%; - padding: 30px; - max-width: 1000px; - margin: auto; + box-sizing: border-box; + width: 100%; + padding: 30px; + max-width: 1000px; + margin: auto; } .map { - height: 500px; + height: 500px; } - diff --git a/demo/demo.js b/demo/demo.js index d1c211c6..9ee91fd9 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -1,27 +1,33 @@ -const tiles1 = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: '© OpenStreetMap contributors' -}); +const tiles1 = L.tileLayer( + 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', + { + maxZoom: 19, + attribution: + '© OpenStreetMap contributors', + } +); -const tiles2 = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: '© OpenStreetMap contributors' -}); +const tiles2 = L.tileLayer( + 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', + { + maxZoom: 19, + attribution: + '© OpenStreetMap contributors', + } +); -const tiles3 = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: '© OpenStreetMap contributors' -}); +const tiles3 = L.tileLayer( + 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', + { + maxZoom: 19, + attribution: + '© OpenStreetMap contributors', + } +); -const map2 = L.map('example2') - .setView([51.505, -0.09], 13) - .addLayer(tiles1); -const map3 = L.map('example3') - .setView([51.505, -0.09], 13) - .addLayer(tiles2); -const map4 = L.map('example4') - .setView([51.505, -0.09], 13) - .addLayer(tiles3); +const map2 = L.map('example2').setView([51.505, -0.09], 13).addLayer(tiles1); +const map3 = L.map('example3').setView([51.505, -0.09], 13).addLayer(tiles2); +const map4 = L.map('example4').setView([51.505, -0.09], 13).addLayer(tiles3); // map2.dragging.disable(); // map2.on('pm:create', function(e) { @@ -93,7 +99,7 @@ map2.pm.addControls({ // map2.pm.enableDraw('Line', { allowSelfIntersection: false }); // map2.pm.enableDraw('Polygon', { allowSelfIntersection: false }); -map2.on('pm:globaleditmodetoggled', function(e) { +map2.on('pm:globaleditmodetoggled', function (e) { // console.log(e); }); @@ -205,11 +211,11 @@ map2.fitBounds(b); console.log(theCollection); -theCollection.on('pm:edit', function(e) { +theCollection.on('pm:edit', function (e) { console.log(e); }); -theCollection.on('pm:dragstart', function(e) { +theCollection.on('pm:dragstart', function (e) { console.log(e); }); @@ -257,8 +263,18 @@ map3.pm.enableDraw('Polygon', { }); var scotland = L.polygon([ - [[60, -13], [60, 0], [50, 4], [50, -13]], - [[55.7, -4.5], [56, -4.5], [56, -4], [55.7, -4]], + [ + [60, -13], + [60, 0], + [50, 4], + [50, -13], + ], + [ + [55.7, -4.5], + [56, -4.5], + [56, -4], + [55.7, -4], + ], ]); scotland.addTo(map3); @@ -274,17 +290,17 @@ map3.fitBounds(bounds); // console.log(e); // }); -map2.on('pm:drawstart', function(e) { +map2.on('pm:drawstart', function (e) { var layer = e.workingLayer; // console.log(layer); - layer.on('pm:centerplaced', function(e) { + layer.on('pm:centerplaced', function (e) { // console.log(e); }); }); -map2.on('pm:create', function(e) { +map2.on('pm:create', function (e) { var layer = e.layer; // console.log(layer); - layer.on('pm:centerplaced', function(e) { + layer.on('pm:centerplaced', function (e) { // console.log(e); }); }); @@ -305,11 +321,11 @@ const polygonLayer = L.polygon([ // preventMarkerRemoval: false, // }); -polygonLayer.on('pm:update', function(e) { +polygonLayer.on('pm:update', function (e) { console.log(e); }); -polygonLayer.on('pm:intersect', function(e) { +polygonLayer.on('pm:intersect', function (e) { console.log(e); }); @@ -325,47 +341,51 @@ map2.pm.disableDraw('Polygon'); map2.pm.enableDraw('Line', { allowSelfIntersection: false }); map2.pm.disableDraw('Line'); -map2.on('pm:create', function(e) { +map2.on('pm:create', function (e) { // e.layer.pm.enable({ allowSelfIntersection: false }); // e.layer.pm.disable(); // console.log(e.layer.pm.hasSelfIntersection()); - e.layer.on('pm:markerdragend', function(e) { + e.layer.on('pm:markerdragend', function (e) { // console.log(e); }); - e.layer.on('pm:update', function(e) { + e.layer.on('pm:update', function (e) { console.log(e); }); - e.layer.on('pm:cut', function(e) { + e.layer.on('pm:cut', function (e) { console.log(e); }); }); -map2.on('pm:drawstart', function(e) { +map2.on('pm:drawstart', function (e) { var layer = e.workingLayer; - layer.on('pm:vertexadded', function(e) { + layer.on('pm:vertexadded', function (e) { // console.log(e); // console.log(e.workingLayer.pm.hasSelfIntersection()); }); }); -polygonLayer.on('pm:vertexadded', function(e) { +polygonLayer.on('pm:vertexadded', function (e) { // console.log(e); }); -polygonLayer.on('pm:vertexremoved', function(e) { +polygonLayer.on('pm:vertexremoved', function (e) { // console.log(e); }); -polygonLayer.on('pm:markerdragstart', function(e) { +polygonLayer.on('pm:markerdragstart', function (e) { // console.log(e); }); // Layer Group Example const layerGroupItem1 = L.polyline( - [[51.51, -0.09], [51.513, -0.08], [51.514, -0.11]], + [ + [51.51, -0.09], + [51.513, -0.08], + [51.514, -0.11], + ], { pmIgnore: true } ); const layerGroupItem2 = L.polygon([ @@ -409,11 +429,11 @@ layerGroup.addLayer(someLayer); someLayer.addData(feature); -layerGroup.on('pm:snap', function(e) { +layerGroup.on('pm:snap', function (e) { console.log('snap'); console.log(e); }); -layerGroup.on('pm:unsnap', function(e) { +layerGroup.on('pm:unsnap', function (e) { console.log('unsnap'); console.log(e); }); @@ -443,19 +463,19 @@ layerGroup.addLayer(layerGroupItem3); // layerGroup.addLayer(layerGroupItem4); // layerGroup.addLayer(layerGroupItem5); -layerGroup.on('pm:dragstart', function(e) { +layerGroup.on('pm:dragstart', function (e) { console.log(e); }); -layerGroup.on('pm:drag', function(e) { +layerGroup.on('pm:drag', function (e) { console.log(e); }); -layerGroup.on('pm:dragend', function(e) { +layerGroup.on('pm:dragend', function (e) { console.log(e); }); -layerGroup.on('pm:markerdragstart', function(e) { +layerGroup.on('pm:markerdragstart', function (e) { console.log(e); }); -layerGroup.on('pm:markerdragend', function(e) { +layerGroup.on('pm:markerdragend', function (e) { console.log(e); }); diff --git a/demo/events.html b/demo/events.html index 6f813fc8..cf8820cf 100644 --- a/demo/events.html +++ b/demo/events.html @@ -1,29 +1,29 @@ - + - - - + + Leaflet Geoman Events Demo - - + + - - + +
-
-

Overview of the available events (Console)

- -
+
+

Overview of the available events (Console)

-
+
+
- - + diff --git a/demo/events.js b/demo/events.js index ea3792a5..17c93407 100644 --- a/demo/events.js +++ b/demo/events.js @@ -1,82 +1,82 @@ var map = L.map('map').setView([39.74739, -105], 13); map.pm.addControls(); -map.pm.setLang("de"); +map.pm.setLang('de'); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: '© OpenStreetMap contributors' + maxZoom: 19, + attribution: + '© OpenStreetMap contributors', }).addTo(map); -function logEvent(e){ - console.log(e); +function logEvent(e) { + console.log(e); } -map.on('pm:drawstart',function (e) { - logEvent(e); - var layer = e.workingLayer; - - layer.on('pm:vertexadded', logEvent); - layer.on('pm:snapdrag', logEvent); - layer.on('pm:snap', logEvent); - layer.on('pm:unsnap', logEvent); - layer.on('pm:centerplaced', logEvent); +map.on('pm:drawstart', function (e) { + logEvent(e); + var layer = e.workingLayer; + layer.on('pm:vertexadded', logEvent); + layer.on('pm:snapdrag', logEvent); + layer.on('pm:snap', logEvent); + layer.on('pm:unsnap', logEvent); + layer.on('pm:centerplaced', logEvent); }); -map.on('pm:drawend',logEvent); -map.on('pm:create',function (e) { - logEvent(e); - var layer = e.layer; - - map.pm.disableDraw(); - - layer.pm.enable({ - allowSelfIntersection: false, - }); - - //Edit Event - layer.on('pm:edit', logEvent); - layer.on('pm:update', logEvent); - layer.on('pm:enable', logEvent); - layer.on('pm:disable', logEvent); - layer.on('pm:vertexadded', logEvent); - layer.on('pm:vertexremoved', logEvent); - layer.on('pm:markerdragstart', logEvent); - layer.on('pm:markerdrag', logEvent); - layer.on('pm:markerdragend', logEvent); - layer.on('pm:snap', logEvent); - layer.on('pm:snapdrag', logEvent); - layer.on('pm:unsnap', logEvent); - layer.on('pm:intersect', logEvent); - layer.on('pm:centerplaced', logEvent); - - //Drag event - layer.on('pm:dragstart',logEvent); - layer.on('pm:drag',logEvent); - layer.on('pm:dragend',logEvent); - - //Cut event - layer.on('pm:cut',logEvent); - - //Remove event - layer.on('pm:remove',logEvent); +map.on('pm:drawend', logEvent); +map.on('pm:create', function (e) { + logEvent(e); + var layer = e.layer; + + map.pm.disableDraw(); + + layer.pm.enable({ + allowSelfIntersection: false, + }); + + //Edit Event + layer.on('pm:edit', logEvent); + layer.on('pm:update', logEvent); + layer.on('pm:enable', logEvent); + layer.on('pm:disable', logEvent); + layer.on('pm:vertexadded', logEvent); + layer.on('pm:vertexremoved', logEvent); + layer.on('pm:markerdragstart', logEvent); + layer.on('pm:markerdrag', logEvent); + layer.on('pm:markerdragend', logEvent); + layer.on('pm:snap', logEvent); + layer.on('pm:snapdrag', logEvent); + layer.on('pm:unsnap', logEvent); + layer.on('pm:intersect', logEvent); + layer.on('pm:centerplaced', logEvent); + + //Drag event + layer.on('pm:dragstart', logEvent); + layer.on('pm:drag', logEvent); + layer.on('pm:dragend', logEvent); + + //Cut event + layer.on('pm:cut', logEvent); + + //Remove event + layer.on('pm:remove', logEvent); }); //Toggle mode events -map.on('pm:globaleditmodetoggled',logEvent); -map.on('pm:globaldragmodetoggled',logEvent); -map.on('pm:globalremovalmodetoggled',logEvent); -map.on('pm:globaldrawmodetoggled',logEvent); -map.on('pm:globalcutmodetoggled',logEvent); +map.on('pm:globaleditmodetoggled', logEvent); +map.on('pm:globaldragmodetoggled', logEvent); +map.on('pm:globalremovalmodetoggled', logEvent); +map.on('pm:globaldrawmodetoggled', logEvent); +map.on('pm:globalcutmodetoggled', logEvent); //Remove event -map.on('pm:remove',logEvent); -map.on('layerremove',logEvent); +map.on('pm:remove', logEvent); +map.on('layerremove', logEvent); //Cut event -map.on('pm:cut',logEvent); +map.on('pm:cut', logEvent); //Language changed -map.on('pm:langchange',logEvent); +map.on('pm:langchange', logEvent); -map.pm.setLang("en"); +map.pm.setLang('en'); diff --git a/demo/index-canvas.html b/demo/index-canvas.html index 4ae25e08..91a41d33 100644 --- a/demo/index-canvas.html +++ b/demo/index-canvas.html @@ -1,49 +1,48 @@ - + - - - + + Leaflet Geoman Demo - - + + + - - - +
- -
-

Leaflet Polygon Management

-

An Open Source Leaflet Plugin for editing polygons, specifically made for Leaflet 1.0

-
-
-

Creating A Polygon

- -
- -
-
-

Editing A Polygon

- -
- -
-
-

Editing A Layer Group

- -
- -
+
+

Leaflet Polygon Management

+

+ An Open Source Leaflet Plugin for editing polygons, specifically made + for Leaflet 1.0 +

+
+
+

Creating A Polygon

+ +
+
+
+

Editing A Polygon

+ +
+
+
+

Editing A Layer Group

+ +
+
- - + diff --git a/demo/index.html b/demo/index.html index b5d1d0ea..0c3d0a5d 100644 --- a/demo/index.html +++ b/demo/index.html @@ -1,50 +1,48 @@ - + - - - + + Leaflet Geoman Demo - - + + + - - - - +
- -
-

Leaflet Polygon Management

-

An Open Source Leaflet Plugin for editing polygons, specifically made for Leaflet 1.0

-
-
-

Creating A Polygon

- -
- -
-
-

Editing A Polygon

- -
- -
-
-

Editing A Layer Group

- -
- -
+
+

Leaflet Polygon Management

+

+ An Open Source Leaflet Plugin for editing polygons, specifically made + for Leaflet 1.0 +

+
+
+

Creating A Polygon

+ +
+
+
+

Editing A Polygon

+ +
+
+
+

Editing A Layer Group

+ +
+
- - + diff --git a/index.html b/index.html index f7b8818d..b557433e 100644 --- a/index.html +++ b/index.html @@ -1,10 +1,12 @@ - + - - + Leaflet Geometry Management - + @@ -16,36 +18,35 @@ --> - + - +
-
+
- - - \ No newline at end of file + + diff --git a/leaflet-geoman.d.ts b/leaflet-geoman.d.ts index 449ab6d6..8acabe94 100644 --- a/leaflet-geoman.d.ts +++ b/leaflet-geoman.d.ts @@ -2,1199 +2,1464 @@ import * as L from 'leaflet'; // redeclare module, maintains compatibility with @types/leaflet declare module 'leaflet' { + /** + * Extends built in leaflet Layer Options. + */ + interface LayerOptions { + pmIgnore?: boolean; + snapIgnore?: boolean; + } + + /** + * Extends built in leaflet Map Options. + */ + interface MapOptions { + pmIgnore?: boolean; + } + + /** + * Extends built in leaflet Map. + */ + interface Map { + pm: PM.PMMap; + } + + /** + * Extends built in leaflet Path. + */ + interface Path { + pm: PM.PMLayer; + } + /** + * Extends built in leaflet ImageOverlay. + */ + interface ImageOverlay { + pm: PM.PMLayer; + } + + /** + * Extends built in leaflet LayerGroup. + */ + interface LayerGroup { + pm: PM.PMLayerGroup; + } + + /** + * Extends built in leaflet Polyline. + */ + interface Polyline { + /** Returns true if Line or Polygon has a self intersection. */ + hasSelfIntersection(): boolean; + } + + /** + * Extends @types/leaflet events... + * + * todo: This is kind of a mess, and it makes all these event handlers show + * up on Layers and Map. Leaflet itself is based around Evented, and @types/leaflet + * makes this very hard to work around. + * + */ + interface Evented { + /****************************************** + * + * AVAILABLE ON MAP + LAYER, THESE ARE OK ON EVENTED. + * + ********************************************/ + + /** Fired when a layer is removed via Removal Mode. */ + on(type: 'pm:remove', fn: PM.RemoveEventHandler): this; + once(type: 'pm:remove', fn: PM.RemoveEventHandler): this; + off(type: 'pm:remove', fn?: PM.RemoveEventHandler): this; + + /** Fired when the layer being cut. Draw+Edit Mode*/ + on(type: 'pm:cut', fn: PM.CutEventHandler): this; + once(type: 'pm:cut', fn: PM.CutEventHandler): this; + off(type: 'pm:cut', fn?: PM.CutEventHandler): this; + + /** Fired when rotation is enabled for a layer. */ + on(type: 'pm:rotateenable', fn: PM.RotateEnableEventHandler): this; + once(type: 'pm:rotateenable', fn: PM.RotateEnableEventHandler): this; + off(type: 'pm:rotateenable', fn?: PM.RotateEnableEventHandler): this; + + /** Fired when rotation is disabled for a layer. */ + on(type: 'pm:rotatedisable', fn: PM.RotateDisableEventHandler): this; + once(type: 'pm:rotatedisable', fn: PM.RotateDisableEventHandler): this; + off(type: 'pm:rotatedisable', fn?: PM.RotateDisableEventHandler): this; + + /** Fired when rotation starts on a layer. */ + on(type: 'pm:rotatestart', fn: PM.RotateStartEventHandler): this; + once(type: 'pm:rotatestart', fn: PM.RotateStartEventHandler): this; + off(type: 'pm:rotatestart', fn?: PM.RotateStartEventHandler): this; + + /** Fired when a layer is rotated. */ + on(type: 'pm:rotate', fn: PM.RotateEventHandler): this; + once(type: 'pm:rotate', fn: PM.RotateEventHandler): this; + off(type: 'pm:rotate', fn?: PM.RotateEventHandler): this; + + /** Fired when rotation ends on a layer. */ + on(type: 'pm:rotateend', fn: PM.RotateEndEventHandler): this; + once(type: 'pm:rotateend', fn: PM.RotateEndEventHandler): this; + off(type: 'pm:rotateend', fn?: PM.RotateEndEventHandler): this; + + /****************************************** + * + * TODO: DRAW/EDIT MODE EVENTS LAYER ONLY + * + ********************************************/ - /** - * Extends built in leaflet Layer Options. - */ - interface LayerOptions { - pmIgnore?: boolean; - snapIgnore?: boolean; - } + /** Fired during a marker move/drag. */ + on(type: 'pm:snapdrag', fn: PM.SnapEventHandler): this; + once(type: 'pm:snapdrag', fn: PM.SnapEventHandler): this; + off(type: 'pm:snapdrag', fn?: PM.SnapEventHandler): this; - /** - * Extends built in leaflet Map Options. - */ - interface MapOptions { - pmIgnore?: boolean; - } + /** Fired when a vertex is snapped. */ + on(type: 'pm:snap', fn: PM.SnapEventHandler): this; + once(type: 'pm:snap', fn: PM.SnapEventHandler): this; + off(type: 'pm:snap', fn?: PM.SnapEventHandler): this; + + /** Fired when a vertex is unsnapped. */ + on(type: 'pm:unsnap', fn: PM.SnapEventHandler): this; + once(type: 'pm:unsnap', fn: PM.SnapEventHandler): this; + off(type: 'pm:unsnap', fn?: PM.SnapEventHandler): this; + + /** Called when the center of a circle is placed/moved. */ + on(type: 'pm:centerplaced', fn: PM.CenterPlacedEventHandler): this; + once(type: 'pm:centerplaced', fn: PM.CenterPlacedEventHandler): this; + off(type: 'pm:centerplaced', fn?: PM.CenterPlacedEventHandler): this; + + /****************************************** + * + * TODO: CUT/EDIT MODE EVENTS LAYER ONLY + * + ********************************************/ + + /** Fired when a layer is edited. */ + on(type: 'pm:edit', fn: PM.EditEventHandler): this; + once(type: 'pm:edit', fn: PM.EditEventHandler): this; + off(type: 'pm:edit', fn?: PM.EditEventHandler): this; + + /****************************************** + * + * TODO: DRAW MODE EVENTS ON MAP ONLY + * + ********************************************/ + + /** Fired when Drawing Mode is toggled. */ + on( + type: 'pm:globaldrawmodetoggled', + fn: PM.GlobalDrawModeToggledEventHandler, + context?: any + ): L.Evented; + once( + type: 'pm:globaldrawmodetoggled', + fn: PM.GlobalDrawModeToggledEventHandler, + context?: any + ): L.Evented; + off( + type: 'pm:globaldrawmodetoggled', + fn?: PM.GlobalDrawModeToggledEventHandler, + context?: any + ): L.Evented; + + /** Called when drawing mode is enabled. Payload includes the shape type and working layer. */ + on( + type: 'pm:drawstart', + fn: PM.DrawStartEventHandler, + context?: any + ): L.Evented; + once( + type: 'pm:drawstart', + fn: PM.DrawStartEventHandler, + context?: any + ): L.Evented; + off( + type: 'pm:drawstart', + fn?: PM.DrawStartEventHandler, + context?: any + ): L.Evented; + + /** Called when drawing mode is disabled. Payload includes the shape type. */ + on( + type: 'pm:drawend', + fn: PM.DrawEndEventHandler, + context?: any + ): L.Evented; + once( + type: 'pm:drawend', + fn: PM.DrawEndEventHandler, + context?: any + ): L.Evented; + off( + type: 'pm:drawend', + fn?: PM.DrawEndEventHandler, + context?: any + ): L.Evented; + + /** Called when drawing mode is disabled. Payload includes the shape type. */ + on(type: 'pm:create', fn: PM.CreateEventHandler, context?: any): L.Evented; + once( + type: 'pm:create', + fn: PM.CreateEventHandler, + context?: any + ): L.Evented; + off( + type: 'pm:create', + fn?: PM.CreateEventHandler, + context?: any + ): L.Evented; + + /****************************************** + * + * TODO: DRAW MODE EVENTS ON LAYER ONLY + * + ********************************************/ + + /** Called when a new vertex is added. */ + on(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler): this; + once(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler): this; + off(type: 'pm:vertexadded', fn?: PM.VertexAddedEventHandler): this; + + /****************************************** + * + * TODO: EDIT MODE EVENTS ON LAYER ONLY + * + ********************************************/ + + /** Fired when edit mode is disabled and a layer is edited and its coordinates have changed. */ + on(type: 'pm:update', fn: PM.UpdateEventHandler): this; + once(type: 'pm:update', fn: PM.UpdateEventHandler): this; + off(type: 'pm:update', fn?: PM.UpdateEventHandler): this; + + /** Fired when edit mode on a layer is enabled. */ + on(type: 'pm:enable', fn: PM.EnableEventHandler): this; + once(type: 'pm:enable', fn: PM.EnableEventHandler): this; + off(type: 'pm:enable', fn?: PM.EnableEventHandler): this; + + /** Fired when edit mode on a layer is disabled. */ + on(type: 'pm:disable', fn: PM.DisableEventHandler): this; + once(type: 'pm:disable', fn: PM.DisableEventHandler): this; + off(type: 'pm:disable', fn?: PM.DisableEventHandler): this; + + /** Fired when a vertex is added. */ + on(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler2): this; + once(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler2): this; + off(type: 'pm:vertexadded', fn?: PM.VertexAddedEventHandler2): this; + + /** Fired when a vertex is removed. */ + on(type: 'pm:vertexremoved', fn: PM.VertexRemovedEventHandler): this; + once(type: 'pm:vertexremoved', fn: PM.VertexRemovedEventHandler): this; + off(type: 'pm:vertexremoved', fn?: PM.VertexRemovedEventHandler): this; + + /** Fired when a vertex is clicked. */ + on(type: 'pm:vertexclick', fn: PM.VertexClickEventHandler): this; + once(type: 'pm:vertexclick', fn: PM.VertexClickEventHandler): this; + off(type: 'pm:vertexclick', fn?: PM.VertexClickEventHandler): this; + + /** Fired when dragging of a marker which corresponds to a vertex starts. */ + on(type: 'pm:markerdragstart', fn: PM.MarkerDragStartEventHandler): this; + once(type: 'pm:markerdragstart', fn: PM.MarkerDragStartEventHandler): this; + off(type: 'pm:markerdragstart', fn?: PM.MarkerDragStartEventHandler): this; + + /** Fired when dragging a vertex-marker. */ + on(type: 'pm:markerdrag', fn: PM.MarkerDragEventHandler): this; + once(type: 'pm:markerdrag', fn: PM.MarkerDragEventHandler): this; + off(type: 'pm:markerdrag', fn?: PM.MarkerDragEventHandler): this; + + /** Fired when dragging of a vertex-marker ends. */ + on(type: 'pm:markerdragend', fn: PM.MarkerDragEndEventHandler): this; + once(type: 'pm:markerdragend', fn: PM.MarkerDragEndEventHandler): this; + off(type: 'pm:markerdragend', fn?: PM.MarkerDragEndEventHandler): this; + + /** Fired when coords of a layer are reset. E.g. by self-intersection.. */ + on(type: 'pm:layerreset', fn: PM.LayerResetEventHandler): this; + once(type: 'pm:layerreset', fn: PM.LayerResetEventHandler): this; + off(type: 'pm:layerreset', fn?: PM.LayerResetEventHandler): this; + + /** When allowSelfIntersection: false, this event is fired as soon as a self-intersection is detected. */ + on(type: 'pm:intersect', fn: PM.IntersectEventHandler): this; + once(type: 'pm:intersect', fn: PM.IntersectEventHandler): this; + off(type: 'pm:intersect', fn?: PM.IntersectEventHandler): this; + + /****************************************** + * + * TODO: EDIT MODE EVENTS ON MAP ONLY + * + ********************************************/ + + /** Fired when Edit Mode is toggled. */ + on( + type: 'pm:globaleditmodetoggled', + fn: PM.GlobalEditModeToggledEventHandler + ): this; + once( + type: 'pm:globaleditmodetoggled', + fn: PM.GlobalEditModeToggledEventHandler + ): this; + off( + type: 'pm:globaleditmodetoggled', + fn?: PM.GlobalEditModeToggledEventHandler + ): this; + + /****************************************** + * + * TODO: DRAG MODE EVENTS ON MAP ONLY + * + ********************************************/ + + /** Fired when Drag Mode is toggled. */ + on( + type: 'pm:globaldragmodetoggled', + fn: PM.GlobalDragModeToggledEventHandler + ): this; + once( + type: 'pm:globaldragmodetoggled', + fn: PM.GlobalDragModeToggledEventHandler + ): this; + off( + type: 'pm:globaldragmodetoggled', + fn?: PM.GlobalDragModeToggledEventHandler + ): this; + + /****************************************** + * + * TODO: DRAG MODE EVENTS ON LAYER ONLY + * + ********************************************/ + + /** Fired when a layer starts being dragged. */ + on(type: 'pm:dragstart', fn: PM.DragStartEventHandler): this; + once(type: 'pm:dragstart', fn: PM.DragStartEventHandler): this; + off(type: 'pm:dragstart', fn?: PM.DragStartEventHandler): this; + + /** Fired when a layer is dragged. */ + on(type: 'pm:drag', fn: PM.DragEventHandler): this; + once(type: 'pm:drag', fn: PM.DragEventHandler): this; + off(type: 'pm:drag', fn?: PM.DragEventHandler): this; + + /** Fired when a layer stops being dragged. */ + on(type: 'pm:dragend', fn: PM.DragEndEventHandler): this; + once(type: 'pm:dragend', fn: PM.DragEndEventHandler): this; + off(type: 'pm:dragend', fn?: PM.DragEndEventHandler): this; + + /****************************************** + * + * TODO: REMOVE MODE EVENTS ON MAP ONLY + * + ********************************************/ + + /** Fired when Removal Mode is toggled. */ + on( + type: 'pm:globalremovalmodetoggled', + fn: PM.GlobalRemovalModeToggledEventHandler + ): this; + once( + type: 'pm:globalremovalmodetoggled', + fn: PM.GlobalRemovalModeToggledEventHandler + ): this; + off( + type: 'pm:globalremovalmodetoggled', + fn?: PM.GlobalRemovalModeToggledEventHandler + ): this; + + /****************************************** + * + * TODO: CUT MODE EVENTS ON MAP ONLY + * + ********************************************/ + + /** Fired when a layer is removed via Removal Mode. */ + on( + type: 'pm:globalcutmodetoggled', + fn: PM.GlobalCutModeToggledEventHandler + ): this; + once( + type: 'pm:globalcutmodetoggled', + fn: PM.GlobalCutModeToggledEventHandler + ): this; + off( + type: 'pm:globalcutmodetoggled', + fn?: PM.GlobalCutModeToggledEventHandler + ): this; + + /****************************************** + * + * TODO: ROTATE MODE EVENTS ON MAP ONLY + * + ********************************************/ + + /** Fired when Rotate Mode is toggled. */ + on( + type: 'pm:globalrotatemodetoggled', + fn: PM.GlobalRotateModeToggledEventHandler + ): this; + once( + type: 'pm:globalrotatemodetoggled', + fn: PM.GlobalRotateModeToggledEventHandler + ): this; + off( + type: 'pm:globalrotatemodetoggled', + fn?: PM.GlobalRotateModeToggledEventHandler + ): this; + + /****************************************** + * + * TODO: TRANSLATION EVENTS ON MAP ONLY + * + ********************************************/ + + /** Standard Leaflet event. Fired when any layer is removed. */ + on(type: 'pm:langchange', fn: PM.LangChangeEventHandler): this; + once(type: 'pm:langchange', fn: PM.LangChangeEventHandler): this; + off(type: 'pm:langchange', fn?: PM.LangChangeEventHandler): this; + + /****************************************** + * + * TODO: CONTROL EVENTS ON MAP ONLY + * + ********************************************/ + + /** Fired when a Toolbar button is clicked. */ + on(type: 'pm:buttonclick', fn: PM.ButtonClickEventHandler): this; + once(type: 'pm:buttonclick', fn: PM.ButtonClickEventHandler): this; + off(type: 'pm:buttonclick', fn?: PM.ButtonClickEventHandler): this; + + /** Fired when a Toolbar action is clicked. */ + on(type: 'pm:actionclick', fn: PM.ActionClickEventHandler): this; + once(type: 'pm:actionclick', fn: PM.ActionClickEventHandler): this; + off(type: 'pm:actionclick', fn?: PM.ActionClickEventHandler): this; + + /****************************************** + * + * TODO: Keyboard EVENT ON MAP ONLY + * + ********************************************/ + + /** Fired when `keydown` or `keyup` on the document is fired. */ + on(type: 'pm:keyevent', fn: PM.KeyboardKeyEventHandler): this; + once(type: 'pm:keyevent', fn: PM.KeyboardKeyEventHandler): this; + off(type: 'pm:keyevent', fn?: PM.KeyboardKeyEventHandler): this; + } + + namespace PM { + /** supported shape names. 'ImageOverlay' is in Edit Mode only. Also accepts custom shape name. */ + type SUPPORTED_SHAPES = + | 'Marker' + | 'Circle' + | 'Line' + | 'Rectangle' + | 'Polygon' + | 'Cut' + | 'CircleMarker' + | 'ImageOverlay' + | string; /** - * Extends built in leaflet Map. + * Changes default registration of leaflet-geoman on leaflet layers. + * + * @param optIn - if true, a layers pmIgnore property has to be set to false to get initiated. */ - interface Map { - pm: PM.PMMap; - } + function setOptIn(optIn: boolean): void; /** - * Extends built in leaflet Path. + * Enable leaflet-geoman on an ignored layer. + * + * @param layer - re-reads layer.options.pmIgnore to initialize leaflet-geoman. */ - interface Path { - pm: PM.PMLayer; - } + function reInitLayer(layer: L.Layer): void; + /** - * Extends built in leaflet ImageOverlay. + * PM map interface. */ - interface ImageOverlay { - pm: PM.PMLayer + interface PMMap + extends PMDrawMap, + PMEditMap, + PMDragMap, + PMRemoveMap, + PMCutMap, + PMRotateMap { + Toolbar: PMMapToolbar; + + Keyboard: PMMapKeyboard; + + /** Adds the Toolbar to the map. */ + addControls(options?: ToolbarOptions): void; + + /** Toggle the visiblity of the Toolbar. */ + removeControls(): void; + + /** Returns true if the Toolbar is visible on the map. */ + controlsVisible(): boolean; + + /** Toggle the visiblity of the Toolbar. */ + toggleControls(): void; + + setLang( + lang: + | 'cz' + | 'da' + | 'de' + | 'el' + | 'en' + | 'es' + | 'fa' + | 'fr' + | 'hu' + | 'id' + | 'it' + | 'nl' + | 'no' + | 'pl' + | 'pt_br' + | 'ro' + | 'ru' + | 'sv' + | 'tr' + | 'ua' + | 'zh' + | 'zh_tw', + customTranslations?: Translations, + fallbackLanguage?: string + ): void; + + /** Set globalOptions and apply them. */ + setGlobalOptions(options: GlobalOptions): void; + + /** Apply the current globalOptions to all existing layers. */ + applyGlobalOptions(): void; + + /** Returns the globalOptions. */ + getGlobalOptions(): GlobalOptions; } - /** - * Extends built in leaflet LayerGroup. - */ - interface LayerGroup { - pm: PM.PMLayerGroup; + class Translations { + tooltips?: { + placeMarker?: string; + firstVertex?: string; + continueLine?: string; + finishLine?: string; + finishPoly?: string; + finishRect?: string; + startCircle?: string; + finishCircle?: string; + placeCircleMarker?: string; + }; + + actions?: { + finish?: string; + cancel?: string; + removeLastVertex?: string; + }; + + buttonTitles?: { + drawMarkerButton?: string; + drawPolyButton?: string; + drawLineButton?: string; + drawCircleButton?: string; + drawRectButton?: string; + editButton?: string; + dragButton?: string; + cutButton?: string; + deleteButton?: string; + drawCircleMarkerButton?: string; + }; } - /** - * Extends built in leaflet Polyline. - */ - interface Polyline { - /** Returns true if Line or Polygon has a self intersection. */ - hasSelfIntersection(): boolean; + type ACTION_NAMES = 'cancel' | 'removeLastVertex' | 'finish' | 'finishMode'; + + class Action { + text: string; + onClick?: (e: any) => void; } - /** - * Extends @types/leaflet events... - * - * todo: This is kind of a mess, and it makes all these event handlers show - * up on Layers and Map. Leaflet itself is based around Evented, and @types/leaflet - * makes this very hard to work around. - * - */ - interface Evented { - - /****************************************** - * - * AVAILABLE ON MAP + LAYER, THESE ARE OK ON EVENTED. - * - ********************************************/ - - /** Fired when a layer is removed via Removal Mode. */ - on(type: 'pm:remove', fn: PM.RemoveEventHandler): this; - once(type: 'pm:remove', fn: PM.RemoveEventHandler): this; - off(type: 'pm:remove', fn?: PM.RemoveEventHandler): this; - - /** Fired when the layer being cut. Draw+Edit Mode*/ - on(type: 'pm:cut', fn: PM.CutEventHandler): this; - once(type: 'pm:cut', fn: PM.CutEventHandler): this; - off(type: 'pm:cut', fn?: PM.CutEventHandler): this; - - /** Fired when rotation is enabled for a layer. */ - on(type: 'pm:rotateenable', fn: PM.RotateEnableEventHandler): this; - once(type: 'pm:rotateenable', fn: PM.RotateEnableEventHandler): this; - off(type: 'pm:rotateenable', fn?: PM.RotateEnableEventHandler): this; - - /** Fired when rotation is disabled for a layer. */ - on(type: 'pm:rotatedisable', fn: PM.RotateDisableEventHandler): this; - once(type: 'pm:rotatedisable', fn: PM.RotateDisableEventHandler): this; - off(type: 'pm:rotatedisable', fn?: PM.RotateDisableEventHandler): this; - - /** Fired when rotation starts on a layer. */ - on(type: 'pm:rotatestart', fn: PM.RotateStartEventHandler): this; - once(type: 'pm:rotatestart', fn: PM.RotateStartEventHandler): this; - off(type: 'pm:rotatestart', fn?: PM.RotateStartEventHandler): this; - - /** Fired when a layer is rotated. */ - on(type: 'pm:rotate', fn: PM.RotateEventHandler): this; - once(type: 'pm:rotate', fn: PM.RotateEventHandler): this; - off(type: 'pm:rotate', fn?: PM.RotateEventHandler): this; - - /** Fired when rotation ends on a layer. */ - on(type: 'pm:rotateend', fn: PM.RotateEndEventHandler): this; - once(type: 'pm:rotateend', fn: PM.RotateEndEventHandler): this; - off(type: 'pm:rotateend', fn?: PM.RotateEndEventHandler): this; - - - /****************************************** - * - * TODO: DRAW/EDIT MODE EVENTS LAYER ONLY - * - ********************************************/ - - /** Fired during a marker move/drag. */ - on(type: 'pm:snapdrag', fn: PM.SnapEventHandler): this; - once(type: 'pm:snapdrag', fn: PM.SnapEventHandler): this; - off(type: 'pm:snapdrag', fn?: PM.SnapEventHandler): this; - - /** Fired when a vertex is snapped. */ - on(type: 'pm:snap', fn: PM.SnapEventHandler): this; - once(type: 'pm:snap', fn: PM.SnapEventHandler): this; - off(type: 'pm:snap', fn?: PM.SnapEventHandler): this; - - /** Fired when a vertex is unsnapped. */ - on(type: 'pm:unsnap', fn: PM.SnapEventHandler): this; - once(type: 'pm:unsnap', fn: PM.SnapEventHandler): this; - off(type: 'pm:unsnap', fn?: PM.SnapEventHandler): this; - - /** Called when the center of a circle is placed/moved. */ - on(type: 'pm:centerplaced', fn: PM.CenterPlacedEventHandler): this; - once(type: 'pm:centerplaced', fn: PM.CenterPlacedEventHandler): this; - off(type: 'pm:centerplaced', fn?: PM.CenterPlacedEventHandler): this; - - /****************************************** - * - * TODO: CUT/EDIT MODE EVENTS LAYER ONLY - * - ********************************************/ - - /** Fired when a layer is edited. */ - on(type: 'pm:edit', fn: PM.EditEventHandler): this; - once(type: 'pm:edit', fn: PM.EditEventHandler): this; - off(type: 'pm:edit', fn?: PM.EditEventHandler): this; - - - /****************************************** - * - * TODO: DRAW MODE EVENTS ON MAP ONLY - * - ********************************************/ - - /** Fired when Drawing Mode is toggled. */ - on(type: 'pm:globaldrawmodetoggled', fn: PM.GlobalDrawModeToggledEventHandler, context?: any): L.Evented; - once(type: 'pm:globaldrawmodetoggled', fn: PM.GlobalDrawModeToggledEventHandler, context?: any): L.Evented; - off(type: 'pm:globaldrawmodetoggled', fn?: PM.GlobalDrawModeToggledEventHandler, context?: any): L.Evented; - - /** Called when drawing mode is enabled. Payload includes the shape type and working layer. */ - on(type: 'pm:drawstart', fn: PM.DrawStartEventHandler, context?: any): L.Evented; - once(type: 'pm:drawstart', fn: PM.DrawStartEventHandler, context?: any): L.Evented; - off(type: 'pm:drawstart', fn?: PM.DrawStartEventHandler, context?: any): L.Evented; - - /** Called when drawing mode is disabled. Payload includes the shape type. */ - on(type: 'pm:drawend', fn: PM.DrawEndEventHandler, context?: any): L.Evented; - once(type: 'pm:drawend', fn: PM.DrawEndEventHandler, context?: any): L.Evented; - off(type: 'pm:drawend', fn?: PM.DrawEndEventHandler, context?: any): L.Evented; - - /** Called when drawing mode is disabled. Payload includes the shape type. */ - on(type: 'pm:create', fn: PM.CreateEventHandler, context?: any): L.Evented; - once(type: 'pm:create', fn: PM.CreateEventHandler, context?: any): L.Evented; - off(type: 'pm:create', fn?: PM.CreateEventHandler, context?: any): L.Evented; - - - /****************************************** - * - * TODO: DRAW MODE EVENTS ON LAYER ONLY - * - ********************************************/ - - /** Called when a new vertex is added. */ - on(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler): this; - once(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler): this; - off(type: 'pm:vertexadded', fn?: PM.VertexAddedEventHandler): this; - - /****************************************** - * - * TODO: EDIT MODE EVENTS ON LAYER ONLY - * - ********************************************/ - - /** Fired when edit mode is disabled and a layer is edited and its coordinates have changed. */ - on(type: 'pm:update', fn: PM.UpdateEventHandler): this; - once(type: 'pm:update', fn: PM.UpdateEventHandler): this; - off(type: 'pm:update', fn?: PM.UpdateEventHandler): this; - - /** Fired when edit mode on a layer is enabled. */ - on(type: 'pm:enable', fn: PM.EnableEventHandler): this; - once(type: 'pm:enable', fn: PM.EnableEventHandler): this; - off(type: 'pm:enable', fn?: PM.EnableEventHandler): this; - - /** Fired when edit mode on a layer is disabled. */ - on(type: 'pm:disable', fn: PM.DisableEventHandler): this; - once(type: 'pm:disable', fn: PM.DisableEventHandler): this; - off(type: 'pm:disable', fn?: PM.DisableEventHandler): this; - - /** Fired when a vertex is added. */ - on(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler2): this; - once(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler2): this; - off(type: 'pm:vertexadded', fn?: PM.VertexAddedEventHandler2): this; - - /** Fired when a vertex is removed. */ - on(type: 'pm:vertexremoved', fn: PM.VertexRemovedEventHandler): this; - once(type: 'pm:vertexremoved', fn: PM.VertexRemovedEventHandler): this; - off(type: 'pm:vertexremoved', fn?: PM.VertexRemovedEventHandler): this; - - /** Fired when a vertex is clicked. */ - on(type: 'pm:vertexclick', fn: PM.VertexClickEventHandler): this; - once(type: 'pm:vertexclick', fn: PM.VertexClickEventHandler): this; - off(type: 'pm:vertexclick', fn?: PM.VertexClickEventHandler): this; - - /** Fired when dragging of a marker which corresponds to a vertex starts. */ - on(type: 'pm:markerdragstart', fn: PM.MarkerDragStartEventHandler): this; - once(type: 'pm:markerdragstart', fn: PM.MarkerDragStartEventHandler): this; - off(type: 'pm:markerdragstart', fn?: PM.MarkerDragStartEventHandler): this; - - /** Fired when dragging a vertex-marker. */ - on(type: 'pm:markerdrag', fn: PM.MarkerDragEventHandler): this; - once(type: 'pm:markerdrag', fn: PM.MarkerDragEventHandler): this; - off(type: 'pm:markerdrag', fn?: PM.MarkerDragEventHandler): this; - - /** Fired when dragging of a vertex-marker ends. */ - on(type: 'pm:markerdragend', fn: PM.MarkerDragEndEventHandler): this; - once(type: 'pm:markerdragend', fn: PM.MarkerDragEndEventHandler): this; - off(type: 'pm:markerdragend', fn?: PM.MarkerDragEndEventHandler): this; - - /** Fired when coords of a layer are reset. E.g. by self-intersection.. */ - on(type: 'pm:layerreset', fn: PM.LayerResetEventHandler): this; - once(type: 'pm:layerreset', fn: PM.LayerResetEventHandler): this; - off(type: 'pm:layerreset', fn?: PM.LayerResetEventHandler): this; - - /** When allowSelfIntersection: false, this event is fired as soon as a self-intersection is detected. */ - on(type: 'pm:intersect', fn: PM.IntersectEventHandler): this; - once(type: 'pm:intersect', fn: PM.IntersectEventHandler): this; - off(type: 'pm:intersect', fn?: PM.IntersectEventHandler): this; - - - /****************************************** - * - * TODO: EDIT MODE EVENTS ON MAP ONLY - * - ********************************************/ - - /** Fired when Edit Mode is toggled. */ - on(type: 'pm:globaleditmodetoggled', fn: PM.GlobalEditModeToggledEventHandler): this; - once(type: 'pm:globaleditmodetoggled', fn: PM.GlobalEditModeToggledEventHandler): this; - off(type: 'pm:globaleditmodetoggled', fn?: PM.GlobalEditModeToggledEventHandler): this; - - /****************************************** - * - * TODO: DRAG MODE EVENTS ON MAP ONLY - * - ********************************************/ - - /** Fired when Drag Mode is toggled. */ - on(type: 'pm:globaldragmodetoggled', fn: PM.GlobalDragModeToggledEventHandler): this; - once(type: 'pm:globaldragmodetoggled', fn: PM.GlobalDragModeToggledEventHandler): this; - off(type: 'pm:globaldragmodetoggled', fn?: PM.GlobalDragModeToggledEventHandler): this; - - /****************************************** - * - * TODO: DRAG MODE EVENTS ON LAYER ONLY - * - ********************************************/ - - /** Fired when a layer starts being dragged. */ - on(type: 'pm:dragstart', fn: PM.DragStartEventHandler): this; - once(type: 'pm:dragstart', fn: PM.DragStartEventHandler): this; - off(type: 'pm:dragstart', fn?: PM.DragStartEventHandler): this; - - /** Fired when a layer is dragged. */ - on(type: 'pm:drag', fn: PM.DragEventHandler): this; - once(type: 'pm:drag', fn: PM.DragEventHandler): this; - off(type: 'pm:drag', fn?: PM.DragEventHandler): this; - - /** Fired when a layer stops being dragged. */ - on(type: 'pm:dragend', fn: PM.DragEndEventHandler): this; - once(type: 'pm:dragend', fn: PM.DragEndEventHandler): this; - off(type: 'pm:dragend', fn?: PM.DragEndEventHandler): this; - - /****************************************** - * - * TODO: REMOVE MODE EVENTS ON MAP ONLY - * - ********************************************/ - - /** Fired when Removal Mode is toggled. */ - on(type: 'pm:globalremovalmodetoggled', fn: PM.GlobalRemovalModeToggledEventHandler): this; - once(type: 'pm:globalremovalmodetoggled', fn: PM.GlobalRemovalModeToggledEventHandler): this; - off(type: 'pm:globalremovalmodetoggled', fn?: PM.GlobalRemovalModeToggledEventHandler): this; - - /****************************************** - * - * TODO: CUT MODE EVENTS ON MAP ONLY - * - ********************************************/ - - /** Fired when a layer is removed via Removal Mode. */ - on(type: 'pm:globalcutmodetoggled', fn: PM.GlobalCutModeToggledEventHandler): this; - once(type: 'pm:globalcutmodetoggled', fn: PM.GlobalCutModeToggledEventHandler): this; - off(type: 'pm:globalcutmodetoggled', fn?: PM.GlobalCutModeToggledEventHandler): this; - - - /****************************************** - * - * TODO: ROTATE MODE EVENTS ON MAP ONLY - * - ********************************************/ - - /** Fired when Rotate Mode is toggled. */ - on(type: 'pm:globalrotatemodetoggled', fn: PM.GlobalRotateModeToggledEventHandler): this; - once(type: 'pm:globalrotatemodetoggled', fn: PM.GlobalRotateModeToggledEventHandler): this; - off(type: 'pm:globalrotatemodetoggled', fn?: PM.GlobalRotateModeToggledEventHandler): this; - - - /****************************************** - * - * TODO: TRANSLATION EVENTS ON MAP ONLY - * - ********************************************/ - - /** Standard Leaflet event. Fired when any layer is removed. */ - on(type: 'pm:langchange', fn: PM.LangChangeEventHandler): this; - once(type: 'pm:langchange', fn: PM.LangChangeEventHandler): this; - off(type: 'pm:langchange', fn?: PM.LangChangeEventHandler): this; - - /****************************************** - * - * TODO: CONTROL EVENTS ON MAP ONLY - * - ********************************************/ - - /** Fired when a Toolbar button is clicked. */ - on(type: 'pm:buttonclick', fn: PM.ButtonClickEventHandler): this; - once(type: 'pm:buttonclick', fn: PM.ButtonClickEventHandler): this; - off(type: 'pm:buttonclick', fn?: PM.ButtonClickEventHandler): this; - - /** Fired when a Toolbar action is clicked. */ - on(type: 'pm:actionclick', fn: PM.ActionClickEventHandler): this; - once(type: 'pm:actionclick', fn: PM.ActionClickEventHandler): this; - off(type: 'pm:actionclick', fn?: PM.ActionClickEventHandler): this; - - /****************************************** - * - * TODO: Keyboard EVENT ON MAP ONLY - * - ********************************************/ - - /** Fired when `keydown` or `keyup` on the document is fired. */ - on(type: 'pm:keyevent', fn: PM.KeyboardKeyEventHandler): this; - once(type: 'pm:keyevent', fn: PM.KeyboardKeyEventHandler): this; - off(type: 'pm:keyevent', fn?: PM.KeyboardKeyEventHandler): this; + type TOOLBAR_CONTROL_ORDER = + | 'drawMarker' + | 'drawCircleMarker' + | 'drawPolyline' + | 'drawRectangle' + | 'drawPolygon' + | 'drawCircle' + | 'editMode' + | 'dragMode' + | 'cutPolygon' + | 'removalMode' + | 'rotateMode' + | string; + + interface PMMapToolbar { + /** Pass an array of button names to reorder the buttons in the Toolbar. */ + changeControlOrder(order?: TOOLBAR_CONTROL_ORDER[]): void; + + /** Receive the current order with. */ + getControlOrder(): TOOLBAR_CONTROL_ORDER[]; + + /** The position of a block (draw, edit, custom, options⭐) in the Toolbar can be changed. If not set, the value from position of the Toolbar is taken. */ + setBlockPosition( + block: 'draw' | 'edit' | 'custom' | 'options', + position: L.ControlPosition + ): void; + + /** Returns a Object with the positions for all blocks */ + getBlockPositions(): BlockPositions; + + /** To add a custom Control to the Toolbar */ + createCustomControl(options: CustomControlOptions): void; + + /** Creates a copy of a draw Control. Returns the drawInstance and the control. */ + copyDrawControl( + copyInstance: string, + options?: CustomControlOptions + ): void; + + /** Change the actions of an existing button. */ + changeActionsOfControl( + name: string, + actions: (ACTION_NAMES | Action)[] + ): void; + + /** disable button by control name */ + setButtonDisabled(name: TOOLBAR_CONTROL_ORDER, state: boolean): void; } - namespace PM { - - /** supported shape names. 'ImageOverlay' is in Edit Mode only. Also accepts custom shape name. */ - type SUPPORTED_SHAPES = - | 'Marker' - | 'Circle' - | 'Line' - | 'Rectangle' - | 'Polygon' - | 'Cut' - | 'CircleMarker' - | 'ImageOverlay' - | string; - - /** - * Changes default registration of leaflet-geoman on leaflet layers. - * - * @param optIn - if true, a layers pmIgnore property has to be set to false to get initiated. - */ - function setOptIn(optIn: boolean): void; - - /** - * Enable leaflet-geoman on an ignored layer. - * - * @param layer - re-reads layer.options.pmIgnore to initialize leaflet-geoman. - */ - function reInitLayer(layer: L.Layer): void; - - - /** - * PM map interface. - */ - interface PMMap extends PMDrawMap, PMEditMap, PMDragMap, PMRemoveMap, PMCutMap, PMRotateMap { - - Toolbar: PMMapToolbar; - - Keyboard: PMMapKeyboard; - - /** Adds the Toolbar to the map. */ - addControls(options?: ToolbarOptions): void; - - /** Toggle the visiblity of the Toolbar. */ - removeControls(): void; - - /** Returns true if the Toolbar is visible on the map. */ - controlsVisible(): boolean; - - /** Toggle the visiblity of the Toolbar. */ - toggleControls(): void; - - setLang( - lang: - | 'cz' - | 'da' - | 'de' - | 'el' - | 'en' - | 'es' - | 'fa' - | 'fr' - | 'hu' - | 'id' - | 'it' - | 'nl' - | 'no' - | 'pl' - | 'pt_br' - | 'ro' - | 'ru' - | 'sv' - | 'tr' - | 'ua' - | 'zh' - | 'zh_tw', - customTranslations?: Translations, - fallbackLanguage?: string - ): void; - - /** Set globalOptions and apply them. */ - setGlobalOptions(options: GlobalOptions): void; - - /** Apply the current globalOptions to all existing layers. */ - applyGlobalOptions(): void; - - /** Returns the globalOptions. */ - getGlobalOptions(): GlobalOptions; - } - - class Translations { - tooltips?: { - placeMarker?: string; - firstVertex?: string; - continueLine?: string; - finishLine?: string; - finishPoly?: string; - finishRect?: string; - startCircle?: string; - finishCircle?: string; - placeCircleMarker?: string; - }; - - actions?: { - finish?: string; - cancel?: string; - removeLastVertex?: string; - }; - - buttonTitles?: { - drawMarkerButton?: string; - drawPolyButton?: string; - drawLineButton?: string; - drawCircleButton?: string; - drawRectButton?: string; - editButton?: string; - dragButton?: string; - cutButton?: string; - deleteButton?: string; - drawCircleMarkerButton?: string; - }; - } - - type ACTION_NAMES = 'cancel' | 'removeLastVertex' | 'finish' | 'finishMode'; - - class Action { - text: string; - onClick?: (e: any) => void; - } - - type TOOLBAR_CONTROL_ORDER = - | 'drawMarker' - | 'drawCircleMarker' - | 'drawPolyline' - | 'drawRectangle' - | 'drawPolygon' - | 'drawCircle' - | 'editMode' - | 'dragMode' - | 'cutPolygon' - | 'removalMode' - | 'rotateMode' - | string; - - interface PMMapToolbar { - - /** Pass an array of button names to reorder the buttons in the Toolbar. */ - changeControlOrder(order?: TOOLBAR_CONTROL_ORDER[]): void; - - /** Receive the current order with. */ - getControlOrder(): TOOLBAR_CONTROL_ORDER[]; - - /** The position of a block (draw, edit, custom, options⭐) in the Toolbar can be changed. If not set, the value from position of the Toolbar is taken. */ - setBlockPosition(block: 'draw' | 'edit' | 'custom' | 'options', position: L.ControlPosition): void; - - /** Returns a Object with the positions for all blocks */ - getBlockPositions(): BlockPositions; - - /** To add a custom Control to the Toolbar */ - createCustomControl(options: CustomControlOptions): void; - - /** Creates a copy of a draw Control. Returns the drawInstance and the control. */ - copyDrawControl(copyInstance: string, options?: CustomControlOptions): void; - - /** Change the actions of an existing button. */ - changeActionsOfControl(name: string, actions: (ACTION_NAMES | Action)[]): void; - - /** disable button by control name */ - setButtonDisabled(name: TOOLBAR_CONTROL_ORDER, state: boolean): void; - } + type KEYBOARD_EVENT_TYPE = 'current' | 'keydown' | 'keyup'; - type KEYBOARD_EVENT_TYPE = - | 'current' - | 'keydown' - | 'keyup'; + interface PMMapKeyboard { + /** Pass an array of button names to reorder the buttons in the Toolbar. */ + getLastKeyEvent(type: KEYBOARD_EVENT_TYPE[]): KeyboardKeyEventHandler; - interface PMMapKeyboard { + /** Returns the current pressed key. [KeyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key). */ + getPressedKey(): string; - /** Pass an array of button names to reorder the buttons in the Toolbar. */ - getLastKeyEvent(type: KEYBOARD_EVENT_TYPE[]): KeyboardKeyEventHandler; + /** Returns true if the `Shift` key is currently pressed. */ + isShiftKeyPressed(): boolean; - /** Returns the current pressed key. [KeyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key). */ - getPressedKey(): string; + /** Returns true if the `Alt` key is currently pressed. */ + isAltKeyPressed(): boolean; - /** Returns true if the `Shift` key is currently pressed. */ - isShiftKeyPressed(): boolean; + /** Returns true if the `Ctrl` key is currently pressed. */ + isCtrlKeyPressed(): boolean; - /** Returns true if the `Alt` key is currently pressed. */ - isAltKeyPressed(): boolean; + /** Returns true if the `Meta` key is currently pressed. */ + isMetaKeyPressed(): boolean; + } - /** Returns true if the `Ctrl` key is currently pressed. */ - isCtrlKeyPressed(): boolean; + interface Button { + /** actions */ + actions: (ACTION_NAMES | Action)[]; - /** Returns true if the `Meta` key is currently pressed. */ - isMetaKeyPressed(): boolean; - } + /** Function fired after clicking the control. */ + afterClick: () => void; - interface Button { - /** actions */ - actions: (ACTION_NAMES | Action)[]; + /** CSS class with the Icon. */ + className: string; - /** Function fired after clicking the control. */ - afterClick: () => void; + /** if true, other buttons will be disabled on click (default: true) */ + disableOtherButtons: boolean; - /** CSS class with the Icon. */ - className: string; + /** Control can be toggled. */ + doToggle: boolean; - /** if true, other buttons will be disabled on click (default: true) */ - disableOtherButtons: boolean; + /** Extending Class f. ex. Line, Polygon, ... L.PM.Draw.EXTENDINGCLASS */ + jsClass: string; - /** Control can be toggled. */ - doToggle: boolean; + /** Function fired when clicking the control. */ + onClick: () => void; - /** Extending Class f. ex. Line, Polygon, ... L.PM.Draw.EXTENDINGCLASS */ - jsClass: string; + position: L.ControlPosition; - /** Function fired when clicking the control. */ - onClick: () => void; + /** Text showing when you hover the control. */ + title: string; - position: L.ControlPosition; + /** toggle state true -> enabled, false -> disabled (default: false) */ + toggleStatus: boolean; - /** Text showing when you hover the control. */ - title: string; + /** block of the control. 'options' is ⭐ only. */ + tool?: 'draw' | 'edit' | 'custom' | 'options'; + } - /** toggle state true -> enabled, false -> disabled (default: false) */ - toggleStatus: boolean; + interface CustomControlOptions { + /** Name of the control */ + name: string; - /** block of the control. 'options' is ⭐ only. */ - tool?: 'draw' | 'edit' | 'custom' | 'options'; - } + /** block of the control. 'options' is ⭐ only. */ + block?: 'draw' | 'edit' | 'custom' | 'options'; - interface CustomControlOptions { - /** Name of the control */ - name: string; + /** Text showing when you hover the control. */ + title?: string; - /** block of the control. 'options' is ⭐ only. */ - block?: 'draw' | 'edit' | 'custom' | 'options'; + /** CSS class with the Icon. */ + className?: string; - /** Text showing when you hover the control. */ - title?: string; + /** Function fired when clicking the control. */ + onClick?: () => void; - /** CSS class with the Icon. */ - className?: string; + /** Function fired after clicking the control. */ + afterClick?: () => void; - /** Function fired when clicking the control. */ - onClick?: () => void; + /** actions */ + actions?: (ACTION_NAMES | Action)[]; - /** Function fired after clicking the control. */ - afterClick?: () => void; + /** Control can be toggled. */ + toggle?: boolean; - /** actions */ - actions?: (ACTION_NAMES | Action)[]; + /** Control is disabled. */ + disabled?: boolean; + } - /** Control can be toggled. */ - toggle?: boolean; + type PANE = + | 'mapPane' + | 'tilePane' + | 'overlayPane' + | 'shadowPane' + | 'markerPane' + | 'tooltipPane' + | 'popupPane' + | string; + + interface GlobalOptions extends DrawModeOptions, EditModeOptions { + /** add the created layers to a layergroup instead to the map. */ + layerGroup?: L.Map | L.LayerGroup; + + /** Prioritize the order of snapping. Default: ['Marker','CircleMarker','Circle','Line','Polygon','Rectangle']. */ + snappingOrder: SUPPORTED_SHAPES[]; + + /** Defines in which panes the layers and helper vertices are created. Default: { vertexPane: 'markerPane', layerPane: 'overlayPane', markerPane: 'markerPane' } */ + panes: { vertexPane: PANE; layerPane: PANE; markerPane: PANE }; + } - /** Control is disabled. */ - disabled?: boolean; - } + interface PMDrawMap { + /** Enable Draw Mode with the passed shape. */ + enableDraw(shape: SUPPORTED_SHAPES, options?: DrawModeOptions): void; - type PANE = 'mapPane' | 'tilePane' | 'overlayPane' | 'shadowPane' | 'markerPane' | 'tooltipPane' | 'popupPane' | string; + /** disable all drawing */ + disableDraw(shape?: SUPPORTED_SHAPES): void; - interface GlobalOptions extends DrawModeOptions, EditModeOptions { - /** add the created layers to a layergroup instead to the map. */ - layerGroup?: L.Map | L.LayerGroup; + /** Draw */ + Draw: Draw; - /** Prioritize the order of snapping. Default: ['Marker','CircleMarker','Circle','Line','Polygon','Rectangle']. */ - snappingOrder: SUPPORTED_SHAPES[]; + /** Returns true if global Draw Mode is enabled. false when disabled. */ + globalDrawModeEnabled(): boolean; - /** Defines in which panes the layers and helper vertices are created. Default: { vertexPane: 'markerPane', layerPane: 'overlayPane', markerPane: 'markerPane' } */ - panes: { vertexPane: PANE, layerPane: PANE, markerPane: PANE } - } + /** Customize the style of the drawn layer. Only for L.Path layers. Shapes can be excluded with a ignoreShapes array or merged with the current style with merge: true in optionsModifier. */ + setPathOptions( + options: L.PathOptions, + optionsModifier?: { ignoreShapes?: SUPPORTED_SHAPES[]; merge?: boolean } + ): void; - interface PMDrawMap { - /** Enable Draw Mode with the passed shape. */ - enableDraw(shape: SUPPORTED_SHAPES, options?: DrawModeOptions): void; + /** Returns all Geoman layers on the map as array. Pass true to get a L.FeatureGroup. */ + getGeomanLayers(asFeatureGroup?: boolean): L.FeatureGroup | L.Layer[]; - /** disable all drawing */ - disableDraw(shape?: SUPPORTED_SHAPES): void; + /** Returns all Geoman draw layers on the map as array. Pass true to get a L.FeatureGroup. */ + getGeomanDrawLayers(asFeatureGroup?: boolean): L.FeatureGroup | L.Layer[]; + } - /** Draw */ - Draw: Draw; + interface PMEditMap { + /** Enables edit mode. The passed options are preserved, even when the mode is enabled via the Toolbar */ + enableGlobalEditMode(options?: EditModeOptions): void; - /** Returns true if global Draw Mode is enabled. false when disabled. */ - globalDrawModeEnabled(): boolean; + /** Disables global edit mode. */ + disableGlobalEditMode(): void; - /** Customize the style of the drawn layer. Only for L.Path layers. Shapes can be excluded with a ignoreShapes array or merged with the current style with merge: true in optionsModifier. */ - setPathOptions(options: L.PathOptions, optionsModifier?: { ignoreShapes?: SUPPORTED_SHAPES[], merge?: boolean}): void; + /** Toggles global edit mode. */ + toggleGlobalEditMode(options?: EditModeOptions): void; - /** Returns all Geoman layers on the map as array. Pass true to get a L.FeatureGroup. */ - getGeomanLayers(asFeatureGroup?: boolean): L.FeatureGroup | L.Layer[]; + /** Returns true if global edit mode is enabled. false when disabled. */ + globalEditModeEnabled(): boolean; + } - /** Returns all Geoman draw layers on the map as array. Pass true to get a L.FeatureGroup. */ - getGeomanDrawLayers(asFeatureGroup?: boolean): L.FeatureGroup | L.Layer[]; - } + interface PMDragMap { + /** Enables global drag mode. */ + enableGlobalDragMode(): void; - interface PMEditMap { - /** Enables edit mode. The passed options are preserved, even when the mode is enabled via the Toolbar */ - enableGlobalEditMode(options?: EditModeOptions): void; + /** Disables global drag mode. */ + disableGlobalDragMode(): void; - /** Disables global edit mode. */ - disableGlobalEditMode(): void; + /** Toggles global drag mode. */ + toggleGlobalDragMode(): void; - /** Toggles global edit mode. */ - toggleGlobalEditMode(options?: EditModeOptions): void; + /** Returns true if global drag mode is enabled. false when disabled. */ + globalDragEnabled(): boolean; + } - /** Returns true if global edit mode is enabled. false when disabled. */ - globalEditModeEnabled(): boolean; - } + interface PMRemoveMap { + /** Enables global removal mode. */ + enableGlobalRemovalMode(): void; - interface PMDragMap { - /** Enables global drag mode. */ - enableGlobalDragMode(): void; + /** Disables global removal mode. */ + disableGlobalRemovalMode(): void; - /** Disables global drag mode. */ - disableGlobalDragMode(): void; + /** Toggles global removal mode. */ + toggleGlobalRemovalMode(): void; - /** Toggles global drag mode. */ - toggleGlobalDragMode(): void; + /** Returns true if global removal mode is enabled. false when disabled. */ + globalRemovalModeEnabled(): boolean; + } - /** Returns true if global drag mode is enabled. false when disabled. */ - globalDragEnabled(): boolean; - } + interface PMCutMap { + /** Enables global cut mode. */ + enableGlobalCutMode(options?: CutModeOptions): void; - interface PMRemoveMap { - /** Enables global removal mode. */ - enableGlobalRemovalMode(): void; + /** Disables global cut mode. */ + disableGlobalCutMode(): void; - /** Disables global removal mode. */ - disableGlobalRemovalMode(): void; + /** Toggles global cut mode. */ + toggleGlobalCutMode(options?: CutModeOptions): void; - /** Toggles global removal mode. */ - toggleGlobalRemovalMode(): void; + /** Returns true if global cut mode is enabled. false when disabled. */ + globalCutModeEnabled(): boolean; + } - /** Returns true if global removal mode is enabled. false when disabled. */ - globalRemovalModeEnabled(): boolean; - } + interface PMRotateMap { + /** Enables global rotate mode. */ + enableGlobalRotateMode(): void; - interface PMCutMap { - /** Enables global cut mode. */ - enableGlobalCutMode(options?: CutModeOptions): void; + /** Disables global rotate mode. */ + disableGlobalRotateMode(): void; - /** Disables global cut mode. */ - disableGlobalCutMode(): void; + /** Toggles global rotate mode. */ + toggleGlobalRotateMode(): void; - /** Toggles global cut mode. */ - toggleGlobalCutMode(options?: CutModeOptions): void; + /** Returns true if global rotate mode is enabled. false when disabled. */ + globalRotateModeEnabled(): boolean; + } - /** Returns true if global cut mode is enabled. false when disabled. */ - globalCutModeEnabled(): boolean; - } + interface PMRotateLayer { + /** Enables rotate mode on the layer. */ + enableRotate(): void; - interface PMRotateMap { - /** Enables global rotate mode. */ - enableGlobalRotateMode(): void; + /** Disables rotate mode on the layer. */ + disableRotate(): void; - /** Disables global rotate mode. */ - disableGlobalRotateMode(): void; + /** Toggles rotate mode on the layer. */ + rotateEnabled(): void; - /** Toggles global rotate mode. */ - toggleGlobalRotateMode(): void; + /** Rotates the layer by x degrees. */ + rotateLayer(degrees: number): void; - /** Returns true if global rotate mode is enabled. false when disabled. */ - globalRotateModeEnabled(): boolean; - } + /** Rotates the layer to x degrees. */ + rotateLayerToAngle(degrees: number): void; - interface PMRotateLayer { - /** Enables rotate mode on the layer. */ - enableRotate(): void; + /** Returns the angle of the layer in degrees. */ + getAngle(): number; + } - /** Disables rotate mode on the layer. */ - disableRotate(): void; + interface Draw { + /** Array of available shapes. */ + getShapes(): SUPPORTED_SHAPES[]; - /** Toggles rotate mode on the layer. */ - rotateEnabled(): void; + /** Returns the active shape. */ + getActiveShape(): SUPPORTED_SHAPES; - /** Rotates the layer by x degrees. */ - rotateLayer(degrees: number): void; + /** Set path options */ + setPathOptions(options: L.PathOptions): void; - /** Rotates the layer to x degrees. */ - rotateLayerToAngle(degrees: number): void; + /** Set options */ + setOptions(options: DrawModeOptions): void; - /** Returns the angle of the layer in degrees. */ - getAngle(): number; - } + /** Get options */ + getOptions(): DrawModeOptions; + } - interface Draw { - /** Array of available shapes. */ - getShapes(): SUPPORTED_SHAPES[]; + interface CutModeOptions { + allowSelfIntersection?: boolean; + } - /** Returns the active shape. */ - getActiveShape(): SUPPORTED_SHAPES; + type VertexValidationHandler = (e: { + layer: L.Layer; + marker: L.Marker; + event: any; + }) => boolean; - /** Set path options */ - setPathOptions(options: L.PathOptions): void; + interface EditModeOptions { + /** Enable snapping to other layers vertices for precision drawing. Can be disabled by holding the ALT key (default:true). */ + snappable?: boolean; - /** Set options */ - setOptions(options: DrawModeOptions): void; + /** the distance to another vertex when a snap should happen (default:20). */ + snapDistance?: number; - /** Get options */ - getOptions(): DrawModeOptions; - } + /** allow self intersections (default:true). */ + allowSelfIntersection?: boolean; - interface CutModeOptions { - allowSelfIntersection?: boolean; - } + /** allow self intersections (default:true). */ + allowSelfIntersectionEdit?: boolean; - type VertexValidationHandler = (e: { layer: L.Layer, marker: L.Marker, event: any }) => boolean; + /** Disable the removal of markers via right click / vertices via removeVertexOn. (default:false). */ + preventMarkerRemoval?: boolean; - interface EditModeOptions { - /** Enable snapping to other layers vertices for precision drawing. Can be disabled by holding the ALT key (default:true). */ - snappable?: boolean; + /** If true, vertex removal that cause a layer to fall below their minimum required vertices will remove the entire layer. If false, these vertices can't be removed. Minimum vertices are 2 for Lines and 3 for Polygons (default:true). */ + removeLayerBelowMinVertexCount?: boolean; - /** the distance to another vertex when a snap should happen (default:20). */ - snapDistance?: number; + /** Defines which layers should dragged with this layer together. true syncs all layers in the same LayerGroup(s) or you pass an `Array` of layers to sync. (default:false). */ + syncLayersOnDrag?: L.Layer[] | boolean; - /** allow self intersections (default:true). */ - allowSelfIntersection?: boolean; + /** Edit-Mode for the layer can disabled (`pm.enable()`). (default:true). */ + allowEditing?: boolean; - /** allow self intersections (default:true). */ - allowSelfIntersectionEdit?: boolean; + /** Removing can be disabled for the layer. (default:true). */ + allowRemoval?: boolean; - /** Disable the removal of markers via right click / vertices via removeVertexOn. (default:false). */ - preventMarkerRemoval?: boolean; + /** Layer can be prevented from cutting. (default:true). */ + allowCutting?: boolean; - /** If true, vertex removal that cause a layer to fall below their minimum required vertices will remove the entire layer. If false, these vertices can't be removed. Minimum vertices are 2 for Lines and 3 for Polygons (default:true). */ - removeLayerBelowMinVertexCount?: boolean; + /** Layer can be prevented from rotation. (default:true). */ + allowRotation?: boolean; - /** Defines which layers should dragged with this layer together. true syncs all layers in the same LayerGroup(s) or you pass an `Array` of layers to sync. (default:false). */ - syncLayersOnDrag?: L.Layer[] | boolean; + /** Dragging can be disabled for the layer. (default:true). */ + draggable?: boolean; - /** Edit-Mode for the layer can disabled (`pm.enable()`). (default:true). */ - allowEditing?: boolean; + /** Leaflet layer event to add a vertex to a Line or Polygon, like dblclick. (default:click). */ + addVertexOn?: + | 'click' + | 'dblclick' + | 'mousedown' + | 'mouseover' + | 'mouseout' + | 'contextmenu'; - /** Removing can be disabled for the layer. (default:true). */ - allowRemoval?: boolean; + /** A function for validation if a vertex (of a Line / Polygon) is allowed to add. It passes a object with `[layer, marker, event}`. For example to check if the layer has a certain property or if the `Ctrl` key is pressed. (default:undefined). */ + addVertexValidation?: undefined | VertexValidationHandler; - /** Layer can be prevented from cutting. (default:true). */ - allowCutting?: boolean; + /** Leaflet layer event to remove a vertex from a Line or Polygon, like dblclick. (default:contextmenu). */ + removeVertexOn?: + | 'click' + | 'dblclick' + | 'mousedown' + | 'mouseover' + | 'mouseout' + | 'contextmenu'; - /** Layer can be prevented from rotation. (default:true). */ - allowRotation?: boolean; + /** A function for validation if a vertex (of a Line / Polygon) is allowed to remove. It passes a object with `[layer, marker, event}`. For example to check if the layer has a certain property or if the `Ctrl` key is pressed. */ + removeVertexValidation?: undefined | VertexValidationHandler; - /** Dragging can be disabled for the layer. (default:true). */ - draggable?: boolean; + /** A function for validation if a vertex / helper-marker is allowed to move / drag. It passes a object with `[layer, marker, event}`. For example to check if the layer has a certain property or if the `Ctrl` key is pressed. */ + moveVertexValidation?: undefined | VertexValidationHandler; - /** Leaflet layer event to add a vertex to a Line or Polygon, like dblclick. (default:click). */ - addVertexOn?: - | 'click' - | 'dblclick' - | 'mousedown' - | 'mouseover' - | 'mouseout' - | 'contextmenu'; + /** Shows only n markers closest to the cursor. Use -1 for no limit (default:-1). */ + limitMarkersToCount?: number; - /** A function for validation if a vertex (of a Line / Polygon) is allowed to add. It passes a object with `[layer, marker, event}`. For example to check if the layer has a certain property or if the `Ctrl` key is pressed. (default:undefined). */ - addVertexValidation?: undefined | VertexValidationHandler; + /** Shows markers when under the given zoom level ⭐ */ + limitMarkersToZoom?: number; - /** Leaflet layer event to remove a vertex from a Line or Polygon, like dblclick. (default:contextmenu). */ - removeVertexOn?: - | 'click' - | 'dblclick' - | 'mousedown' - | 'mouseover' - | 'mouseout' - | 'contextmenu'; + /** Shows only markers in the viewport ⭐ */ + limitMarkersToViewport?: boolean; - /** A function for validation if a vertex (of a Line / Polygon) is allowed to remove. It passes a object with `[layer, marker, event}`. For example to check if the layer has a certain property or if the `Ctrl` key is pressed. */ - removeVertexValidation?: undefined | VertexValidationHandler; + /** Shows markers only after the layer was clicked ⭐ */ + limitMarkersToClick?: boolean; - /** A function for validation if a vertex / helper-marker is allowed to move / drag. It passes a object with `[layer, marker, event}`. For example to check if the layer has a certain property or if the `Ctrl` key is pressed. */ - moveVertexValidation?: undefined | VertexValidationHandler; + /** Pin shared vertices/markers together during edit ⭐ */ + pinning?: boolean; - /** Shows only n markers closest to the cursor. Use -1 for no limit (default:-1). */ - limitMarkersToCount?: number; + /** hide the middle Markers in edit mode from Polyline and Polygon. */ + hideMiddleMarkers?: boolean; + } - /** Shows markers when under the given zoom level ⭐ */ - limitMarkersToZoom?: number; + interface DrawModeOptions { + /** enable snapping to other layers vertices for precision drawing. Can be disabled by holding the ALT key (default:true). */ + snappable?: boolean; - /** Shows only markers in the viewport ⭐ */ - limitMarkersToViewport?: boolean; + /** the distance to another vertex when a snap should happen (default:20). */ + snapDistance?: number; - /** Shows markers only after the layer was clicked ⭐ */ - limitMarkersToClick?: boolean; + /** allow snapping in the middle of two vertices (middleMarker)(default:false). */ + snapMiddle?: boolean; - /** Pin shared vertices/markers together during edit ⭐ */ - pinning?: boolean; + /** allow snapping between two vertices. (default: true)*/ + snapSegment?: boolean; - /** hide the middle Markers in edit mode from Polyline and Polygon. */ - hideMiddleMarkers?: boolean; - } + /** require the last point of a shape to be snapped. (default: false). */ + requireSnapToFinish?: boolean; - interface DrawModeOptions { - /** enable snapping to other layers vertices for precision drawing. Can be disabled by holding the ALT key (default:true). */ - snappable?: boolean; + /** show helpful tooltips for your user (default:true). */ + tooltips?: boolean; - /** the distance to another vertex when a snap should happen (default:20). */ - snapDistance?: number; + /** allow self intersections (default:true). */ + allowSelfIntersection?: boolean; - /** allow snapping in the middle of two vertices (middleMarker)(default:false). */ - snapMiddle?: boolean; + /** leaflet path options for the lines between drawn vertices/markers. (default:{color:'red'}). */ + templineStyle?: L.PathOptions; - /** allow snapping between two vertices. (default: true)*/ - snapSegment?: boolean; + /** leaflet path options for the helper line between last drawn vertex and the cursor. (default:{color:'red',dashArray:[5,5]}). */ + hintlineStyle?: L.PathOptions; - /** require the last point of a shape to be snapped. (default: false). */ - requireSnapToFinish?: boolean; + /** leaflet path options for the drawn layer (Only for L.Path layers). (default:null). */ + pathOptions?: L.PathOptions; - /** show helpful tooltips for your user (default:true). */ - tooltips?: boolean; + /** leaflet marker options (only for drawing markers). (default:{draggable:true}). */ + markerStyle?: L.MarkerOptions; - /** allow self intersections (default:true). */ - allowSelfIntersection?: boolean; + /** show a marker at the cursor (default:true). */ + cursorMarker?: boolean; - /** leaflet path options for the lines between drawn vertices/markers. (default:{color:'red'}). */ - templineStyle?: L.PathOptions; + /** leaflet layer event to finish the drawn shape (default:null). */ + finishOn?: + | null + | 'click' + | 'dblclick' + | 'mousedown' + | 'mouseover' + | 'mouseout' + | 'contextmenu' + | 'snap'; - /** leaflet path options for the helper line between last drawn vertex and the cursor. (default:{color:'red',dashArray:[5,5]}). */ - hintlineStyle?: L.PathOptions; + /** hide the middle Markers in edit mode from Polyline and Polygon. (default:false). */ + hideMiddleMarkers?: boolean; - /** leaflet path options for the drawn layer (Only for L.Path layers). (default:null). */ - pathOptions?: L.PathOptions; + /** set the min radius of a Circle. (default:null). */ + minRadiusCircle?: number; - /** leaflet marker options (only for drawing markers). (default:{draggable:true}). */ - markerStyle?: L.MarkerOptions; + /** set the max radius of a Circle. (default:null). */ + maxRadiusCircle?: number; - /** show a marker at the cursor (default:true). */ - cursorMarker?: boolean; + /** set the min radius of a CircleMarker when editable is active. (default:null). */ + minRadiusCircleMarker?: number; - /** leaflet layer event to finish the drawn shape (default:null). */ - finishOn?: - | null - | 'click' - | 'dblclick' - | 'mousedown' - | 'mouseover' - | 'mouseout' - | 'contextmenu' - | 'snap'; + /** set the max radius of a CircleMarker when editable is active. (default:null). */ + maxRadiusCircleMarker?: number; - /** hide the middle Markers in edit mode from Polyline and Polygon. (default:false). */ - hideMiddleMarkers?: boolean; + /** makes a CircleMarker editable like a Circle (default:false). */ + editable?: boolean; - /** set the min radius of a Circle. (default:null). */ - minRadiusCircle?: number; + /** Markers and CircleMarkers are editable during the draw-session (you can drag them around immediately after drawing them) (default:true). */ + markerEditable?: boolean; - /** set the max radius of a Circle. (default:null). */ - maxRadiusCircle?: number; + /** Draw-Mode stays enabled after finishing a layer to immediately draw the next layer. Defaults to true for Markers and CircleMarkers and false for all other layers. */ + continueDrawing?: boolean; - /** set the min radius of a CircleMarker when editable is active. (default:null). */ - minRadiusCircleMarker?: number; + /** angel of rectangle. */ + rectangleAngle?: number; - /** set the max radius of a CircleMarker when editable is active. (default:null). */ - maxRadiusCircleMarker?: number; + /** Cut-Mode: Only the passed layers can be cut. Cutted layers are removed from the Array until no layers are left anymore and cutting is working on all layers again. (Default: []) */ + layersToCut?: L.Layer[]; + } - /** makes a CircleMarker editable like a Circle (default:false). */ - editable?: boolean; + /** + * PM toolbar options. + */ + interface ToolbarOptions { + /** toolbar position. */ + position?: L.ControlPosition; - /** Markers and CircleMarkers are editable during the draw-session (you can drag them around immediately after drawing them) (default:true). */ - markerEditable?: boolean; + /** the position of each block can be customized. If not set, the value from position is taken. */ + positions?: BlockPositions; - /** Draw-Mode stays enabled after finishing a layer to immediately draw the next layer. Defaults to true for Markers and CircleMarkers and false for all other layers. */ - continueDrawing?: boolean; + /** adds button to draw Markers (default:true) */ + drawMarker?: boolean; - /** angel of rectangle. */ - rectangleAngle?: number; + /** adds button to draw CircleMarkers (default:true) */ + drawCircleMarker?: boolean; - /** Cut-Mode: Only the passed layers can be cut. Cutted layers are removed from the Array until no layers are left anymore and cutting is working on all layers again. (Default: []) */ - layersToCut?: L.Layer[]; - } + /** adds button to draw Line (default:true) */ + drawPolyline?: boolean; - /** - * PM toolbar options. - */ - interface ToolbarOptions { - /** toolbar position. */ - position?: L.ControlPosition; + /** adds button to draw Rectangle (default:true) */ + drawRectangle?: boolean; - /** the position of each block can be customized. If not set, the value from position is taken. */ - positions?: BlockPositions; + /** adds button to draw Polygon (default:true) */ + drawPolygon?: boolean; - /** adds button to draw Markers (default:true) */ - drawMarker?: boolean; + /** adds button to draw Circle (default:true) */ + drawCircle?: boolean; - /** adds button to draw CircleMarkers (default:true) */ - drawCircleMarker?: boolean; + /** adds button to toggle edit mode for all layers (default:true) */ + editMode?: boolean; - /** adds button to draw Line (default:true) */ - drawPolyline?: boolean; + /** adds button to toggle drag mode for all layers (default:true) */ + dragMode?: boolean; - /** adds button to draw Rectangle (default:true) */ - drawRectangle?: boolean; + /** adds button to cut a hole in a polygon or line (default:true) */ + cutPolygon?: boolean; - /** adds button to draw Polygon (default:true) */ - drawPolygon?: boolean; + /** adds a button to remove layers (default:true) */ + removalMode?: boolean; - /** adds button to draw Circle (default:true) */ - drawCircle?: boolean; + /** adds a button to rotate layers (default:true) */ + rotateMode?: boolean; - /** adds button to toggle edit mode for all layers (default:true) */ - editMode?: boolean; + /** all buttons will be displayed as one block Customize Controls (default:false) */ + oneBlock?: boolean; - /** adds button to toggle drag mode for all layers (default:true) */ - dragMode?: boolean; + /** shows all draw buttons / buttons in the draw block (default:true) */ + drawControls?: boolean; - /** adds button to cut a hole in a polygon or line (default:true) */ - cutPolygon?: boolean; + /** shows all edit buttons / buttons in the edit block (default:true) */ + editControls?: boolean; - /** adds a button to remove layers (default:true) */ - removalMode?: boolean; + /** shows all buttons in the custom block (default:true) */ + customControls?: boolean; - /** adds a button to rotate layers (default:true) */ - rotateMode?: boolean; + /** shows all options buttons / buttons in the option block ⭐ */ + optionsControls?: boolean; - /** all buttons will be displayed as one block Customize Controls (default:false) */ - oneBlock?: boolean; + /** adds a button to toggle the Pinning Option ⭐ */ + pinningOption?: boolean; - /** shows all draw buttons / buttons in the draw block (default:true) */ - drawControls?: boolean; + /** adds a button to toggle the Snapping Option ⭐ */ + snappingOption?: boolean; + } - /** shows all edit buttons / buttons in the edit block (default:true) */ - editControls?: boolean; + /** the position of each block. */ + interface BlockPositions { + /** draw control position (default:''). '' also refers to this position. */ + draw?: L.ControlPosition; - /** shows all buttons in the custom block (default:true) */ - customControls?: boolean; + /** edit control position (default:''). */ + edit?: L.ControlPosition; - /** shows all options buttons / buttons in the option block ⭐ */ - optionsControls?: boolean; + /** custom control position (default:''). */ + custom?: L.ControlPosition; - /** adds a button to toggle the Pinning Option ⭐ */ - pinningOption?: boolean; + /** options control position (default:'') ⭐ */ + options?: L.ControlPosition; + } - /** adds a button to toggle the Snapping Option ⭐ */ - snappingOption?: boolean; - } + interface PMEditLayer { + /** Enables edit mode. The passed options are preserved, even when the mode is enabled via the Toolbar */ + enable(options?: EditModeOptions): void; - /** the position of each block. */ - interface BlockPositions { - /** draw control position (default:''). '' also refers to this position. */ - draw?: L.ControlPosition; + /** sets layer options */ + setOptions(options?: EditModeOptions): void; - /** edit control position (default:''). */ - edit?: L.ControlPosition; + /** gets layer options */ + getOptions(): EditModeOptions; - /** custom control position (default:''). */ - custom?: L.ControlPosition; + /** Disables edit mode. */ + disable(): void; - /** options control position (default:'') ⭐ */ - options?: L.ControlPosition; - } + /** Toggles edit mode. Passed options are preserved. */ + toggleEdit(options?: EditModeOptions): void; - interface PMEditLayer { - /** Enables edit mode. The passed options are preserved, even when the mode is enabled via the Toolbar */ - enable(options?: EditModeOptions): void; + /** Returns true if edit mode is enabled. false when disabled. */ + enabled(): boolean; - /** sets layer options */ - setOptions(options?: EditModeOptions): void; + /** Returns true if Line or Polygon has a self intersection. */ + hasSelfIntersection(): boolean; - /** gets layer options */ - getOptions(): EditModeOptions; + /** Removes the layer with the same checks as GlobalRemovalMode. */ + remove(): void; + } - /** Disables edit mode. */ - disable(): void; + interface PMDragLayer { + /** enables dragging for the layer. */ + enableLayerDrag(): void; - /** Toggles edit mode. Passed options are preserved. */ - toggleEdit(options?: EditModeOptions): void; + /** disables dragging for the layer. */ + disableLayerDrag(): void; - /** Returns true if edit mode is enabled. false when disabled. */ - enabled(): boolean; + /** returns if the layer is currently dragging. */ + dragging(): boolean; - /** Returns true if Line or Polygon has a self intersection. */ - hasSelfIntersection(): boolean; + /** returns if drag mode is enabled for the layer. */ + layerDragEnabled(): boolean; + } - /** Removes the layer with the same checks as GlobalRemovalMode. */ - remove(): void; - } + interface PMLayer extends PMRotateLayer, PMEditLayer, PMDragLayer { + /** get shape of the layer. */ + getShape(): SUPPORTED_SHAPES; + } - interface PMDragLayer { - /** enables dragging for the layer. */ - enableLayerDrag(): void; + interface PMLayerGroup { + /** Enables edit mode for all child layers. The passed options are preserved, even when the mode is enabled via the Toolbar */ + enable(options?: EditModeOptions): void; - /** disables dragging for the layer. */ - disableLayerDrag(): void; + /** Disable edit mode for all child layers.*/ + disable(): void; - /** returns if the layer is currently dragging. */ - dragging(): boolean; + /** Returns if minimum one layer is enabled. */ + enabled(): boolean; - /** returns if drag mode is enabled for the layer. */ - layerDragEnabled(): boolean; - } + /** Toggle enable / disable on all layers. */ + toggleEdit(options?: EditModeOptions): void; + /** Returns the layers of the LayerGroup. `deep=true` return also the children of LayerGroup children. `filterGeoman=true` filter out layers that don't have Leaflet-Geoman or temporary stuff. `filterGroupsOut=true` does not return the LayerGroup layers self. (Default: `deep=false`,`filterGeoman=true`, `filterGroupsOut=true` ) */ + getLayers( + deep?: boolean, + filterGeoman?: boolean, + filterGroupsOut?: boolean + ): L.Layer[]; - interface PMLayer extends PMRotateLayer, PMEditLayer, PMDragLayer { - /** get shape of the layer. */ - getShape(): SUPPORTED_SHAPES; - } + /** Apply Leaflet-Geoman options to all children. The passed options are preserved, even when the mode is enabled via the Toolbar */ + setOptions(options?: EditModeOptions): void; - interface PMLayerGroup { - /** Enables edit mode for all child layers. The passed options are preserved, even when the mode is enabled via the Toolbar */ - enable(options?: EditModeOptions): void; + /** Returns the options of the LayerGroup. */ + getOptions(): EditModeOptions; - /** Disable edit mode for all child layers.*/ - disable(): void; + /** Returns if currently a layer in the LayerGroup is dragging. */ + dragging(): boolean; + } - /** Returns if minimum one layer is enabled. */ - enabled(): boolean; + namespace Utils { + /** Returns the translation of the passed path. path = json-string f.ex. tooltips.placeMarker */ + function getTranslation(path: string): string; - /** Toggle enable / disable on all layers. */ - toggleEdit(options?: EditModeOptions): void; + /** returns the middle LatLng between two LatLngs */ + function calcMiddleLatLng( + map: L.Map, + latlng1: L.LatLng, + latlng2: L.LatLng + ): L.LatLng; - /** Returns the layers of the LayerGroup. `deep=true` return also the children of LayerGroup children. `filterGeoman=true` filter out layers that don't have Leaflet-Geoman or temporary stuff. `filterGroupsOut=true` does not return the LayerGroup layers self. (Default: `deep=false`,`filterGeoman=true`, `filterGroupsOut=true` ) */ - getLayers(deep?: boolean, filterGeoman?: boolean, filterGroupsOut?: boolean): L.Layer[] + /** returns all layers that are available for Geoman */ + function findLayers(map: L.Map): L.Layer[]; - /** Apply Leaflet-Geoman options to all children. The passed options are preserved, even when the mode is enabled via the Toolbar */ - setOptions(options?: EditModeOptions): void; + /** converts a circle into a polygon with default 60 sides */ + function circleToPolygon(circle: L.Circle, sides?: number): L.Polygon; + } - /** Returns the options of the LayerGroup. */ - getOptions(): EditModeOptions; + /** + * DRAW MODE MAP EVENT HANDLERS + */ - /** Returns if currently a layer in the LayerGroup is dragging. */ - dragging(): boolean; - } + export type GlobalDrawModeToggledEventHandler = (event: { + enabled: boolean; + shape: PM.SUPPORTED_SHAPES; + map: L.Map; + }) => void; + export type DrawStartEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + workingLayer: L.Layer; + }) => void; + export type DrawEndEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type CreateEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + layer: L.Layer; + }) => void; - namespace Utils { - /** Returns the translation of the passed path. path = json-string f.ex. tooltips.placeMarker */ - function getTranslation(path: string): string; + /** + * DRAW MODE LAYER EVENT HANDLERS + */ - /** returns the middle LatLng between two LatLngs */ - function calcMiddleLatLng(map: L.Map, latlng1: L.LatLng, latlng2: L.LatLng): L.LatLng; + export type VertexAddedEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + workingLayer: L.Layer; + marker: L.Marker; + latLng: L.LatLng; + }) => void; + export type SnapEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + distance: number; + layer: L.Layer; + workingLayer: L.Layer; + marker: L.Marker; + layerInteractedWith: L.Layer; + segement: any; + snapLatLng: L.LatLng; + }) => void; + export type CenterPlacedEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + workingLayer: L.Layer; + latLng: L.LatLng; + }) => void; - /** returns all layers that are available for Geoman */ - function findLayers(map: L.Map): L.Layer[]; + /** + * EDIT MODE LAYER EVENT HANDLERS + */ - /** converts a circle into a polygon with default 60 sides */ - function circleToPolygon(circle: L.Circle, sides?: number): L.Polygon - } + export type EditEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + layer: L.Layer; + }) => void; + export type UpdateEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + layer: L.Layer; + }) => void; + export type EnableEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + layer: L.Layer; + }) => void; + export type DisableEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + layer: L.Layer; + }) => void; + export type VertexAddedEventHandler2 = (e: { + layer: L.Layer; + indexPath: number; + latLng: L.LatLng; + marker: L.Marker; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type VertexRemovedEventHandler = (e: { + layer: L.Layer; + indexPath: number; + marker: L.Marker; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type VertexClickEventHandler = (e: { + layer: L.Layer; + indexPath: number; + markerEvent: any; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type MarkerDragStartEventHandler = (e: { + layer: L.Layer; + indexPath: number; + markerEvent: any; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type MarkerDragEventHandler = (e: { + layer: L.Layer; + indexPath: number; + markerEvent: any; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type MarkerDragEndEventHandler = (e: { + layer: L.Layer; + indexPath: number; + markerEvent: any; + shape: PM.SUPPORTED_SHAPES; + intersectionRest: boolean; + }) => void; + export type LayerResetEventHandler = (e: { + layer: L.Layer; + indexPath: number; + markerEvent: any; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type IntersectEventHandler = (e: { + shape: PM.SUPPORTED_SHAPES; + layer: L.Layer; + intersection: L.LatLng; + }) => void; + /** + * EDIT MODE MAP EVENT HANDLERS + */ + export type GlobalEditModeToggledEventHandler = (event: { + enabled: boolean; + map: L.Map; + }) => void; - /** - * DRAW MODE MAP EVENT HANDLERS - */ + /** + * DRAG MODE MAP EVENT HANDLERS + */ + export type GlobalDragModeToggledEventHandler = (event: { + enabled: boolean; + map: L.Map; + }) => void; - export type GlobalDrawModeToggledEventHandler = (event: { enabled: boolean, shape: PM.SUPPORTED_SHAPES, map: L.Map }) => void; - export type DrawStartEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, workingLayer: L.Layer }) => void; - export type DrawEndEventHandler = (e: { shape: PM.SUPPORTED_SHAPES }) => void; - export type CreateEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, layer: L.Layer }) => void; + /** + * DRAG MODE LAYER EVENT HANDLERS + */ + export type DragStartEventHandler = (e: { + layer: L.Layer; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type DragEventHandler = (e: { + layer: L.Layer; + containerPoint: any; + latLng: L.LatLng; + layerPoint: L.Point; + originalEvent: any; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type DragEndEventHandler = (e: { + layer: L.Layer; + shape: PM.SUPPORTED_SHAPES; + }) => void; - /** - * DRAW MODE LAYER EVENT HANDLERS - */ + /** + * REMOVE MODE LAYER EVENT HANDLERS + */ - export type VertexAddedEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, workingLayer: L.Layer, marker: L.Marker, latLng: L.LatLng }) => void; - export type SnapEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, distance: number, layer: L.Layer, workingLayer: L.Layer, marker: L.Marker, layerInteractedWith: L.Layer, segement: any, snapLatLng: L.LatLng }) => void; - export type CenterPlacedEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, workingLayer: L.Layer, latLng: L.LatLng }) => void; + export type RemoveEventHandler = (e: { + layer: L.Layer; + shape: PM.SUPPORTED_SHAPES; + }) => void; - /** - * EDIT MODE LAYER EVENT HANDLERS - */ + /** + * REMOVE MODE MAP EVENT HANDLERS + */ + export type GlobalRemovalModeToggledEventHandler = (e: { + enabled: boolean; + map: L.Map; + }) => void; - export type EditEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, layer: L.Layer }) => void; - export type UpdateEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, layer: L.Layer }) => void; - export type EnableEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, layer: L.Layer }) => void; - export type DisableEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, layer: L.Layer }) => void; - export type VertexAddedEventHandler2 = (e: { layer: L.Layer, indexPath: number, latLng: L.LatLng, marker: L.Marker, shape: PM.SUPPORTED_SHAPES }) => void; - export type VertexRemovedEventHandler = (e: { layer: L.Layer, indexPath: number, marker: L.Marker, shape: PM.SUPPORTED_SHAPES }) => void; - export type VertexClickEventHandler = (e: { layer: L.Layer, indexPath: number, markerEvent: any, shape: PM.SUPPORTED_SHAPES }) => void; - export type MarkerDragStartEventHandler = (e: { layer: L.Layer, indexPath: number, markerEvent: any, shape: PM.SUPPORTED_SHAPES }) => void; - export type MarkerDragEventHandler = (e: { layer: L.Layer, indexPath: number, markerEvent: any, shape: PM.SUPPORTED_SHAPES }) => void; - export type MarkerDragEndEventHandler = (e: { layer: L.Layer, indexPath: number, markerEvent: any, shape: PM.SUPPORTED_SHAPES, intersectionRest: boolean }) => void; - export type LayerResetEventHandler = (e: { layer: L.Layer, indexPath: number, markerEvent: any, shape: PM.SUPPORTED_SHAPES }) => void; - export type IntersectEventHandler = (e: { shape: PM.SUPPORTED_SHAPES, layer: L.Layer, intersection: L.LatLng }) => void; - - /** - * EDIT MODE MAP EVENT HANDLERS - */ - export type GlobalEditModeToggledEventHandler = (event: { enabled: boolean, map: L.Map }) => void; - - /** - * DRAG MODE MAP EVENT HANDLERS - */ - export type GlobalDragModeToggledEventHandler = (event: { enabled: boolean, map: L.Map }) => void; - - /** - * DRAG MODE LAYER EVENT HANDLERS - */ - export type DragStartEventHandler = (e: { layer: L.Layer, shape: PM.SUPPORTED_SHAPES }) => void; - export type DragEventHandler = (e: { layer: L.Layer, containerPoint: any, latLng: L.LatLng, layerPoint: L.Point, originalEvent: any, shape: PM.SUPPORTED_SHAPES }) => void; - export type DragEndEventHandler = (e: { layer: L.Layer, shape: PM.SUPPORTED_SHAPES }) => void; - - /** - * REMOVE MODE LAYER EVENT HANDLERS - */ - - export type RemoveEventHandler = (e: { layer: L.Layer, shape: PM.SUPPORTED_SHAPES }) => void; - - /** - * REMOVE MODE MAP EVENT HANDLERS - */ - export type GlobalRemovalModeToggledEventHandler = (e: { enabled: boolean, map: L.Map }) => void; - - /** - * CUT MODE MAP EVENT HANDLERS - */ - export type GlobalCutModeToggledEventHandler = (e: { layer: L.Layer, originalLayer: L.Layer, shape: PM.SUPPORTED_SHAPES }) => void; - export type CutEventHandler = (e: { layer: L.Layer, originalLayer: L.Layer, shape: PM.SUPPORTED_SHAPES }) => void; - - /** - * ROTATE MODE LAYER EVENT HANDLERS - */ - export type RotateEnableEventHandler = (e: { layer: L.Layer, helpLayer: L.Layer }) => void; - export type RotateDisableEventHandler = (e: { layer: L.Layer }) => void; - export type RotateStartEventHandler = (e: { layer: L.Layer, helpLayer: L.Layer, startAngle: number, originLatLngs: L.LatLng[] }) => void; - export type RotateEventHandler = (e: { layer: L.Layer, helpLayer: L.Layer, startAngle: number, angle: number, angleDiff: number, oldLatLngs: L.LatLng[], newLatLngs: L.LatLng[] }) => void; - export type RotateEndEventHandler = (e: { layer: L.Layer, helpLayer: L.Layer, startAngle: number, angle: number, originLatLngs: L.LatLng[], newLatLngs: L.LatLng[] }) => void; - - - /** - * ROTATE MODE MAP EVENT HANDLERS - */ - export type GlobalRotateModeToggledEventHandler = (e: { enabled: boolean, map: L.Map }) => void; - - /** - * TRANSLATION EVENT HANDLERS - */ - export type LangChangeEventHandler = (e: { activeLang: string, oldLang: string, fallback: string, translations: PM.Translations }) => void; - - /** - * CONTROL MAP EVENT HANDLERS - */ - export type ButtonClickEventHandler = (e: { btnName: string, button: PM.Button }) => void; - export type ActionClickEventHandler = (e: { text: string; action: string; btnName: string; button: PM.Button }) => void; - - /** - * KEYBOARD EVENT HANDLERS - */ - export type KeyboardKeyEventHandler = (e: { focusOn: 'document' | 'map', eventType: 'keydown' | 'keyup', event: any }) => void; + /** + * CUT MODE MAP EVENT HANDLERS + */ + export type GlobalCutModeToggledEventHandler = (e: { + layer: L.Layer; + originalLayer: L.Layer; + shape: PM.SUPPORTED_SHAPES; + }) => void; + export type CutEventHandler = (e: { + layer: L.Layer; + originalLayer: L.Layer; + shape: PM.SUPPORTED_SHAPES; + }) => void; - } -} + /** + * ROTATE MODE LAYER EVENT HANDLERS + */ + export type RotateEnableEventHandler = (e: { + layer: L.Layer; + helpLayer: L.Layer; + }) => void; + export type RotateDisableEventHandler = (e: { layer: L.Layer }) => void; + export type RotateStartEventHandler = (e: { + layer: L.Layer; + helpLayer: L.Layer; + startAngle: number; + originLatLngs: L.LatLng[]; + }) => void; + export type RotateEventHandler = (e: { + layer: L.Layer; + helpLayer: L.Layer; + startAngle: number; + angle: number; + angleDiff: number; + oldLatLngs: L.LatLng[]; + newLatLngs: L.LatLng[]; + }) => void; + export type RotateEndEventHandler = (e: { + layer: L.Layer; + helpLayer: L.Layer; + startAngle: number; + angle: number; + originLatLngs: L.LatLng[]; + newLatLngs: L.LatLng[]; + }) => void; + + /** + * ROTATE MODE MAP EVENT HANDLERS + */ + export type GlobalRotateModeToggledEventHandler = (e: { + enabled: boolean; + map: L.Map; + }) => void; + /** + * TRANSLATION EVENT HANDLERS + */ + export type LangChangeEventHandler = (e: { + activeLang: string; + oldLang: string; + fallback: string; + translations: PM.Translations; + }) => void; + + /** + * CONTROL MAP EVENT HANDLERS + */ + export type ButtonClickEventHandler = (e: { + btnName: string; + button: PM.Button; + }) => void; + export type ActionClickEventHandler = (e: { + text: string; + action: string; + btnName: string; + button: PM.Button; + }) => void; + + /** + * KEYBOARD EVENT HANDLERS + */ + export type KeyboardKeyEventHandler = (e: { + focusOn: 'document' | 'map'; + eventType: 'keydown' | 'keyup'; + event: any; + }) => void; + } +} diff --git a/src/assets/translations/da.json b/src/assets/translations/da.json index b4a469dd..e581e990 100644 --- a/src/assets/translations/da.json +++ b/src/assets/translations/da.json @@ -29,4 +29,4 @@ "snappingButton": "Fastgør trukket markør til andre elementer", "pinningButton": "Sammenlæg delte elementer" } -} \ No newline at end of file +} diff --git a/src/assets/translations/es.json b/src/assets/translations/es.json index e6d04e4b..e6024683 100644 --- a/src/assets/translations/es.json +++ b/src/assets/translations/es.json @@ -1,32 +1,32 @@ { - "tooltips": { - "placeMarker": "Presiona para colocar un marcador", - "firstVertex": "Presiona para colocar el primer vértice", - "continueLine": "Presiona para continuar dibujando", - "finishLine": "Presiona cualquier marcador existente para finalizar", - "finishPoly": "Presiona el primer marcador para finalizar", - "finishRect": "Presiona para finalizar", - "startCircle": "Presiona para colocar el centro del circulo", - "finishCircle": "Presiona para finalizar el circulo", - "placeCircleMarker": "Presiona para colocar un marcador de circulo" - }, - "actions": { - "finish": "Finalizar", - "cancel": "Cancelar", - "removeLastVertex": "Remover ultimo vértice" - }, - "buttonTitles": { - "drawMarkerButton": "Dibujar Marcador", - "drawPolyButton": "Dibujar Polígono", - "drawLineButton": "Dibujar Línea", - "drawCircleButton": "Dibujar Circulo", - "drawRectButton": "Dibujar Rectángulo", - "editButton": "Editar Capas", - "dragButton": "Arrastrar Capas", - "cutButton": "Cortar Capas", - "deleteButton": "Remover Capas", - "drawCircleMarkerButton": "Dibujar Marcador de Circulo", - "snappingButton": "El marcador de Snap arrastrado a otras capas y vértices", - "pinningButton": "Fijar juntos los vértices compartidos" - } + "tooltips": { + "placeMarker": "Presiona para colocar un marcador", + "firstVertex": "Presiona para colocar el primer vértice", + "continueLine": "Presiona para continuar dibujando", + "finishLine": "Presiona cualquier marcador existente para finalizar", + "finishPoly": "Presiona el primer marcador para finalizar", + "finishRect": "Presiona para finalizar", + "startCircle": "Presiona para colocar el centro del circulo", + "finishCircle": "Presiona para finalizar el circulo", + "placeCircleMarker": "Presiona para colocar un marcador de circulo" + }, + "actions": { + "finish": "Finalizar", + "cancel": "Cancelar", + "removeLastVertex": "Remover ultimo vértice" + }, + "buttonTitles": { + "drawMarkerButton": "Dibujar Marcador", + "drawPolyButton": "Dibujar Polígono", + "drawLineButton": "Dibujar Línea", + "drawCircleButton": "Dibujar Circulo", + "drawRectButton": "Dibujar Rectángulo", + "editButton": "Editar Capas", + "dragButton": "Arrastrar Capas", + "cutButton": "Cortar Capas", + "deleteButton": "Remover Capas", + "drawCircleMarkerButton": "Dibujar Marcador de Circulo", + "snappingButton": "El marcador de Snap arrastrado a otras capas y vértices", + "pinningButton": "Fijar juntos los vértices compartidos" + } } diff --git a/src/assets/translations/hu.json b/src/assets/translations/hu.json index 1a1a8a2d..b47a8f60 100644 --- a/src/assets/translations/hu.json +++ b/src/assets/translations/hu.json @@ -29,4 +29,4 @@ "snappingButton": "Kapcsolja a jelöltőt másik elemhez vagy ponthoz", "pinningButton": "Közös pontok összekötése" } -} \ No newline at end of file +} diff --git a/src/assets/translations/index.js b/src/assets/translations/index.js index f9c579d2..422d3711 100644 --- a/src/assets/translations/index.js +++ b/src/assets/translations/index.js @@ -45,5 +45,5 @@ export default { fa, ua, tr, - cz + cz, }; diff --git a/src/assets/translations/pt_br.json b/src/assets/translations/pt_br.json index 5a12666f..790d38e5 100644 --- a/src/assets/translations/pt_br.json +++ b/src/assets/translations/pt_br.json @@ -1,32 +1,32 @@ { - "tooltips": { - "placeMarker": "Clique para posicionar o marcador", - "firstVertex": "Clique para posicionar o primeiro vértice", - "continueLine": "Clique para continuar desenhando", - "finishLine": "Clique em qualquer marcador existente para finalizar", - "finishPoly": "Clique no primeiro ponto para fechar o polígono", - "finishRect": "Clique para finalizar", - "startCircle": "Clique para posicionar o centro do círculo", - "finishCircle": "Clique para fechar o círculo", - "placeCircleMarker": "Clique para posicionar o marcador circular" - }, - "actions": { - "finish": "Finalizar", - "cancel": "Cancelar", - "removeLastVertex": "Remover último vértice" - }, - "buttonTitles": { - "drawMarkerButton": "Desenhar um marcador", - "drawPolyButton": "Desenhar um polígono", - "drawLineButton": "Desenhar uma polilinha", - "drawCircleButton": "Desenhar um círculo", - "drawRectButton": "Desenhar um retângulo", - "editButton": "Editar camada(s)", - "dragButton": "Mover camada(s)", - "cutButton": "Recortar camada(s)", - "deleteButton": "Remover camada(s)", - "drawCircleMarkerButton": "Marcador de círculos de desenho", - "snappingButton": "Marcador arrastado para outras camadas e vértices", - "pinningButton": "Vértices compartilhados de pinos juntos" - } + "tooltips": { + "placeMarker": "Clique para posicionar o marcador", + "firstVertex": "Clique para posicionar o primeiro vértice", + "continueLine": "Clique para continuar desenhando", + "finishLine": "Clique em qualquer marcador existente para finalizar", + "finishPoly": "Clique no primeiro ponto para fechar o polígono", + "finishRect": "Clique para finalizar", + "startCircle": "Clique para posicionar o centro do círculo", + "finishCircle": "Clique para fechar o círculo", + "placeCircleMarker": "Clique para posicionar o marcador circular" + }, + "actions": { + "finish": "Finalizar", + "cancel": "Cancelar", + "removeLastVertex": "Remover último vértice" + }, + "buttonTitles": { + "drawMarkerButton": "Desenhar um marcador", + "drawPolyButton": "Desenhar um polígono", + "drawLineButton": "Desenhar uma polilinha", + "drawCircleButton": "Desenhar um círculo", + "drawRectButton": "Desenhar um retângulo", + "editButton": "Editar camada(s)", + "dragButton": "Mover camada(s)", + "cutButton": "Recortar camada(s)", + "deleteButton": "Remover camada(s)", + "drawCircleMarkerButton": "Marcador de círculos de desenho", + "snappingButton": "Marcador arrastado para outras camadas e vértices", + "pinningButton": "Vértices compartilhados de pinos juntos" } +} diff --git a/src/css/controls.css b/src/css/controls.css index d7dc19d3..2e976523 100644 --- a/src/css/controls.css +++ b/src/css/controls.css @@ -1,5 +1,4 @@ .leaflet-pm-toolbar { - } .leaflet-pm-toolbar .leaflet-buttons-control-button { @@ -9,8 +8,12 @@ z-index: 3; } -.leaflet-pm-toolbar .leaflet-pm-actions-container a.leaflet-pm-action:first-child:not(.pos-right), -.leaflet-pm-toolbar .leaflet-pm-actions-container a.leaflet-pm-action:last-child.pos-right { +.leaflet-pm-toolbar + .leaflet-pm-actions-container + a.leaflet-pm-action:first-child:not(.pos-right), +.leaflet-pm-toolbar + .leaflet-pm-actions-container + a.leaflet-pm-action:last-child.pos-right { border-radius: 0; } @@ -18,15 +21,21 @@ border-radius: 0; } -.leaflet-pm-toolbar .button-container:last-child a.leaflet-buttons-control-button { +.leaflet-pm-toolbar + .button-container:last-child + a.leaflet-buttons-control-button { border-radius: 0 0 2px 2px; } -.leaflet-pm-toolbar .button-container:first-child a.leaflet-buttons-control-button { +.leaflet-pm-toolbar + .button-container:first-child + a.leaflet-buttons-control-button { border-radius: 2px 2px 0 0; } -.leaflet-pm-toolbar .button-container:last-child a.leaflet-buttons-control-button { +.leaflet-pm-toolbar + .button-container:last-child + a.leaflet-buttons-control-button { border-bottom: none; } @@ -81,7 +90,8 @@ background-image: url('../assets/icons/Rotate.svg'); } -.leaflet-buttons-control-button:hover,.leaflet-buttons-control-button:focus { +.leaflet-buttons-control-button:hover, +.leaflet-buttons-control-button:focus { cursor: pointer; background-color: #f4f4f4; } @@ -107,7 +117,10 @@ direction: ltr; } -.leaflet-right .leaflet-pm-toolbar .button-container .leaflet-pm-actions-container { +.leaflet-right + .leaflet-pm-toolbar + .button-container + .leaflet-pm-actions-container { right: 100%; left: auto; } @@ -116,14 +129,20 @@ display: block; } -.button-container .leaflet-pm-actions-container:not(.pos-right) a.leaflet-pm-action:last-child { +.button-container + .leaflet-pm-actions-container:not(.pos-right) + a.leaflet-pm-action:last-child { border-radius: 0 3px 3px 0; border-right: 0; } -.button-container .leaflet-pm-actions-container.pos-right a.leaflet-pm-action:first-child { +.button-container + .leaflet-pm-actions-container.pos-right + a.leaflet-pm-action:first-child { border-radius: 3px 0 0 3px; } -.button-container .leaflet-pm-actions-container.pos-right a.leaflet-pm-action:last-child { +.button-container + .leaflet-pm-actions-container.pos-right + a.leaflet-pm-action:last-child { border-right: 0; } .button-container .leaflet-pm-actions-container .leaflet-pm-action { @@ -138,27 +157,32 @@ height: 29px; line-height: 29px; } -.leaflet-pm-toolbar .button-container:first-child.pos-right.active a.leaflet-buttons-control-button { +.leaflet-pm-toolbar + .button-container:first-child.pos-right.active + a.leaflet-buttons-control-button { border-top-left-radius: 0; } -.leaflet-pm-toolbar .button-container:first-child.active:not(.pos-right) a.leaflet-buttons-control-button { +.leaflet-pm-toolbar + .button-container:first-child.active:not(.pos-right) + a.leaflet-buttons-control-button { border-top-right-radius: 0; } -.button-container .leaflet-pm-actions-container .leaflet-pm-action:hover, .button-container .leaflet-pm-actions-container .leaflet-pm-action:focus { +.button-container .leaflet-pm-actions-container .leaflet-pm-action:hover, +.button-container .leaflet-pm-actions-container .leaflet-pm-action:focus { cursor: pointer; background-color: #777; } /* That the active control is always over the other controls */ -.leaflet-pm-toolbar.activeChild{ +.leaflet-pm-toolbar.activeChild { z-index: 801; } -.leaflet-buttons-control-button.pm-disabled{ +.leaflet-buttons-control-button.pm-disabled { background-color: #f4f4f4; } -.control-icon.pm-disabled{ +.control-icon.pm-disabled { filter: opacity(0.6); } diff --git a/src/css/layers.css b/src/css/layers.css index 03875d67..577ac184 100644 --- a/src/css/layers.css +++ b/src/css/layers.css @@ -51,6 +51,6 @@ display: none; } -.vertexmarker-disabled{ +.vertexmarker-disabled { opacity: 0.7; } diff --git a/src/js/Draw/L.PM.Draw.Circle.js b/src/js/Draw/L.PM.Draw.Circle.js index fe729b08..7f22dae0 100644 --- a/src/js/Draw/L.PM.Draw.Circle.js +++ b/src/js/Draw/L.PM.Draw.Circle.js @@ -1,6 +1,6 @@ import Draw from './L.PM.Draw'; -import {destinationOnLine, getTranslation} from '../helpers'; +import { destinationOnLine, getTranslation } from '../helpers'; Draw.Circle = Draw.extend({ initialize(map) { @@ -24,7 +24,7 @@ Draw.Circle = Draw.extend({ // this is the circle we want to draw this._layer = L.circle([0, 0], this.options.templineStyle); - this._setPane(this._layer,'layerPane'); + this._setPane(this._layer, 'layerPane'); this._layer._pmTempLayer = true; this._layerGroup.addLayer(this._layer); @@ -34,7 +34,7 @@ Draw.Circle = Draw.extend({ draggable: false, zIndexOffset: 100, }); - this._setPane(this._centerMarker,'vertexPane'); + this._setPane(this._centerMarker, 'vertexPane'); this._centerMarker._pmTempLayer = true; this._layerGroup.addLayer(this._centerMarker); @@ -43,7 +43,7 @@ Draw.Circle = Draw.extend({ zIndexOffset: 110, icon: L.divIcon({ className: 'marker-icon cursor-marker' }), }); - this._setPane(this._hintMarker,'vertexPane'); + this._setPane(this._hintMarker, 'vertexPane'); this._hintMarker._pmTempLayer = true; this._layerGroup.addLayer(this._hintMarker); @@ -66,7 +66,7 @@ Draw.Circle = Draw.extend({ // this is the hintline from the hint marker to the center marker this._hintline = L.polyline([], this.options.hintlineStyle); - this._setPane(this._hintline,'layerPane'); + this._setPane(this._hintline, 'layerPane'); this._hintline._pmTempLayer = true; this._layerGroup.addLayer(this._hintline); @@ -79,7 +79,6 @@ Draw.Circle = Draw.extend({ // sync hint marker with mouse cursor this._map.on('mousemove', this._syncHintMarker, this); - // toggle the draw button of the Toolbar in case drawing mode got enabled without the button this._map.pm.Toolbar.toggleButton(this.toolbarButtonName, true); @@ -112,7 +111,6 @@ Draw.Circle = Draw.extend({ // remove helping layers this._map.removeLayer(this._layerGroup); - // toggle the draw button of the Toolbar in case drawing mode got disabled without the button this._map.pm.Toolbar.toggleButton(this.toolbarButtonName, false); @@ -153,11 +151,17 @@ Draw.Circle = Draw.extend({ distance = A.distanceTo(B); } - if(this.options.minRadiusCircle && distance < this.options.minRadiusCircle) { + if ( + this.options.minRadiusCircle && + distance < this.options.minRadiusCircle + ) { this._layer.setRadius(this.options.minRadiusCircle); - }else if(this.options.maxRadiusCircle && distance > this.options.maxRadiusCircle) { + } else if ( + this.options.maxRadiusCircle && + distance > this.options.maxRadiusCircle + ) { this._layer.setRadius(this.options.maxRadiusCircle); - }else{ + } else { this._layer.setRadius(distance); } }, @@ -212,7 +216,11 @@ Draw.Circle = Draw.extend({ }, _finishShape(e) { // If snap finish is required but the last marker wasn't snapped, do not finish the shape! - if (this.options.requireSnapToFinish && !this._hintMarker._snapped && !this._isFirstLayer()) { + if ( + this.options.requireSnapToFinish && + !this._hintMarker._snapped && + !this._isFirstLayer() + ) { return; } @@ -234,21 +242,24 @@ Draw.Circle = Draw.extend({ radius = center.distanceTo(latlng); } - if(this.options.minRadiusCircle && radius < this.options.minRadiusCircle){ + if (this.options.minRadiusCircle && radius < this.options.minRadiusCircle) { radius = this.options.minRadiusCircle; - }else if(this.options.maxRadiusCircle && radius > this.options.maxRadiusCircle){ + } else if ( + this.options.maxRadiusCircle && + radius > this.options.maxRadiusCircle + ) { radius = this.options.maxRadiusCircle; } - const options = Object.assign({}, this.options.pathOptions, { radius }); + const options = { ...this.options.pathOptions, radius }; // create the final circle layer const circleLayer = L.circle(center, options); - this._setPane(circleLayer,'layerPane'); + this._setPane(circleLayer, 'layerPane'); this._finishLayer(circleLayer); circleLayer.addTo(this._map.pm._getContainingLayer()); - if(circleLayer.pm) { + if (circleLayer.pm) { // create polygon around the circle border circleLayer.pm._updateHiddenPolyCircle(); } @@ -258,34 +269,56 @@ Draw.Circle = Draw.extend({ // disable drawing this.disable(); - if(this.options.continueDrawing){ + if (this.options.continueDrawing) { this.enable(); } }, - _getNewDestinationOfHintMarker(){ + _getNewDestinationOfHintMarker() { const latlng = this._centerMarker.getLatLng(); let secondLatLng = this._hintMarker.getLatLng(); const distance = latlng.distanceTo(secondLatLng); - if(this.options.minRadiusCircle && distance < this.options.minRadiusCircle) { - secondLatLng = destinationOnLine(this._map,latlng,secondLatLng,this.options.minRadiusCircle); - }else if(this.options.maxRadiusCircle && distance > this.options.maxRadiusCircle) { - secondLatLng = destinationOnLine(this._map,latlng,secondLatLng,this.options.maxRadiusCircle); + if ( + this.options.minRadiusCircle && + distance < this.options.minRadiusCircle + ) { + secondLatLng = destinationOnLine( + this._map, + latlng, + secondLatLng, + this.options.minRadiusCircle + ); + } else if ( + this.options.maxRadiusCircle && + distance > this.options.maxRadiusCircle + ) { + secondLatLng = destinationOnLine( + this._map, + latlng, + secondLatLng, + this.options.maxRadiusCircle + ); } return secondLatLng; }, - _handleHintMarkerSnapping(){ - if(this._hintMarker._snapped) { + _handleHintMarkerSnapping() { + if (this._hintMarker._snapped) { const latlng = this._centerMarker.getLatLng(); const secondLatLng = this._hintMarker.getLatLng(); const distance = latlng.distanceTo(secondLatLng); - if(this.options.minRadiusCircle && distance < this.options.minRadiusCircle) { + if ( + this.options.minRadiusCircle && + distance < this.options.minRadiusCircle + ) { this._hintMarker.setLatLng(this._hintMarker._orgLatLng); - } else if(this.options.maxRadiusCircle && distance > this.options.maxRadiusCircle) { + } else if ( + this.options.maxRadiusCircle && + distance > this.options.maxRadiusCircle + ) { this._hintMarker.setLatLng(this._hintMarker._orgLatLng); } } // calculate the new latlng of marker if the snapped latlng radius is out of min/max this._hintMarker.setLatLng(this._getNewDestinationOfHintMarker()); - } + }, }); diff --git a/src/js/Draw/L.PM.Draw.CircleMarker.js b/src/js/Draw/L.PM.Draw.CircleMarker.js index eb1ecfc1..abfafd75 100644 --- a/src/js/Draw/L.PM.Draw.CircleMarker.js +++ b/src/js/Draw/L.PM.Draw.CircleMarker.js @@ -1,5 +1,5 @@ import Draw from './L.PM.Draw'; -import {destinationOnLine, getTranslation } from '../helpers'; +import { destinationOnLine, getTranslation } from '../helpers'; Draw.CircleMarker = Draw.Marker.extend({ initialize(map) { @@ -17,7 +17,6 @@ Draw.CircleMarker = Draw.Marker.extend({ // change enabled state this._enabled = true; - // toggle the draw button of the Toolbar in case drawing mode got enabled without the button this._map.pm.Toolbar.toggleButton(this.toolbarButtonName, true); @@ -30,7 +29,7 @@ Draw.CircleMarker = Draw.Marker.extend({ // this is the circle we want to draw this._layer = L.circleMarker([0, 0], this.options.templineStyle); - this._setPane(this._layer,'layerPane'); + this._setPane(this._layer, 'layerPane'); this._layer._pmTempLayer = true; this._layerGroup.addLayer(this._layer); @@ -40,7 +39,7 @@ Draw.CircleMarker = Draw.Marker.extend({ draggable: false, zIndexOffset: 100, }); - this._setPane(this._centerMarker,'vertexPane'); + this._setPane(this._centerMarker, 'vertexPane'); this._centerMarker._pmTempLayer = true; this._layerGroup.addLayer(this._centerMarker); @@ -49,7 +48,7 @@ Draw.CircleMarker = Draw.Marker.extend({ zIndexOffset: 110, icon: L.divIcon({ className: 'marker-icon cursor-marker' }), }); - this._setPane(this._hintMarker,'vertexPane'); + this._setPane(this._hintMarker, 'vertexPane'); this._hintMarker._pmTempLayer = true; this._layerGroup.addLayer(this._hintMarker); @@ -73,7 +72,7 @@ Draw.CircleMarker = Draw.Marker.extend({ // this is the hintline from the hint marker to the center marker this._hintline = L.polyline([], this.options.hintlineStyle); - this._setPane(this._hintline,'layerPane'); + this._setPane(this._hintline, 'layerPane'); this._hintline._pmTempLayer = true; this._layerGroup.addLayer(this._hintline); // create a polygon-point on click @@ -86,7 +85,7 @@ Draw.CircleMarker = Draw.Marker.extend({ // this is the hintmarker on the mouse cursor this._hintMarker = L.circleMarker([0, 0], this.options.templineStyle); - this._setPane(this._hintMarker,'layerPane'); + this._setPane(this._hintMarker, 'layerPane'); this._hintMarker._pmTempLayer = true; this._hintMarker.addTo(this._map); // this is just to keep the snappable mixin happy @@ -111,7 +110,7 @@ Draw.CircleMarker = Draw.Marker.extend({ if (!this.options.editable && this.options.markerEditable) { // enable edit mode for existing markers - this._map.eachLayer(layer => { + this._map.eachLayer((layer) => { if (this.isRelevantMarker(layer)) { layer.pm.enable(); } @@ -148,7 +147,7 @@ Draw.CircleMarker = Draw.Marker.extend({ this._map.off('click', this._createMarker, this); // disable dragging and removing for all markers - this._map.eachLayer(layer => { + this._map.eachLayer((layer) => { if (this.isRelevantMarker(layer)) { layer.pm.disable(); } @@ -219,11 +218,17 @@ Draw.CircleMarker = Draw.Marker.extend({ const distance = this._map.project(A).distanceTo(this._map.project(B)); - if(this.options.minRadiusCircleMarker && distance < this.options.minRadiusCircleMarker) { + if ( + this.options.minRadiusCircleMarker && + distance < this.options.minRadiusCircleMarker + ) { this._layer.setRadius(this.options.minRadiusCircleMarker); - }else if(this.options.maxRadiusCircleMarker && distance > this.options.maxRadiusCircleMarker) { + } else if ( + this.options.maxRadiusCircleMarker && + distance > this.options.maxRadiusCircleMarker + ) { this._layer.setRadius(this.options.maxRadiusCircleMarker); - }else{ + } else { this._layer.setRadius(distance); } }, @@ -243,11 +248,20 @@ Draw.CircleMarker = Draw.Marker.extend({ this._handleHintMarkerSnapping(); }, isRelevantMarker(layer) { - return layer instanceof L.CircleMarker && !(layer instanceof L.Circle) && layer.pm && !layer._pmTempLayer; + return ( + layer instanceof L.CircleMarker && + !(layer instanceof L.Circle) && + layer.pm && + !layer._pmTempLayer + ); }, _createMarker(e) { // If snap finish is required but the last marker wasn't snapped, do not finish the shape! - if (this.options.requireSnapToFinish && !this._hintMarker._snapped && !this._isFirstLayer()) { + if ( + this.options.requireSnapToFinish && + !this._hintMarker._snapped && + !this._isFirstLayer() + ) { return; } @@ -267,12 +281,12 @@ Draw.CircleMarker = Draw.Marker.extend({ // create marker const marker = L.circleMarker(latlng, this.options.pathOptions); - this._setPane(marker,'layerPane'); + this._setPane(marker, 'layerPane'); this._finishLayer(marker); // add marker to the map marker.addTo(this._map.pm._getContainingLayer()); - if(marker.pm && this.options.markerEditable) { + if (marker.pm && this.options.markerEditable) { // enable editing for the marker marker.pm.enable(); } @@ -282,14 +296,17 @@ Draw.CircleMarker = Draw.Marker.extend({ this._cleanupSnapping(); - if(!this.options.continueDrawing){ + if (!this.options.continueDrawing) { this.disable(); } }, _finishShape(e) { - // If snap finish is required but the last marker wasn't snapped, do not finish the shape! - if (this.options.requireSnapToFinish && !this._hintMarker._snapped && !this._isFirstLayer()) { + if ( + this.options.requireSnapToFinish && + !this._hintMarker._snapped && + !this._isFirstLayer() + ) { return; } @@ -302,26 +319,33 @@ Draw.CircleMarker = Draw.Marker.extend({ // calc the radius const center = this._centerMarker.getLatLng(); const latlng = this._hintMarker.getLatLng(); - let radius = this._map.project(center).distanceTo(this._map.project(latlng)); - + let radius = this._map + .project(center) + .distanceTo(this._map.project(latlng)); - if(this.options.editable) { - if (this.options.minRadiusCircleMarker && radius < this.options.minRadiusCircleMarker) { + if (this.options.editable) { + if ( + this.options.minRadiusCircleMarker && + radius < this.options.minRadiusCircleMarker + ) { radius = this.options.minRadiusCircleMarker; - } else if (this.options.maxRadiusCircleMarker && radius > this.options.maxRadiusCircleMarker) { + } else if ( + this.options.maxRadiusCircleMarker && + radius > this.options.maxRadiusCircleMarker + ) { radius = this.options.maxRadiusCircleMarker; } } - const options = Object.assign({}, this.options.pathOptions, { radius }); + const options = { ...this.options.pathOptions, radius }; // create the final circle layer const circleLayer = L.circleMarker(center, options); - this._setPane(circleLayer,'layerPane'); + this._setPane(circleLayer, 'layerPane'); this._finishLayer(circleLayer); circleLayer.addTo(this._map.pm._getContainingLayer()); - if(circleLayer.pm) { + if (circleLayer.pm) { // create polygon around the circle border circleLayer.pm._updateHiddenPolyCircle(); } @@ -331,32 +355,58 @@ Draw.CircleMarker = Draw.Marker.extend({ // disable drawing this.disable(); - if(this.options.continueDrawing){ + if (this.options.continueDrawing) { this.enable(); } }, - _getNewDestinationOfHintMarker(){ + _getNewDestinationOfHintMarker() { let secondLatLng = this._hintMarker.getLatLng(); - if(this.options.editable) { + if (this.options.editable) { const latlng = this._centerMarker.getLatLng(); - const distance = this._map.project(latlng).distanceTo(this._map.project(secondLatLng)); - if (this.options.minRadiusCircleMarker && distance < this.options.minRadiusCircleMarker) { - secondLatLng = destinationOnLine(this._map, latlng, secondLatLng, this._pxRadiusToMeter(this.options.minRadiusCircleMarker)); - } else if (this.options.maxRadiusCircleMarker && distance > this.options.maxRadiusCircleMarker) { - secondLatLng = destinationOnLine(this._map, latlng, secondLatLng, this._pxRadiusToMeter(this.options.maxRadiusCircleMarker)); + const distance = this._map + .project(latlng) + .distanceTo(this._map.project(secondLatLng)); + if ( + this.options.minRadiusCircleMarker && + distance < this.options.minRadiusCircleMarker + ) { + secondLatLng = destinationOnLine( + this._map, + latlng, + secondLatLng, + this._pxRadiusToMeter(this.options.minRadiusCircleMarker) + ); + } else if ( + this.options.maxRadiusCircleMarker && + distance > this.options.maxRadiusCircleMarker + ) { + secondLatLng = destinationOnLine( + this._map, + latlng, + secondLatLng, + this._pxRadiusToMeter(this.options.maxRadiusCircleMarker) + ); } } return secondLatLng; }, - _handleHintMarkerSnapping(){ - if(this.options.editable) { + _handleHintMarkerSnapping() { + if (this.options.editable) { if (this._hintMarker._snapped) { const latlng = this._centerMarker.getLatLng(); const secondLatLng = this._hintMarker.getLatLng(); - const distance = this._map.project(latlng).distanceTo(this._map.project(secondLatLng)); - if (this.options.minRadiusCircleMarker && distance < this.options.minRadiusCircleMarker) { + const distance = this._map + .project(latlng) + .distanceTo(this._map.project(secondLatLng)); + if ( + this.options.minRadiusCircleMarker && + distance < this.options.minRadiusCircleMarker + ) { this._hintMarker.setLatLng(this._hintMarker._orgLatLng); - } else if (this.options.maxRadiusCircleMarker && distance > this.options.maxRadiusCircleMarker) { + } else if ( + this.options.maxRadiusCircleMarker && + distance > this.options.maxRadiusCircleMarker + ) { this._hintMarker.setLatLng(this._hintMarker._orgLatLng); } } @@ -364,10 +414,10 @@ Draw.CircleMarker = Draw.Marker.extend({ this._hintMarker.setLatLng(this._getNewDestinationOfHintMarker()); } }, - _pxRadiusToMeter(radius){ + _pxRadiusToMeter(radius) { const center = this._centerMarker.getLatLng(); const pointA = this._map.project(center); const pointB = L.point(pointA.x + radius, pointA.y); return this._map.unproject(pointB).distanceTo(center); - } + }, }); diff --git a/src/js/Draw/L.PM.Draw.Cut.js b/src/js/Draw/L.PM.Draw.Cut.js index f284718c..9ba709bd 100644 --- a/src/js/Draw/L.PM.Draw.Cut.js +++ b/src/js/Draw/L.PM.Draw.Cut.js @@ -1,9 +1,14 @@ -import lineIntersect from "@turf/line-intersect"; -import lineSplit from "@turf/line-split"; -import booleanContains from "@turf/boolean-contains"; -import get from "lodash/get"; +import lineIntersect from '@turf/line-intersect'; +import lineSplit from '@turf/line-split'; +import booleanContains from '@turf/boolean-contains'; +import get from 'lodash/get'; import Draw from './L.PM.Draw'; -import {difference, flattenPolyline, groupToMultiLineString, intersect} from "../helpers/turfHelper"; +import { + difference, + flattenPolyline, + groupToMultiLineString, + intersect, +} from '../helpers/turfHelper'; Draw.Cut = Draw.Polygon.extend({ initialize(map) { @@ -36,12 +41,12 @@ Draw.Cut = Draw.Polygon.extend({ this._otherSnapLayers.splice(this._tempSnapLayerIndex, 1); delete this._tempSnapLayerIndex; - this._editedLayers.forEach(({layer, originalLayer}) =>{ + this._editedLayers.forEach(({ layer, originalLayer }) => { // fire pm:cut on the cutted layer - this._fireCut(originalLayer,layer,originalLayer); + this._fireCut(originalLayer, layer, originalLayer); // fire pm:cut on the map - this._fireCut(this._map,layer,originalLayer); + this._fireCut(this._map, layer, originalLayer); // fire edit event after cut originalLayer.pm._fireEdit(); @@ -50,7 +55,7 @@ Draw.Cut = Draw.Polygon.extend({ // disable drawing this.disable(); - if(this.options.continueDrawing){ + if (this.options.continueDrawing) { this.enable(); } }, @@ -61,92 +66,112 @@ Draw.Cut = Draw.Polygon.extend({ // find all layers that intersect with `layer`, the just drawn cutting layer const layers = Object.keys(all) - // convert object to array - .map(l => all[l]) + // convert object to array + .map((l) => all[l]) // only layers handled by leaflet-geoman - .filter(l => l.pm) - .filter(l => !l._pmTempLayer) + .filter((l) => l.pm) + .filter((l) => !l._pmTempLayer) // filter out everything that ignore leaflet-geoman - .filter(l => ( + .filter( + (l) => (!L.PM.optIn && !l.options.pmIgnore) || // if optIn is not set / true and pmIgnore is not set / true (default) (L.PM.optIn && l.options.pmIgnore === false) // if optIn is true and pmIgnore is false); - ) ) // only polyline instances - .filter(l => l instanceof L.Polyline) + .filter((l) => l instanceof L.Polyline) // exclude the drawn one - .filter(l => l !== layer) + .filter((l) => l !== layer) // layer is allowed to cut - .filter(l => l.pm.options.allowCutting) + .filter((l) => l.pm.options.allowCutting) // filter out everything that ignore leaflet-geoman - .filter(l =>{ + .filter((l) => { // TODO: after cutting nothing else can be cutted anymore until a new list is passed, because the layers don't exists anymore. Should we remove the cutted layers from the list? - if(this.options.layersToCut && L.Util.isArray(this.options.layersToCut) && this.options.layersToCut.length > 0){ + if ( + this.options.layersToCut && + L.Util.isArray(this.options.layersToCut) && + this.options.layersToCut.length > 0 + ) { return this.options.layersToCut.indexOf(l) > -1; - }else{ - return true; } + return true; }) // filter out everything that ignore leaflet-geoman - .filter(l => !this._layerGroup.hasLayer(l)) + .filter((l) => !this._layerGroup.hasLayer(l)) // only layers with intersections - .filter(l => { + .filter((l) => { try { - const lineInter = !!lineIntersect(layer.toGeoJSON(15), l.toGeoJSON(15)).features.length > 0; + const lineInter = + !!lineIntersect(layer.toGeoJSON(15), l.toGeoJSON(15)).features + .length > 0; - if(lineInter || (l instanceof L.Polyline && !(l instanceof L.Polygon))){ + if ( + lineInter || + (l instanceof L.Polyline && !(l instanceof L.Polygon)) + ) { return lineInter; } return !!intersect(layer.toGeoJSON(15), l.toGeoJSON(15)); - } catch (e) { if (l instanceof L.Polygon) { /* eslint-disable-next-line no-console */ - console.error('You can\'t cut polygons with self-intersections'); + console.error("You can't cut polygons with self-intersections"); } return false; } }); // loop through all layers that intersect with the drawn (cutting) layer - layers.forEach(l => { + layers.forEach((l) => { let newLayer; - if(l instanceof L.Polygon) { // Also for L.Rectangle + if (l instanceof L.Polygon) { + // Also for L.Rectangle // easiest way to clone the complete latlngs without reference newLayer = L.polygon(l.getLatLngs()); const coords = newLayer.getLatLngs(); // snapping points added to the layer, so borders are cutted correct - _latlngInfos.forEach((info)=>{ - if(info && info.snapInfo) { - const {latlng} = info; + _latlngInfos.forEach((info) => { + if (info && info.snapInfo) { + const { latlng } = info; // get closest layer ( == input layer) with the closest segment to the intersection point const closest = this._calcClosestLayer(latlng, [newLayer]); - if (closest && closest.segment && closest.distance < this.options.snapDistance) { - const {segment} = closest; + if ( + closest && + closest.segment && + closest.distance < this.options.snapDistance + ) { + const { segment } = closest; if (segment && segment.length === 2) { - const {indexPath, parentPath, newIndex} = L.PM.Utils._getIndexFromSegment(coords, segment); + const { + indexPath, + parentPath, + newIndex, + } = L.PM.Utils._getIndexFromSegment(coords, segment); // define the coordsRing that is edited - const coordsRing = indexPath.length > 1 ? get(coords, parentPath) : coords; + const coordsRing = + indexPath.length > 1 ? get(coords, parentPath) : coords; coordsRing.splice(newIndex, 0, latlng); } } } }); - }else{ // L.Polyline + } else { + // L.Polyline newLayer = l; } // find layer difference - const diff = this._cutLayer(layer,newLayer); + const diff = this._cutLayer(layer, newLayer); // the resulting layer after the cut let resultLayer = L.geoJSON(diff, l.options); if (resultLayer.getLayers().length === 1) { [resultLayer] = resultLayer.getLayers(); // prevent that a unnecessary layergroup is created } - this._setPane(resultLayer,'layerPane'); - const resultingLayer = resultLayer.addTo(this._map.pm._getContainingLayer()); + this._setPane(resultLayer, 'layerPane'); + const resultingLayer = resultLayer.addTo( + this._map.pm._getContainingLayer() + ); // give the new layer the original options resultingLayer.pm.enable(l.pm.options); resultingLayer.pm.disable(); @@ -166,29 +191,33 @@ Draw.Cut = Draw.Polygon.extend({ this._map.pm.removeLayer({ target: resultingLayer }); } - if(resultingLayer instanceof L.LayerGroup) { - resultingLayer.eachLayer((_layer)=>{ + if (resultingLayer instanceof L.LayerGroup) { + resultingLayer.eachLayer((_layer) => { this._addDrawnLayerProp(_layer); }); this._addDrawnLayerProp(resultingLayer); - }else{ + } else { this._addDrawnLayerProp(resultingLayer); } - if(this.options.layersToCut && L.Util.isArray(this.options.layersToCut) && this.options.layersToCut.length > 0){ + if ( + this.options.layersToCut && + L.Util.isArray(this.options.layersToCut) && + this.options.layersToCut.length > 0 + ) { const idx = this.options.layersToCut.indexOf(l); - if( idx > -1){ + if (idx > -1) { this.options.layersToCut.splice(idx, 1); } } this._editedLayers.push({ layer: resultingLayer, - originalLayer: l + originalLayer: l, }); }); }, - _cutLayer(layer,l){ + _cutLayer(layer, l) { const fg = L.geoJSON(); let diff; // cut @@ -198,14 +227,14 @@ Draw.Cut = Draw.Polygon.extend({ } else { const features = flattenPolyline(l); - features.forEach((feature)=>{ + features.forEach((feature) => { // get splitted line to look which line part is coverd by the cut polygon const lineDiff = lineSplit(feature, layer.toGeoJSON(15)); let group; if (lineDiff && lineDiff.features.length > 0) { group = L.geoJSON(lineDiff); - }else{ + } else { group = L.geoJSON(feature); } @@ -217,9 +246,9 @@ Draw.Cut = Draw.Polygon.extend({ }); }); - if(features.length > 1){ + if (features.length > 1) { diff = groupToMultiLineString(fg); - }else{ + } else { diff = fg.toGeoJSON(15); } } diff --git a/src/js/Draw/L.PM.Draw.Line.js b/src/js/Draw/L.PM.Draw.Line.js index 95f17d70..fadd0511 100644 --- a/src/js/Draw/L.PM.Draw.Line.js +++ b/src/js/Draw/L.PM.Draw.Line.js @@ -23,23 +23,23 @@ Draw.Line = Draw.extend({ // this is the polyLine that'll make up the polygon this._layer = L.polyline([], this.options.templineStyle); - this._setPane(this._layer,'layerPane'); + this._setPane(this._layer, 'layerPane'); this._layer._pmTempLayer = true; this._layerGroup.addLayer(this._layer); // this is the hintline from the mouse cursor to the last marker this._hintline = L.polyline([], this.options.hintlineStyle); - this._setPane(this._hintline,'layerPane'); + this._setPane(this._hintline, 'layerPane'); this._hintline._pmTempLayer = true; this._layerGroup.addLayer(this._hintline); // this is the hintmarker on the mouse cursor - this._hintMarker = L.marker(this._map.getCenter(),{ + this._hintMarker = L.marker(this._map.getCenter(), { interactive: false, // always vertex marker below will be triggered from the click event -> _finishShape #911 zIndexOffset: 100, icon: L.divIcon({ className: 'marker-icon cursor-marker' }), }); - this._setPane(this._hintMarker,'vertexPane'); + this._setPane(this._hintMarker, 'vertexPane'); this._hintMarker._pmTempLayer = true; this._layerGroup.addLayer(this._hintMarker); @@ -95,7 +95,6 @@ Draw.Line = Draw.extend({ // TODO: think about moving this somewhere else? this._otherSnapLayers = []; - // fire drawstart event this._fireDrawStart(); this._setGlobalDrawMode(); @@ -138,7 +137,6 @@ Draw.Line = Draw.extend({ // fire drawend event this._fireDrawEnd(); this._setGlobalDrawMode(); - }, enabled() { return this._enabled; @@ -250,7 +248,7 @@ Draw.Line = Draw.extend({ this._layer._latlngInfo = this._layer._latlngInfo || []; this._layer._latlngInfo.push({ latlng, - snapInfo: this._hintMarker._snapInfo + snapInfo: this._hintMarker._snapInfo, }); this._layer.addLatLng(latlng); @@ -259,7 +257,7 @@ Draw.Line = Draw.extend({ this._hintline.setLatLngs([latlng, latlng]); - this._fireVertexAdded(newMarker, undefined, latlng, "Draw"); + this._fireVertexAdded(newMarker, undefined, latlng, 'Draw'); // check if we should finish on snap if (this.options.finishOn === 'snap' && this._hintMarker._snapped) { @@ -280,9 +278,9 @@ Draw.Line = Draw.extend({ // find corresponding marker const marker = this._layerGroup .getLayers() - .filter(l => l instanceof L.Marker) - .filter(l => !L.DomUtil.hasClass(l._icon, 'cursor-marker')) - .find(l => l.getLatLng() === removedCoord); + .filter((l) => l instanceof L.Marker) + .filter((l) => !L.DomUtil.hasClass(l._icon, 'cursor-marker')) + .find((l) => l.getLatLng() === removedCoord); // remove that marker this._layerGroup.removeLayer(marker); @@ -305,7 +303,11 @@ Draw.Line = Draw.extend({ } // If snap finish is required but the last marker wasn't snapped, do not finish the shape! - if (this.options.requireSnapToFinish && !this._hintMarker._snapped && !this._isFirstLayer()) { + if ( + this.options.requireSnapToFinish && + !this._hintMarker._snapped && + !this._isFirstLayer() + ) { return; } @@ -319,7 +321,7 @@ Draw.Line = Draw.extend({ // create the leaflet shape and add it to the map const polylineLayer = L.polyline(coords, this.options.pathOptions); - this._setPane(polylineLayer,'layerPane'); + this._setPane(polylineLayer, 'layerPane'); this._finishLayer(polylineLayer); polylineLayer.addTo(this._map.pm._getContainingLayer()); @@ -332,7 +334,7 @@ Draw.Line = Draw.extend({ // disable drawing this.disable(); - if(this.options.continueDrawing){ + if (this.options.continueDrawing) { this.enable(); } }, @@ -342,7 +344,7 @@ Draw.Line = Draw.extend({ draggable: false, icon: L.divIcon({ className: 'marker-icon' }), }); - this._setPane(marker,'vertexPane'); + this._setPane(marker, 'vertexPane'); marker._pmTempLayer = true; // add it to the map @@ -353,16 +355,16 @@ Draw.Line = Draw.extend({ return marker; }, - _setTooltipText(){ - const {length} = this._layer.getLatLngs().flat(); - let text = ""; + _setTooltipText() { + const { length } = this._layer.getLatLngs().flat(); + let text = ''; // handle tooltip text - if(length <= 1){ + if (length <= 1) { text = getTranslation('tooltips.continueLine'); - }else{ + } else { text = getTranslation('tooltips.finishLine'); } this._hintMarker.setTooltipContent(text); - } + }, }); diff --git a/src/js/Draw/L.PM.Draw.Marker.js b/src/js/Draw/L.PM.Draw.Marker.js index 3260f6f9..e9980df1 100644 --- a/src/js/Draw/L.PM.Draw.Marker.js +++ b/src/js/Draw/L.PM.Draw.Marker.js @@ -23,7 +23,7 @@ Draw.Marker = Draw.extend({ // this is the hintmarker on the mouse cursor this._hintMarker = L.marker([0, 0], this.options.markerStyle); - this._setPane(this._hintMarker,'markerPane'); + this._setPane(this._hintMarker, 'markerPane'); this._hintMarker._pmTempLayer = true; this._hintMarker.addTo(this._map); @@ -46,10 +46,9 @@ Draw.Marker = Draw.extend({ // sync hint marker with mouse cursor this._map.on('mousemove', this._syncHintMarker, this); - // enable edit mode for existing markers - if(this.options.markerEditable) { - this._map.eachLayer(layer => { + if (this.options.markerEditable) { + this._map.eachLayer((layer) => { if (this.isRelevantMarker(layer)) { layer.pm.enable(); } @@ -79,13 +78,12 @@ Draw.Marker = Draw.extend({ this._map.off('mousemove', this._syncHintMarker, this); // disable dragging and removing for all markers - this._map.eachLayer(layer => { + this._map.eachLayer((layer) => { if (this.isRelevantMarker(layer)) { layer.pm.disable(); } }); - // toggle the draw button of the Toolbar in case drawing mode got disabled without the button this._map.pm.Toolbar.toggleButton(this.toolbarButtonName, false); @@ -128,7 +126,11 @@ Draw.Marker = Draw.extend({ } // If snap finish is required but the last marker wasn't snapped, do not finish the shape! - if (this.options.requireSnapToFinish && !this._hintMarker._snapped && !this._isFirstLayer()) { + if ( + this.options.requireSnapToFinish && + !this._hintMarker._snapped && + !this._isFirstLayer() + ) { return; } @@ -143,24 +145,21 @@ Draw.Marker = Draw.extend({ // create marker const marker = new L.Marker(latlng, this.options.markerStyle); - this._setPane(marker,'markerPane'); + this._setPane(marker, 'markerPane'); this._finishLayer(marker); - if(!marker.pm){ + if (!marker.pm) { // if pm is not create we don't apply dragging to the marker (draggable is applied to the marker, when it is added to the map ) marker.options.draggable = false; } // add marker to the map marker.addTo(this._map.pm._getContainingLayer()); - - if(marker.pm && this.options.markerEditable) { + if (marker.pm && this.options.markerEditable) { // enable editing for the marker marker.pm.enable(); - }else{ - if(marker.dragging) { - marker.dragging.disable(); - } + } else if (marker.dragging) { + marker.dragging.disable(); } // fire the pm:create event and pass shape and marker @@ -168,7 +167,7 @@ Draw.Marker = Draw.extend({ this._cleanupSnapping(); - if(!this.options.continueDrawing){ + if (!this.options.continueDrawing) { this.disable(); } }, diff --git a/src/js/Draw/L.PM.Draw.Polygon.js b/src/js/Draw/L.PM.Draw.Polygon.js index 5f118c43..70e3e0a7 100644 --- a/src/js/Draw/L.PM.Draw.Polygon.js +++ b/src/js/Draw/L.PM.Draw.Polygon.js @@ -13,7 +13,7 @@ Draw.Polygon = Draw.Line.extend({ draggable: false, icon: L.divIcon({ className: 'marker-icon' }), }); - this._setPane(marker,'vertexPane'); + this._setPane(marker, 'vertexPane'); // mark this marker as temporary marker._pmTempLayer = true; @@ -35,19 +35,19 @@ Draw.Polygon = Draw.Line.extend({ // add a click event w/ no handler to the marker // event won't bubble so prevents creation of identical markers in same polygon // fixes issue where double click during poly creation when allowSelfIntersection: false caused it to break - marker.on('click', () => (1)); + marker.on('click', () => 1); } return marker; }, - _setTooltipText(){ - const {length} = this._layer.getLatLngs().flat(); - let text = ""; + _setTooltipText() { + const { length } = this._layer.getLatLngs().flat(); + let text = ''; // handle tooltip text - if(length <= 2){ + if (length <= 2) { text = getTranslation('tooltips.continueLine'); - }else{ + } else { text = getTranslation('tooltips.finishPoly'); } this._hintMarker.setTooltipContent(text); @@ -64,7 +64,11 @@ Draw.Polygon = Draw.Line.extend({ } // If snap finish is required but the last marker wasn't snapped, do not finish the shape! - if (this.options.requireSnapToFinish && !this._hintMarker._snapped && !this._isFirstLayer()) { + if ( + this.options.requireSnapToFinish && + !this._hintMarker._snapped && + !this._isFirstLayer() + ) { return; } @@ -77,7 +81,7 @@ Draw.Polygon = Draw.Line.extend({ } const polygonLayer = L.polygon(coords, this.options.pathOptions); - this._setPane(polygonLayer,'layerPane'); + this._setPane(polygonLayer, 'layerPane'); this._finishLayer(polygonLayer); polygonLayer.addTo(this._map.pm._getContainingLayer()); @@ -93,7 +97,7 @@ Draw.Polygon = Draw.Line.extend({ // disable drawing this.disable(); - if(this.options.continueDrawing){ + if (this.options.continueDrawing) { this.enable(); } }, diff --git a/src/js/Draw/L.PM.Draw.Rectangle.js b/src/js/Draw/L.PM.Draw.Rectangle.js index 3edc192e..8e17e329 100644 --- a/src/js/Draw/L.PM.Draw.Rectangle.js +++ b/src/js/Draw/L.PM.Draw.Rectangle.js @@ -21,8 +21,14 @@ Draw.Rectangle = Draw.extend({ this._layerGroup.addTo(this._map); // the rectangle we want to draw - this._layer = L.rectangle([[0, 0], [0, 0]], this.options.pathOptions); - this._setPane(this._layer,'layerPane'); + this._layer = L.rectangle( + [ + [0, 0], + [0, 0], + ], + this.options.pathOptions + ); + this._setPane(this._layer, 'layerPane'); this._layer._pmTempLayer = true; // this is the marker at the origin of the rectangle @@ -33,7 +39,7 @@ Draw.Rectangle = Draw.extend({ zIndexOffset: -100, opacity: this.options.cursorMarker ? 1 : 0, }); - this._setPane(this._startMarker,'vertexPane'); + this._setPane(this._startMarker, 'vertexPane'); this._startMarker._pmTempLayer = true; this._layerGroup.addLayer(this._startMarker); @@ -42,7 +48,7 @@ Draw.Rectangle = Draw.extend({ zIndexOffset: 150, icon: L.divIcon({ className: 'marker-icon cursor-marker' }), }); - this._setPane(this._hintMarker,'vertexPane'); + this._setPane(this._hintMarker, 'vertexPane'); this._hintMarker._pmTempLayer = true; this._layerGroup.addLayer(this._hintMarker); @@ -73,7 +79,7 @@ Draw.Rectangle = Draw.extend({ draggable: false, zIndexOffset: 100, }); - this._setPane(styleMarker,'vertexPane'); + this._setPane(styleMarker, 'vertexPane'); styleMarker._pmTempLayer = true; this._layerGroup.addLayer(styleMarker); @@ -100,7 +106,6 @@ Draw.Rectangle = Draw.extend({ // fire drawstart event this._fireDrawStart(); this._setGlobalDrawMode(); - }, disable() { // disable drawing mode @@ -133,7 +138,6 @@ Draw.Rectangle = Draw.extend({ // fire drawend event this._fireDrawEnd(); this._setGlobalDrawMode(); - }, enabled() { return this._enabled; @@ -161,7 +165,7 @@ Draw.Rectangle = Draw.extend({ // if we have the other two visibilty markers, show and place them now if (this.options.cursorMarker && this._styleMarkers) { - this._styleMarkers.forEach(styleMarker => { + this._styleMarkers.forEach((styleMarker) => { L.DomUtil.addClass(styleMarker._icon, 'visible'); styleMarker.setLatLng(latlng); }); @@ -203,7 +207,12 @@ Draw.Rectangle = Draw.extend({ const B = this._hintMarker.getLatLng(); // Create a (maybe rotated) box using corners A & B (A = Starting Position, B = Current Mouse Position) - const corners = L.PM.Utils._getRotatedRectangle(A, B, this.options.rectangleAngle || 0, this._map); + const corners = L.PM.Utils._getRotatedRectangle( + A, + B, + this.options.rectangleAngle || 0, + this._map + ); this._layer.setLatLngs(corners); // Add matching style markers, if cursor marker is shown @@ -211,7 +220,7 @@ Draw.Rectangle = Draw.extend({ const unmarkedCorners = []; // Find two corners not currently occupied by starting marker and hint marker - corners.forEach(corner => { + corners.forEach((corner) => { if ( !corner.equals(this._startMarker.getLatLng()) && !corner.equals(this._hintMarker.getLatLng()) @@ -249,7 +258,11 @@ Draw.Rectangle = Draw.extend({ const A = this._startMarker.getLatLng(); // If snap finish is required but the last marker wasn't snapped, do not finish the shape! - if (this.options.requireSnapToFinish && !this._hintMarker._snapped && !this._isFirstLayer()) { + if ( + this.options.requireSnapToFinish && + !this._hintMarker._snapped && + !this._isFirstLayer() + ) { return; } @@ -257,15 +270,20 @@ Draw.Rectangle = Draw.extend({ const rectangleLayer = L.rectangle([A, B], this.options.pathOptions); // rectangle can only initialized with bounds (not working with rotation) so we update the latlngs - if(this.options.rectangleAngle){ - const corners = L.PM.Utils._getRotatedRectangle(A, B, this.options.rectangleAngle || 0, this._map); + if (this.options.rectangleAngle) { + const corners = L.PM.Utils._getRotatedRectangle( + A, + B, + this.options.rectangleAngle || 0, + this._map + ); rectangleLayer.setLatLngs(corners); - if(rectangleLayer.pm){ + if (rectangleLayer.pm) { rectangleLayer.pm._setAngle(this.options.rectangleAngle || 0); } } - this._setPane(rectangleLayer,'layerPane'); + this._setPane(rectangleLayer, 'layerPane'); this._finishLayer(rectangleLayer); rectangleLayer.addTo(this._map.pm._getContainingLayer()); @@ -274,7 +292,7 @@ Draw.Rectangle = Draw.extend({ // disable drawing this.disable(); - if(this.options.continueDrawing){ + if (this.options.continueDrawing) { this.enable(); } }, diff --git a/src/js/Draw/L.PM.Draw.js b/src/js/Draw/L.PM.Draw.js index 8446a3c9..b2fc17b9 100644 --- a/src/js/Draw/L.PM.Draw.js +++ b/src/js/Draw/L.PM.Draw.js @@ -1,11 +1,11 @@ import merge from 'lodash/merge'; import SnapMixin from '../Mixins/Snapping'; -import EventMixin from "../Mixins/Events"; +import EventMixin from '../Mixins/Events'; const Draw = L.Class.extend({ includes: [SnapMixin, EventMixin], options: { - snappable: true, //TODO: next major Release, rename it to allowSnapping + snappable: true, // TODO: next major Release, rename it to allowSnapping snapDistance: 20, snapMiddle: false, allowSelfIntersection: true, @@ -20,7 +20,7 @@ const Draw = L.Class.extend({ finishOn: null, markerStyle: { draggable: true, - icon: L.icon() + icon: L.icon(), }, hideMiddleMarkers: false, minRadiusCircle: null, @@ -43,28 +43,36 @@ const Draw = L.Class.extend({ // Overwriting the default tooltipAnchor of the default Marker Icon, because the tooltip functionality was updated but not the anchor in the Icon // Issue https://github.com/Leaflet/Leaflet/issues/7302 - Leaflet v1.7.1 const defaultIcon = new L.Icon.Default(); - defaultIcon.options.tooltipAnchor = [0,0]; + defaultIcon.options.tooltipAnchor = [0, 0]; this.options.markerStyle.icon = defaultIcon; // save the map this._map = map; // define all possible shapes that can be drawn - this.shapes = ['Marker', 'CircleMarker', 'Line', 'Polygon', 'Rectangle', 'Circle', 'Cut']; + this.shapes = [ + 'Marker', + 'CircleMarker', + 'Line', + 'Polygon', + 'Rectangle', + 'Circle', + 'Cut', + ]; // initiate drawing class for our shapes - this.shapes.forEach(shape => { + this.shapes.forEach((shape) => { this[shape] = new L.PM.Draw[shape](this._map); }); - this.Marker.setOptions({continueDrawing: true}); - this.CircleMarker.setOptions({continueDrawing: true}); + this.Marker.setOptions({ continueDrawing: true }); + this.CircleMarker.setOptions({ continueDrawing: true }); }, setPathOptions(options, mergeOptions = false) { - if(!mergeOptions) { + if (!mergeOptions) { this.options.pathOptions = options; - }else{ - this.options.pathOptions = merge(this.options.pathOptions,options); + } else { + this.options.pathOptions = merge(this.options.pathOptions, options); } }, getShapes() { @@ -94,20 +102,20 @@ const Draw = L.Class.extend({ // there can only be one drawing mode active at a time on a map // so it doesn't matter which one should be disabled. // just disable all of them - this.shapes.forEach(shape => { + this.shapes.forEach((shape) => { this[shape].disable(); }); }, addControls() { // add control buttons for our shapes - this.shapes.forEach(shape => { + this.shapes.forEach((shape) => { this[shape].addButton(); }); }, getActiveShape() { // returns the active shape let enabledShape; - this.shapes.forEach(shape => { + this.shapes.forEach((shape) => { if (this[shape]._enabled) { enabledShape = shape; } @@ -116,7 +124,7 @@ const Draw = L.Class.extend({ }, _setGlobalDrawMode() { // extended to all PM.Draw shapes - if (this._shape === "Cut") { + if (this._shape === 'Cut') { this._fireGlobalCutModeToggled(); } else { this._fireGlobalDrawModeToggled(); @@ -126,25 +134,21 @@ const Draw = L.Class.extend({ if (this._enabled) { layers.forEach((layer) => { L.PM.Utils.disablePopup(layer); - }) + }); } else { layers.forEach((layer) => { L.PM.Utils.enablePopup(layer); - }) + }); } }, createNewDrawInstance(name, jsClass) { const instance = this._getShapeFromBtnName(jsClass); if (this[name]) { - throw new TypeError( - "Draw Type already exists" - ); + throw new TypeError('Draw Type already exists'); } if (!L.PM.Draw[instance]) { - throw new TypeError( - `There is no class L.PM.Draw.${instance}` - ); + throw new TypeError(`There is no class L.PM.Draw.${instance}`); } this[name] = new L.PM.Draw[instance](this._map); @@ -163,17 +167,17 @@ const Draw = L.Class.extend({ }, _getShapeFromBtnName(name) { const shapeMapping = { - "drawMarker": "Marker", - "drawCircle": "Circle", - "drawPolygon": "Polygon", - "drawPolyline": "Line", - "drawRectangle": "Rectangle", - "drawCircleMarker": "CircleMarker", - "editMode": "Edit", - "dragMode": "Drag", - "cutPolygon": "Cut", - "removalMode": "Removal", - "rotateMode": "Rotate", + drawMarker: 'Marker', + drawCircle: 'Circle', + drawPolygon: 'Polygon', + drawPolyline: 'Line', + drawRectangle: 'Rectangle', + drawCircleMarker: 'CircleMarker', + editMode: 'Edit', + dragMode: 'Drag', + cutPolygon: 'Cut', + removalMode: 'Removal', + rotateMode: 'Rotate', }; if (shapeMapping[name]) { @@ -181,7 +185,7 @@ const Draw = L.Class.extend({ } return this[name] ? this[name]._shape : name; }, - _finishLayer(layer){ + _finishLayer(layer) { if (layer.pm) { // add the pm options from drawing to the new layer (edit) layer.pm.setOptions(this.options); @@ -192,22 +196,31 @@ const Draw = L.Class.extend({ } this._addDrawnLayerProp(layer); }, - _addDrawnLayerProp(layer){ + _addDrawnLayerProp(layer) { layer._drawnByGeoman = true; }, - _setPane(layer,type){ - if(type === "layerPane"){ - layer.options.pane = this._map.pm.globalOptions.panes && this._map.pm.globalOptions.panes.layerPane || 'overlayPane'; - }else if(type === "vertexPane"){ - layer.options.pane = this._map.pm.globalOptions.panes && this._map.pm.globalOptions.panes.vertexPane || 'markerPane'; - }else if(type === "markerPane"){ - layer.options.pane = this._map.pm.globalOptions.panes && this._map.pm.globalOptions.panes.markerPane || 'markerPane'; + _setPane(layer, type) { + if (type === 'layerPane') { + layer.options.pane = + (this._map.pm.globalOptions.panes && + this._map.pm.globalOptions.panes.layerPane) || + 'overlayPane'; + } else if (type === 'vertexPane') { + layer.options.pane = + (this._map.pm.globalOptions.panes && + this._map.pm.globalOptions.panes.vertexPane) || + 'markerPane'; + } else if (type === 'markerPane') { + layer.options.pane = + (this._map.pm.globalOptions.panes && + this._map.pm.globalOptions.panes.markerPane) || + 'markerPane'; } }, - _isFirstLayer(){ + _isFirstLayer() { const map = this._map || this._layer._map; return map.pm.getGeomanLayers().length === 0; - } + }, }); export default Draw; diff --git a/src/js/Edit/L.PM.Edit.Circle.js b/src/js/Edit/L.PM.Edit.Circle.js index 013719de..b0e212ce 100644 --- a/src/js/Edit/L.PM.Edit.Circle.js +++ b/src/js/Edit/L.PM.Edit.Circle.js @@ -1,5 +1,5 @@ import Edit from './L.PM.Edit'; -import {destinationOnLine} from "../helpers"; +import { destinationOnLine } from '../helpers'; Edit.Circle = Edit.extend({ _shape: 'Circle', @@ -15,7 +15,7 @@ Edit.Circle = Edit.extend({ this._map = this._layer._map; // layer is not allowed to edit - if(!this.options.allowEditing){ + if (!this.options.allowEditing) { this.disable(); return; } @@ -35,7 +35,7 @@ Edit.Circle = Edit.extend({ this.applyOptions(); // if polygon gets removed from map, disable edit mode - this._layer.on('remove', e => { + this._layer.on('remove', (e) => { this.disable(e.target); }); // create polygon around the circle border @@ -57,7 +57,7 @@ Edit.Circle = Edit.extend({ this._centerMarker.off('dragstart', this._onCircleDragStart, this); this._centerMarker.off('drag', this._onCircleDrag, this); this._centerMarker.off('dragend', this._onCircleDragEnd, this); - this._outerMarker.off('drag',this._handleOuterMarkerSnapping, this); + this._outerMarker.off('drag', this._handleOuterMarkerSnapping, this); layer.pm._enabled = false; layer.pm._helperLayers.clearLayers(); @@ -66,7 +66,6 @@ Edit.Circle = Edit.extend({ const el = layer._path ? layer._path : this._layer._renderer._container; L.DomUtil.removeClass(el, 'leaflet-pm-draggable'); - if (this._layerEdited) { this._fireUpdate(); } @@ -113,7 +112,7 @@ Edit.Circle = Edit.extend({ if (this.options.snappable) { this._initSnappableMarkers(); // update marker latlng when snapped latlng radius is out of min/max - this._outerMarker.on('drag',this._handleOuterMarkerSnapping, this); + this._outerMarker.on('drag', this._handleOuterMarkerSnapping, this); // sync the hintline with hint marker this._outerMarker.on('move', this._syncHintLine, this); this._outerMarker.on('move', this._syncCircleRadius, this); @@ -126,7 +125,7 @@ Edit.Circle = Edit.extend({ const A = markerA.getLatLng(); const B = markerB.getLatLng(); this._hintline = L.polyline([A, B], this.options.hintlineStyle); - this._setPane(this._hintline,'layerPane'); + this._setPane(this._hintline, 'layerPane'); this._hintline._pmTempLayer = true; this._helperLayers.addLayer(this._hintline); }, @@ -157,7 +156,7 @@ Edit.Circle = Edit.extend({ draggable: true, icon: L.divIcon({ className: 'marker-icon' }), }); - this._setPane(marker,'vertexPane'); + this._setPane(marker, 'vertexPane'); marker._origLatLng = latlng; marker._pmTempLayer = true; @@ -177,7 +176,7 @@ Edit.Circle = Edit.extend({ }, _moveCircle(e) { const draggedMarker = e.target; - if(draggedMarker._cancelDragEventChain) { + if (draggedMarker._cancelDragEventChain) { return; } @@ -194,7 +193,7 @@ Edit.Circle = Edit.extend({ this._updateHiddenPolyCircle(); - this._fireCenterPlaced("Edit"); + this._fireCenterPlaced('Edit'); }, _syncCircleRadius() { const A = this._centerMarker.getLatLng(); @@ -202,11 +201,17 @@ Edit.Circle = Edit.extend({ const distance = A.distanceTo(B); - if(this.options.minRadiusCircle && distance < this.options.minRadiusCircle) { + if ( + this.options.minRadiusCircle && + distance < this.options.minRadiusCircle + ) { this._layer.setRadius(this.options.minRadiusCircle); - }else if(this.options.maxRadiusCircle && distance > this.options.maxRadiusCircle) { + } else if ( + this.options.maxRadiusCircle && + distance > this.options.maxRadiusCircle + ) { this._layer.setRadius(this.options.maxRadiusCircle); - }else{ + } else { this._layer.setRadius(distance); } @@ -220,7 +225,7 @@ Edit.Circle = Edit.extend({ this._hintline.setLatLngs([A, B]); }, _disableSnapping() { - this._markers.forEach(marker => { + this._markers.forEach((marker) => { marker.off('move', this._syncHintLine, this); marker.off('move', this._syncCircleRadius, this); marker.off('drag', this._handleSnapping, this); @@ -230,7 +235,7 @@ Edit.Circle = Edit.extend({ this._layer.off('pm:dragstart', this._unsnap, this); }, _onMarkerDragStart(e) { - if(!this._vertexValidation('move',e)){ + if (!this._vertexValidation('move', e)) { return; } this._fireMarkerDragStart(e); @@ -238,7 +243,7 @@ Edit.Circle = Edit.extend({ _onMarkerDrag(e) { // dragged marker const draggedMarker = e.target; - if(!this._vertexValidationDrag(draggedMarker)){ + if (!this._vertexValidationDrag(draggedMarker)) { return; } this._fireMarkerDrag(e); @@ -246,7 +251,7 @@ Edit.Circle = Edit.extend({ _onMarkerDragEnd(e) { // dragged marker const draggedMarker = e.target; - if(!this._vertexValidationDragEnd(draggedMarker)){ + if (!this._vertexValidationDragEnd(draggedMarker)) { return; } @@ -256,7 +261,7 @@ Edit.Circle = Edit.extend({ this._fireMarkerDragEnd(e); }, _onCircleDragStart(e) { - if(!this._vertexValidationDrag(e.target)){ + if (!this._vertexValidationDrag(e.target)) { // we create a new flag, because the other flag is cleared before _fireDragEnd is called this._vertexValidationReset = true; return; @@ -265,13 +270,13 @@ Edit.Circle = Edit.extend({ this._fireDragStart(e); }, _onCircleDrag(e) { - if(this._vertexValidationReset){ + if (this._vertexValidationReset) { return; } this._fireDrag(e); }, _onCircleDragEnd() { - if(this._vertexValidationReset){ + if (this._vertexValidationReset) { delete this._vertexValidationReset; return; } @@ -279,13 +284,15 @@ Edit.Circle = Edit.extend({ }, _updateHiddenPolyCircle() { if (this._hiddenPolyCircle) { - this._hiddenPolyCircle.setLatLngs(L.PM.Utils.circleToPolygon(this._layer, 200).getLatLngs()); + this._hiddenPolyCircle.setLatLngs( + L.PM.Utils.circleToPolygon(this._layer, 200).getLatLngs() + ); } else { this._hiddenPolyCircle = L.PM.Utils.circleToPolygon(this._layer, 200); } if (!this._hiddenPolyCircle._parentCopy) { - this._hiddenPolyCircle._parentCopy = this._layer + this._hiddenPolyCircle._parentCopy = this._layer; } }, _getLatLngOnCircle(center, radius) { @@ -294,29 +301,51 @@ Edit.Circle = Edit.extend({ return this._map.unproject(pointB); }, - _getNewDestinationOfOuterMarker(){ + _getNewDestinationOfOuterMarker() { const latlng = this._centerMarker.getLatLng(); let secondLatLng = this._outerMarker.getLatLng(); const distance = latlng.distanceTo(secondLatLng); - if(this.options.minRadiusCircle && distance < this.options.minRadiusCircle) { - secondLatLng = destinationOnLine(this._map,latlng,secondLatLng,this.options.minRadiusCircle); - }else if(this.options.maxRadiusCircle && distance > this.options.maxRadiusCircle) { - secondLatLng = destinationOnLine(this._map,latlng,secondLatLng,this.options.maxRadiusCircle); + if ( + this.options.minRadiusCircle && + distance < this.options.minRadiusCircle + ) { + secondLatLng = destinationOnLine( + this._map, + latlng, + secondLatLng, + this.options.minRadiusCircle + ); + } else if ( + this.options.maxRadiusCircle && + distance > this.options.maxRadiusCircle + ) { + secondLatLng = destinationOnLine( + this._map, + latlng, + secondLatLng, + this.options.maxRadiusCircle + ); } return secondLatLng; }, - _handleOuterMarkerSnapping(){ - if(this._outerMarker._snapped) { + _handleOuterMarkerSnapping() { + if (this._outerMarker._snapped) { const latlng = this._centerMarker.getLatLng(); const secondLatLng = this._outerMarker.getLatLng(); const distance = latlng.distanceTo(secondLatLng); - if(this.options.minRadiusCircle && distance < this.options.minRadiusCircle) { + if ( + this.options.minRadiusCircle && + distance < this.options.minRadiusCircle + ) { this._outerMarker.setLatLng(this._outerMarker._orgLatLng); - } else if(this.options.maxRadiusCircle && distance > this.options.maxRadiusCircle) { + } else if ( + this.options.maxRadiusCircle && + distance > this.options.maxRadiusCircle + ) { this._outerMarker.setLatLng(this._outerMarker._orgLatLng); } } // calculate the new latlng of marker if radius is out of min/max this._outerMarker.setLatLng(this._getNewDestinationOfOuterMarker()); - } + }, }); diff --git a/src/js/Edit/L.PM.Edit.CircleMarker.js b/src/js/Edit/L.PM.Edit.CircleMarker.js index f69fcafd..087a789b 100644 --- a/src/js/Edit/L.PM.Edit.CircleMarker.js +++ b/src/js/Edit/L.PM.Edit.CircleMarker.js @@ -1,5 +1,5 @@ import Edit from './L.PM.Edit'; -import {destinationOnLine} from "../helpers"; +import { destinationOnLine } from '../helpers'; Edit.CircleMarker = Edit.extend({ _shape: 'CircleMarker', @@ -9,7 +9,7 @@ Edit.CircleMarker = Edit.extend({ // create polygon around the circle border this._updateHiddenPolyCircle(); }, - //TODO: remove default option in next major Release + // TODO: remove default option in next major Release enable(options = { draggable: true, snappable: true }) { L.Util.setOptions(this, options); @@ -21,7 +21,7 @@ Edit.CircleMarker = Edit.extend({ } // layer is not allowed to edit - if(!this.options.allowEditing){ + if (!this.options.allowEditing) { this.disable(); return; } @@ -62,7 +62,7 @@ Edit.CircleMarker = Edit.extend({ if (this.options.editable) { this._map.off('move', this._syncMarkers, this); - if(this._outerMarker) { + if (this._outerMarker) { // update marker latlng when snapped latlng radius is out of min/max this._outerMarker.on('drag', this._handleOuterMarkerSnapping, this); } @@ -123,9 +123,9 @@ Edit.CircleMarker = Edit.extend({ // https://github.com/Leaflet/Leaflet/issues/6492 this._centerMarker.on('drag', this._moveCircle, this); - if(this.options.editable){ + if (this.options.editable) { // update marker latlng when snapped latlng radius is out of min/max - this._outerMarker.on('drag',this._handleOuterMarkerSnapping, this); + this._outerMarker.on('drag', this._handleOuterMarkerSnapping, this); } // sync the hintline with hint marker this._outerMarker.on('move', this._syncHintLine, this); @@ -177,7 +177,7 @@ Edit.CircleMarker = Edit.extend({ const A = markerA.getLatLng(); const B = markerB.getLatLng(); this._hintline = L.polyline([A, B], this.options.hintlineStyle); - this._setPane(this._hintline,'layerPane'); + this._setPane(this._hintline, 'layerPane'); this._hintline._pmTempLayer = true; this._helperLayers.addLayer(this._hintline); }, @@ -200,7 +200,7 @@ Edit.CircleMarker = Edit.extend({ draggable: true, icon: L.divIcon({ className: 'marker-icon' }), }); - this._setPane(marker,'vertexPane'); + this._setPane(marker, 'vertexPane'); marker._origLatLng = latlng; marker._pmTempLayer = true; @@ -227,7 +227,7 @@ Edit.CircleMarker = Edit.extend({ this._updateHiddenPolyCircle(); - this._fireCenterPlaced("Edit"); + this._fireCenterPlaced('Edit'); }, _syncMarkers() { const center = this._layer.getLatLng(); @@ -248,11 +248,17 @@ Edit.CircleMarker = Edit.extend({ const B = this._outerMarker.getLatLng(); const distance = this._map.project(A).distanceTo(this._map.project(B)); - if(this.options.minRadiusCircleMarker && distance < this.options.minRadiusCircleMarker) { + if ( + this.options.minRadiusCircleMarker && + distance < this.options.minRadiusCircleMarker + ) { this._layer.setRadius(this.options.minRadiusCircleMarker); - }else if(this.options.maxRadiusCircleMarker && distance > this.options.maxRadiusCircleMarker) { + } else if ( + this.options.maxRadiusCircleMarker && + distance > this.options.maxRadiusCircleMarker + ) { this._layer.setRadius(this.options.maxRadiusCircleMarker); - }else{ + } else { this._layer.setRadius(distance); } @@ -272,14 +278,13 @@ Edit.CircleMarker = Edit.extend({ this._fireRemove(this._layer); this._fireRemove(this._map, this._layer); }, - _onDragStart(e){ + _onDragStart(e) { this._map.pm.Draw.CircleMarker._layerIsDragging = true; - if(!this._vertexValidation('move',e)){ - return; + if (!this._vertexValidation('move', e)) { } }, _onMarkerDragStart(e) { - if(!this._vertexValidation('move',e)){ + if (!this._vertexValidation('move', e)) { return; } @@ -288,7 +293,10 @@ Edit.CircleMarker = Edit.extend({ _onMarkerDrag(e) { // dragged marker const draggedMarker = e.target; - if(draggedMarker instanceof L.Marker && !this._vertexValidationDrag(draggedMarker)){ + if ( + draggedMarker instanceof L.Marker && + !this._vertexValidationDrag(draggedMarker) + ) { return; } @@ -299,7 +307,7 @@ Edit.CircleMarker = Edit.extend({ // dragged marker const draggedMarker = e.target; - if(!this._vertexValidationDragEnd(draggedMarker)){ + if (!this._vertexValidationDragEnd(draggedMarker)) { return; } if (this.options.editable) { @@ -313,7 +321,8 @@ Edit.CircleMarker = Edit.extend({ const marker = this._layer; this.options.snapDistance = this.options.snapDistance || 30; - this.options.snapSegment = this.options.snapSegment === undefined ? true : this.options.snapSegment; + this.options.snapSegment = + this.options.snapSegment === undefined ? true : this.options.snapSegment; marker.off('pm:drag', this._handleSnapping, this); marker.on('pm:drag', this._handleSnapping, this); @@ -334,7 +343,7 @@ Edit.CircleMarker = Edit.extend({ }, _updateHiddenPolyCircle() { const map = this._layer._map || this._map; - if(map) { + if (map) { const pointA = map.project(this._layer.getLatLng()); const pointB = L.point(pointA.x + this._layer.getRadius(), pointA.y); const radius = this._layer.getLatLng().distanceTo(map.unproject(pointB)); @@ -343,45 +352,73 @@ Edit.CircleMarker = Edit.extend({ _layer.setRadius(radius); if (this._hiddenPolyCircle) { - this._hiddenPolyCircle.setLatLngs(L.PM.Utils.circleToPolygon(_layer, 200).getLatLngs()); + this._hiddenPolyCircle.setLatLngs( + L.PM.Utils.circleToPolygon(_layer, 200).getLatLngs() + ); } else { this._hiddenPolyCircle = L.PM.Utils.circleToPolygon(_layer, 200); } if (!this._hiddenPolyCircle._parentCopy) { - this._hiddenPolyCircle._parentCopy = this._layer + this._hiddenPolyCircle._parentCopy = this._layer; } } }, - _getNewDestinationOfOuterMarker(){ + _getNewDestinationOfOuterMarker() { const latlng = this._centerMarker.getLatLng(); let secondLatLng = this._outerMarker.getLatLng(); - const distance = this._map.project(latlng).distanceTo(this._map.project(secondLatLng)); - if(this.options.minRadiusCircleMarker && distance < this.options.minRadiusCircleMarker) { - secondLatLng = destinationOnLine(this._map,latlng,secondLatLng,this._pxRadiusToMeter(this.options.minRadiusCircleMarker)); - }else if(this.options.maxRadiusCircleMarker && distance > this.options.maxRadiusCircleMarker) { - secondLatLng = destinationOnLine(this._map,latlng,secondLatLng,this._pxRadiusToMeter(this.options.maxRadiusCircleMarker)); + const distance = this._map + .project(latlng) + .distanceTo(this._map.project(secondLatLng)); + if ( + this.options.minRadiusCircleMarker && + distance < this.options.minRadiusCircleMarker + ) { + secondLatLng = destinationOnLine( + this._map, + latlng, + secondLatLng, + this._pxRadiusToMeter(this.options.minRadiusCircleMarker) + ); + } else if ( + this.options.maxRadiusCircleMarker && + distance > this.options.maxRadiusCircleMarker + ) { + secondLatLng = destinationOnLine( + this._map, + latlng, + secondLatLng, + this._pxRadiusToMeter(this.options.maxRadiusCircleMarker) + ); } return secondLatLng; }, - _handleOuterMarkerSnapping(){ - if(this._outerMarker._snapped) { + _handleOuterMarkerSnapping() { + if (this._outerMarker._snapped) { const latlng = this._centerMarker.getLatLng(); const secondLatLng = this._outerMarker.getLatLng(); - const distance = this._map.project(latlng).distanceTo(this._map.project(secondLatLng)); - if(this.options.minRadiusCircleMarker && distance < this.options.minRadiusCircleMarker) { + const distance = this._map + .project(latlng) + .distanceTo(this._map.project(secondLatLng)); + if ( + this.options.minRadiusCircleMarker && + distance < this.options.minRadiusCircleMarker + ) { this._outerMarker.setLatLng(this._outerMarker._orgLatLng); - } else if(this.options.maxRadiusCircleMarker && distance > this.options.maxRadiusCircleMarker) { + } else if ( + this.options.maxRadiusCircleMarker && + distance > this.options.maxRadiusCircleMarker + ) { this._outerMarker.setLatLng(this._outerMarker._orgLatLng); } } // calculate the new latlng of marker if radius is out of min/max this._outerMarker.setLatLng(this._getNewDestinationOfOuterMarker()); }, - _pxRadiusToMeter(radius){ + _pxRadiusToMeter(radius) { const center = this._centerMarker.getLatLng(); const pointA = this._map.project(center); const pointB = L.point(pointA.x + radius, pointA.y); return this._map.unproject(pointB).distanceTo(center); - } + }, }); diff --git a/src/js/Edit/L.PM.Edit.ImageOverlay.js b/src/js/Edit/L.PM.Edit.ImageOverlay.js index 6f7baff0..910646dc 100644 --- a/src/js/Edit/L.PM.Edit.ImageOverlay.js +++ b/src/js/Edit/L.PM.Edit.ImageOverlay.js @@ -16,7 +16,7 @@ Edit.ImageOverlay = Edit.extend({ enabled() { return this._enabled; }, - //TODO: remove default option in next major Release + // TODO: remove default option in next major Release enable(options = { draggable: true, snappable: true }) { L.Util.setOptions(this, options); this._map = this._layer._map; @@ -26,7 +26,7 @@ Edit.ImageOverlay = Edit.extend({ } // layer is not allowed to edit - if(!this.options.allowEditing){ + if (!this.options.allowEditing) { this.disable(); return; } diff --git a/src/js/Edit/L.PM.Edit.LayerGroup.js b/src/js/Edit/L.PM.Edit.LayerGroup.js index 4136c344..5ea2f0ef 100644 --- a/src/js/Edit/L.PM.Edit.LayerGroup.js +++ b/src/js/Edit/L.PM.Edit.LayerGroup.js @@ -10,7 +10,7 @@ Edit.LayerGroup = L.Class.extend({ this._getMap(); // init all layers of the group - this._layers.forEach(layer => this._initLayer(layer)); + this._layers.forEach((layer) => this._initLayer(layer)); // if a new layer is added to the group, reinitialize // This only works for FeatureGroups, not LayerGroups @@ -21,25 +21,41 @@ Edit.LayerGroup = L.Class.extend({ return; } this._layers = this.getLayers(); - const _initLayers = this._layers.filter((layer) => !layer.pm._parentLayerGroup || !(this._layerGroup._leaflet_id in layer.pm._parentLayerGroup)); + const _initLayers = this._layers.filter( + (layer) => + !layer.pm._parentLayerGroup || + !(this._layerGroup._leaflet_id in layer.pm._parentLayerGroup) + ); // init the newly added layers (can be multiple because of the throttle) _initLayers.forEach((layer) => { this._initLayer(layer); }); // if editing was already enabled for this group, enable it again // so the new layers are enabled - if (_initLayers.length > 0 && this._getMap() && this._getMap().pm.globalEditModeEnabled()) { + if ( + _initLayers.length > 0 && + this._getMap() && + this._getMap().pm.globalEditModeEnabled() + ) { if (this.enabled()) { this.enable(this.getOptions()); } } }; - this._layerGroup.on('layeradd', L.Util.throttle(addThrottle, 100, this), this); + this._layerGroup.on( + 'layeradd', + L.Util.throttle(addThrottle, 100, this), + this + ); // Remove the layergroup from the layer - this._layerGroup.on('layerremove', (e) => { - this._removeLayerFromGroup(e.target); - }, this); + this._layerGroup.on( + 'layerremove', + (e) => { + this._removeLayerFromGroup(e.target); + }, + this + ); const removeThrottle = (e) => { if (e.target._pmTempLayer) { @@ -49,14 +65,18 @@ Edit.LayerGroup = L.Class.extend({ }; // if a layer is removed from the group, calc the layers list again. // we run this as throttle because the findLayers() is a larger function - this._layerGroup.on('layerremove', L.Util.throttle(removeThrottle, 100, this), this); + this._layerGroup.on( + 'layerremove', + L.Util.throttle(removeThrottle, 100, this), + this + ); }, enable(options, _layerIds = []) { - if(_layerIds.length === 0) { + if (_layerIds.length === 0) { this._layers = this.getLayers(); } this._options = options; - this._layers.forEach(layer => { + this._layers.forEach((layer) => { if (layer instanceof L.LayerGroup) { if (_layerIds.indexOf(layer._leaflet_id) === -1) { _layerIds.push(layer._leaflet_id); @@ -68,10 +88,10 @@ Edit.LayerGroup = L.Class.extend({ }); }, disable(_layerIds = []) { - if(_layerIds.length === 0) { + if (_layerIds.length === 0) { this._layers = this.getLayers(); } - this._layers.forEach(layer => { + this._layers.forEach((layer) => { if (layer instanceof L.LayerGroup) { if (_layerIds.indexOf(layer._leaflet_id) === -1) { _layerIds.push(layer._leaflet_id); @@ -83,7 +103,7 @@ Edit.LayerGroup = L.Class.extend({ }); }, enabled(_layerIds = []) { - if(_layerIds.length === 0) { + if (_layerIds.length === 0) { this._layers = this.getLayers(); } const enabled = this._layers.find((layer) => { @@ -99,11 +119,11 @@ Edit.LayerGroup = L.Class.extend({ return !!enabled; }, toggleEdit(options, _layerIds = []) { - if(_layerIds.length === 0) { + if (_layerIds.length === 0) { this._layers = this.getLayers(); } this._options = options; - this._layers.forEach(layer => { + this._layers.forEach((layer) => { if (layer instanceof L.LayerGroup) { if (_layerIds.indexOf(layer._leaflet_id) === -1) { _layerIds.push(layer._leaflet_id); @@ -123,7 +143,7 @@ Edit.LayerGroup = L.Class.extend({ layer.pm._parentLayerGroup[id] = this._layerGroup; }, _removeLayerFromGroup(layer) { - if(layer.pm && layer.pm._layerGroup) { + if (layer.pm && layer.pm._layerGroup) { const id = L.Util.stamp(this._layerGroup); delete layer.pm._layerGroup[id]; } @@ -131,7 +151,7 @@ Edit.LayerGroup = L.Class.extend({ dragging() { this._layers = this.getLayers(); if (this._layers) { - const dragging = this._layers.find(layer => layer.pm.dragging()); + const dragging = this._layers.find((layer) => layer.pm.dragging()); return !!dragging; } return false; @@ -139,19 +159,26 @@ Edit.LayerGroup = L.Class.extend({ getOptions() { return this.options; }, - _getMap(){ - return this._map || this._layers.find(l => !!l._map)?._map || null; + _getMap() { + return this._map || this._layers.find((l) => !!l._map)?._map || null; }, - getLayers(deep = false, filterGeoman = true, filterGroupsOut = true, _layerIds = []){ + getLayers( + deep = false, + filterGeoman = true, + filterGroupsOut = true, + _layerIds = [] + ) { let layers = []; - if(deep) { + if (deep) { // get the layers of LayerGroup children - this._layerGroup.getLayers().forEach((layer)=>{ + this._layerGroup.getLayers().forEach((layer) => { layers.push(layer); if (layer instanceof L.LayerGroup) { if (_layerIds.indexOf(layer._leaflet_id) === -1) { _layerIds.push(layer._leaflet_id); - layers = layers.concat(layer.pm.getLayers(true, true, true, _layerIds)); + layers = layers.concat( + layer.pm.getLayers(true, true, true, _layerIds) + ); } } }); @@ -160,30 +187,30 @@ Edit.LayerGroup = L.Class.extend({ layers = this._layerGroup.getLayers(); } - if(filterGroupsOut) { - layers = layers.filter(layer => !(layer instanceof L.LayerGroup)); + if (filterGroupsOut) { + layers = layers.filter((layer) => !(layer instanceof L.LayerGroup)); } - if(filterGeoman) { + if (filterGeoman) { // filter out layers that don't have leaflet-geoman - layers = layers.filter(layer => !!layer.pm); + layers = layers.filter((layer) => !!layer.pm); // filter out everything that's leaflet-geoman specific temporary stuff - layers = layers.filter(layer => !layer._pmTempLayer); + layers = layers.filter((layer) => !layer._pmTempLayer); // filter out everything that ignore leaflet-geoman - layers = layers.filter(layer => ( + layers = layers.filter( + (layer) => (!L.PM.optIn && !layer.options.pmIgnore) || // if optIn is not set / true and pmIgnore is not set / true (default) (L.PM.optIn && layer.options.pmIgnore === false) // if optIn is true and pmIgnore is false); - ) ); } return layers; }, setOptions(options, _layerIds = []) { - if(_layerIds.length === 0) { + if (_layerIds.length === 0) { this._layers = this.getLayers(); } this.options = options; - this._layers.forEach(layer => { - if(layer.pm) { + this._layers.forEach((layer) => { + if (layer.pm) { if (layer instanceof L.LayerGroup) { if (_layerIds.indexOf(layer._leaflet_id) === -1) { _layerIds.push(layer._leaflet_id); diff --git a/src/js/Edit/L.PM.Edit.Line.js b/src/js/Edit/L.PM.Edit.Line.js index 2dc91776..499873e1 100644 --- a/src/js/Edit/L.PM.Edit.Line.js +++ b/src/js/Edit/L.PM.Edit.Line.js @@ -2,7 +2,7 @@ import kinks from '@turf/kinks'; import lineIntersect from '@turf/line-intersect'; import get from 'lodash/get'; import Edit from './L.PM.Edit'; -import {isEmptyDeep, removeEmptyCoordRings} from '../helpers'; +import { isEmptyDeep, removeEmptyCoordRings } from '../helpers'; import MarkerLimits from '../Mixins/MarkerLimits'; @@ -32,7 +32,7 @@ Edit.Line = Edit.extend({ } // layer is not allowed to edit - if(!this.options.allowEditing){ + if (!this.options.allowEditing) { this.disable(); return; } @@ -63,14 +63,14 @@ Edit.Line = Edit.extend({ } if (!this.options.allowSelfIntersection) { - if(this._layer.options.color !== '#f00000ff') { + if (this._layer.options.color !== '#f00000ff') { this.cachedColor = this._layer.options.color; this.isRed = false; - }else{ + } else { this.isRed = true; } this._handleLayerStyle(); - }else{ + } else { this.cachedColor = undefined; } this._fireEnable(); @@ -151,7 +151,7 @@ Edit.Line = Edit.extend({ this._markerGroup._pmTempLayer = true; // handle coord-rings (outer, inner, etc) - const handleRing = coordsArr => { + const handleRing = (coordsArr) => { // if there is another coords ring, go a level deep and do this again if (Array.isArray(coordsArr[0])) { return coordsArr.map(handleRing, this); @@ -164,7 +164,9 @@ Edit.Line = Edit.extend({ // create small markers in the middle of the regular markers coordsArr.map((v, k) => { // find the next index fist - const nextIndex = this.isPolygon() ? (k + 1) % coordsArr.length : k + 1; + const nextIndex = this.isPolygon() + ? (k + 1) % coordsArr.length + : k + 1; // create the marker return this._createMiddleMarker(ringArr[k], ringArr[nextIndex]); }); @@ -189,7 +191,7 @@ Edit.Line = Edit.extend({ draggable: true, icon: L.divIcon({ className: 'marker-icon' }), }); - this._setPane(marker,'vertexPane'); + this._setPane(marker, 'vertexPane'); marker._pmTempLayer = true; @@ -208,7 +210,6 @@ Edit.Line = Edit.extend({ } } - this._markerGroup.addLayer(marker); return marker; @@ -240,14 +241,14 @@ Edit.Line = Edit.extend({ rightM._middleMarkerPrev = middleMarker; middleMarker.on(this.options.addVertexOn, this._onMiddleMarkerClick, this); - middleMarker.on('movestart',this._onMiddleMarkerMoveStart, this); + middleMarker.on('movestart', this._onMiddleMarkerMoveStart, this); return middleMarker; }, - _onMiddleMarkerClick(e){ + _onMiddleMarkerClick(e) { const middleMarker = e.target; - if(!this._vertexValidation('add',e)) { + if (!this._vertexValidation('add', e)) { return; } // TODO: move the next two lines inside _addMarker() as soon as @@ -257,10 +258,10 @@ Edit.Line = Edit.extend({ middleMarker.setIcon(icon); this._addMarker(middleMarker, middleMarker.leftM, middleMarker.rightM); }, - _onMiddleMarkerMoveStart(e){ + _onMiddleMarkerMoveStart(e) { const middleMarker = e.target; middleMarker.on('moveend', this._onMiddleMarkerMoveEnd, this); - if(!this._vertexValidation('add',e)) { + if (!this._vertexValidation('add', e)) { middleMarker.on('move', this._onMiddleMarkerMovePrevent, this); return; } @@ -275,24 +276,24 @@ Edit.Line = Edit.extend({ const middleMarker = e.target; this._vertexValidationDrag(middleMarker); }, - _onMiddleMarkerMoveEnd(e){ + _onMiddleMarkerMoveEnd(e) { const middleMarker = e.target; middleMarker.off('move', this._onMiddleMarkerMovePrevent, this); middleMarker.off('moveend', this._onMiddleMarkerMoveEnd, this); - if(!this._vertexValidationDragEnd(middleMarker)) { + if (!this._vertexValidationDragEnd(middleMarker)) { return; } const icon = L.divIcon({ className: 'marker-icon' }); middleMarker.setIcon(icon); // timeout is needed else this._onVertexClick fires the event because it is called after deleting the flag - setTimeout(()=> { + setTimeout(() => { delete middleMarker._dragging; - },100); + }, 100); }, // adds a new marker from a middlemarker _addMarker(newM, leftM, rightM) { // first, make this middlemarker a regular marker - newM.off('movestart',this._onMiddleMarkerMoveStart, this); + newM.off('movestart', this._onMiddleMarkerMoveStart, this); newM.off(this.options.addVertexOn, this._onMiddleMarkerClick, this); // now, create the polygon coordinate point for that marker // and push into marker array @@ -336,7 +337,11 @@ Edit.Line = Edit.extend({ this._fireEdit(); this._layerEdited = true; - this._fireVertexAdded(newM,this.findDeepMarkerIndex(this._markers, newM).indexPath, latlng); + this._fireVertexAdded( + newM, + this.findDeepMarkerIndex(this._markers, newM).indexPath, + latlng + ); if (this.options.snappable) { this._initSnappableMarkers(); @@ -367,7 +372,10 @@ Edit.Line = Edit.extend({ const layer = this._layer; if (this.hasSelfIntersection()) { - if (!this.options.allowSelfIntersection && this.options.allowSelfIntersectionEdit) { + if ( + !this.options.allowSelfIntersection && + this.options.allowSelfIntersectionEdit + ) { this._updateDisabledMarkerStyle(this._markers, true); } @@ -390,13 +398,16 @@ Edit.Line = Edit.extend({ // if not, reset the style to the default color layer.setStyle({ color: this.cachedColor }); this.isRed = false; - if (!this.options.allowSelfIntersection && this.options.allowSelfIntersectionEdit) { + if ( + !this.options.allowSelfIntersection && + this.options.allowSelfIntersectionEdit + ) { this._updateDisabledMarkerStyle(this._markers, false); } } }, - _flashLayer(){ - if(!this.cachedColor){ + _flashLayer() { + if (!this.cachedColor) { this.cachedColor = this._layer.options.color; } @@ -416,9 +427,9 @@ Edit.Line = Edit.extend({ if (marker._icon) { if (disabled && !this._checkMarkerAllowedToDrag(marker)) { - L.DomUtil.addClass(marker._icon, "vertexmarker-disabled"); + L.DomUtil.addClass(marker._icon, 'vertexmarker-disabled'); } else { - L.DomUtil.removeClass(marker._icon, "vertexmarker-disabled"); + L.DomUtil.removeClass(marker._icon, 'vertexmarker-disabled'); } } }); @@ -427,8 +438,8 @@ Edit.Line = Edit.extend({ // the marker that should be removed const marker = e.target; - if(!this._vertexValidation('remove',e)) { - return; + if (!this._vertexValidation('remove', e)) { + return; } // if self intersection isn't allowed, save the coords upon dragstart @@ -459,11 +470,13 @@ Edit.Line = Edit.extend({ let markerArr = indexPath.length > 1 ? get(this._markers, parentPath) : this._markers; - // prevent removal of the layer if the vertex count is below minimum - if(!this.options.removeLayerBelowMinVertexCount) { + if (!this.options.removeLayerBelowMinVertexCount) { // if on a line only 2 vertices left or on a polygon 3 vertices left, don't allow to delete - if (coordsRing.length <= 2 || (this.isPolygon() && coordsRing.length <= 3)) { + if ( + coordsRing.length <= 2 || + (this.isPolygon() && coordsRing.length <= 3) + ) { this._flashLayer(); return; } @@ -507,9 +520,10 @@ Edit.Line = Edit.extend({ this._markers = removeEmptyCoordRings(this._markers); // No need to calculate the middle marker when the layer was removed - if(!layerRemoved) { + if (!layerRemoved) { // get new markerArr because we cleaned up coords and markers array - markerArr = indexPath.length > 1 ? get(this._markers, parentPath) : this._markers; + markerArr = + indexPath.length > 1 ? get(this._markers, parentPath) : this._markers; // now handle the middle markers // remove the marker and the middlemarkers next to it from the map @@ -534,7 +548,8 @@ Edit.Line = Edit.extend({ } else { // find neighbor marker-indexes leftMarkerIndex = index - 1 < 0 ? undefined : index - 1; - rightMarkerIndex = index + 1 >= markerArr.length ? undefined : index + 1; + rightMarkerIndex = + index + 1 >= markerArr.length ? undefined : index + 1; } // don't create middlemarkers if there is only one marker left @@ -563,7 +578,7 @@ Edit.Line = Edit.extend({ // thanks for the function, Felix Heck let result; - const run = path => (v, i) => { + const run = (path) => (v, i) => { const iRes = path.concat(i); if (v._leaflet_id === marker._leaflet_id) { @@ -615,13 +630,13 @@ Edit.Line = Edit.extend({ ); // the markers neighbors - const markerArr = indexPath.length > 1 ? get(this._markers, parentPath) : this._markers; + const markerArr = + indexPath.length > 1 ? get(this._markers, parentPath) : this._markers; // find the indizes of next and previous markers const nextMarkerIndex = (index + 1) % markerArr.length; const prevMarkerIndex = (index + (markerArr.length - 1)) % markerArr.length; - // get prev and next marker const prevMarker = markerArr[prevMarkerIndex]; const nextMarker = markerArr[nextMarkerIndex]; @@ -634,13 +649,22 @@ Edit.Line = Edit.extend({ const prevLine = L.polyline([prevMarker.getLatLng(), marker.getLatLng()]); const nextLine = L.polyline([marker.getLatLng(), nextMarker.getLatLng()]); - let prevLineIntersectionLen = lineIntersect(this._layer.toGeoJSON(15), prevLine.toGeoJSON(15)).features.length; - let nextLineIntersectionLen = lineIntersect(this._layer.toGeoJSON(15), nextLine.toGeoJSON(15)).features.length; + let prevLineIntersectionLen = lineIntersect( + this._layer.toGeoJSON(15), + prevLine.toGeoJSON(15) + ).features.length; + let nextLineIntersectionLen = lineIntersect( + this._layer.toGeoJSON(15), + nextLine.toGeoJSON(15) + ).features.length; // The first and last line has one intersection fewer because they are not connected if (marker.getLatLng() === this._markers[0][0].getLatLng()) { nextLineIntersectionLen += 1; - } else if (marker.getLatLng() === this._markers[0][this._markers[0].length - 1].getLatLng()) { + } else if ( + marker.getLatLng() === + this._markers[0][this._markers[0].length - 1].getLatLng() + ) { prevLineIntersectionLen += 1; } @@ -649,7 +673,6 @@ Edit.Line = Edit.extend({ return false; } return true; - }, _onMarkerDragStart(e) { const marker = e.target; @@ -659,7 +682,7 @@ Edit.Line = Edit.extend({ this.cachedColor = this._layer.options.color; } - if(!this._vertexValidation('move',e)){ + if (!this._vertexValidation('move', e)) { return; } @@ -673,7 +696,11 @@ Edit.Line = Edit.extend({ this._coordsBeforeEdit = this._layer.getLatLngs(); } - if (!this.options.allowSelfIntersection && this.options.allowSelfIntersectionEdit && this.hasSelfIntersection()) { + if ( + !this.options.allowSelfIntersection && + this.options.allowSelfIntersectionEdit && + this.hasSelfIntersection() + ) { this._markerAllowedToDrag = this._checkMarkerAllowedToDrag(marker); } else { this._markerAllowedToDrag = null; @@ -683,7 +710,7 @@ Edit.Line = Edit.extend({ // dragged marker const marker = e.target; - if(!this._vertexValidationDrag(marker)){ + if (!this._vertexValidationDrag(marker)) { return; } @@ -697,7 +724,12 @@ Edit.Line = Edit.extend({ return; } - if (!this.options.allowSelfIntersection && this.options.allowSelfIntersectionEdit && this.hasSelfIntersection() && this._markerAllowedToDrag === false) { + if ( + !this.options.allowSelfIntersection && + this.options.allowSelfIntersectionEdit && + this.hasSelfIntersection() && + this._markerAllowedToDrag === false + ) { this._layer.setLatLngs(this._coordsBeforeEdit); // re-enable markers for the new coords this._initMarkers(); @@ -751,21 +783,25 @@ Edit.Line = Edit.extend({ _onMarkerDragEnd(e) { const marker = e.target; - if(!this._vertexValidationDragEnd(marker)){ + if (!this._vertexValidationDragEnd(marker)) { return; } const { indexPath } = this.findDeepMarkerIndex(this._markers, marker); - // if self intersection is not allowed but this edit caused a self intersection, // reset and cancel; do not fire events let intersection = this.hasSelfIntersection(); - if (intersection && this.options.allowSelfIntersectionEdit && this._markerAllowedToDrag) { + if ( + intersection && + this.options.allowSelfIntersectionEdit && + this._markerAllowedToDrag + ) { intersection = false; } - const intersectionReset = !this.options.allowSelfIntersection && intersection; + const intersectionReset = + !this.options.allowSelfIntersection && intersection; this._fireMarkerDragEnd(e, indexPath, intersectionReset); @@ -784,10 +820,13 @@ Edit.Line = Edit.extend({ // check for selfintersection again (mainly to reset the style) this._handleLayerStyle(); - this._fireLayerReset(e,indexPath); + this._fireLayerReset(e, indexPath); return; } - if (!this.options.allowSelfIntersection && this.options.allowSelfIntersectionEdit) { + if ( + !this.options.allowSelfIntersection && + this.options.allowSelfIntersectionEdit + ) { this._handleLayerStyle(); } // fire edit event @@ -796,12 +835,12 @@ Edit.Line = Edit.extend({ }, _onVertexClick(e) { const vertex = e.target; - if(vertex._dragging){ + if (vertex._dragging) { return; } const { indexPath } = this.findDeepMarkerIndex(this._markers, vertex); - this._fireVertexClick(e,indexPath); + this._fireVertexClick(e, indexPath); }, }); diff --git a/src/js/Edit/L.PM.Edit.Marker.js b/src/js/Edit/L.PM.Edit.Marker.js index 0ea5ae8a..43746301 100644 --- a/src/js/Edit/L.PM.Edit.Marker.js +++ b/src/js/Edit/L.PM.Edit.Marker.js @@ -10,14 +10,14 @@ Edit.Marker = Edit.extend({ // register dragend event e.g. to fire pm:edit this._layer.on('dragend', this._onDragEnd, this); }, - //TODO: remove default option in next major Release + // TODO: remove default option in next major Release enable(options = { draggable: true }) { L.Util.setOptions(this, options); this._map = this._layer._map; // layer is not allowed to edit - if(!this.options.allowEditing){ + if (!this.options.allowEditing) { this.disable(); return; } @@ -89,7 +89,8 @@ Edit.Marker = Edit.extend({ const marker = this._layer; this.options.snapDistance = this.options.snapDistance || 30; - this.options.snapSegment = this.options.snapSegment === undefined ? true : this.options.snapSegment; + this.options.snapSegment = + this.options.snapSegment === undefined ? true : this.options.snapSegment; marker.off('pm:drag', this._handleSnapping, this); marker.on('pm:drag', this._handleSnapping, this); @@ -105,5 +106,5 @@ Edit.Marker = Edit.extend({ marker.off('pm:drag', this._handleSnapping, this); marker.off('pm:dragend', this._cleanupSnapping, this); marker.off('pm:dragstart', this._unsnap, this); - } + }, }); diff --git a/src/js/Edit/L.PM.Edit.Polygon.js b/src/js/Edit/L.PM.Edit.Polygon.js index 259eaeeb..1cd54b1d 100644 --- a/src/js/Edit/L.PM.Edit.Polygon.js +++ b/src/js/Edit/L.PM.Edit.Polygon.js @@ -1,22 +1,27 @@ -import lineIntersect from "@turf/line-intersect"; +import lineIntersect from '@turf/line-intersect'; import Edit from './L.PM.Edit'; Edit.Polygon = Edit.Line.extend({ - _shape: 'Polygon', - _checkMarkerAllowedToDrag(marker) { - const { prevMarker, nextMarker } = this._getNeighborMarkers(marker); + _shape: 'Polygon', + _checkMarkerAllowedToDrag(marker) { + const { prevMarker, nextMarker } = this._getNeighborMarkers(marker); - const prevLine = L.polyline([prevMarker.getLatLng(), marker.getLatLng()]); - const nextLine = L.polyline([marker.getLatLng(), nextMarker.getLatLng()]); + const prevLine = L.polyline([prevMarker.getLatLng(), marker.getLatLng()]); + const nextLine = L.polyline([marker.getLatLng(), nextMarker.getLatLng()]); - const prevLineIntersectionLen = lineIntersect(this._layer.toGeoJSON(15), prevLine.toGeoJSON(15)).features.length; - const nextLineIntersectionLen = lineIntersect(this._layer.toGeoJSON(15), nextLine.toGeoJSON(15)).features.length; + const prevLineIntersectionLen = lineIntersect( + this._layer.toGeoJSON(15), + prevLine.toGeoJSON(15) + ).features.length; + const nextLineIntersectionLen = lineIntersect( + this._layer.toGeoJSON(15), + nextLine.toGeoJSON(15) + ).features.length; - // <= 2 the start and end point of the line always intersecting because they have the same coords. - if (prevLineIntersectionLen <= 2 && nextLineIntersectionLen <= 2) { - return false; - } - return true; - - }, + // <= 2 the start and end point of the line always intersecting because they have the same coords. + if (prevLineIntersectionLen <= 2 && nextLineIntersectionLen <= 2) { + return false; + } + return true; + }, }); diff --git a/src/js/Edit/L.PM.Edit.Rectangle.js b/src/js/Edit/L.PM.Edit.Rectangle.js index 16ce19b4..8bb6cf7c 100644 --- a/src/js/Edit/L.PM.Edit.Rectangle.js +++ b/src/js/Edit/L.PM.Edit.Rectangle.js @@ -29,13 +29,12 @@ Edit.Rectangle = Edit.Polygon.extend({ [this._cornerMarkers] = this._markers; // Update the marker latlngs if the rectangle is rotated - this._layer.getLatLngs()[0].forEach((latlng,index)=>{ - const marker = this._cornerMarkers.find((m)=> m._index === index); - if(marker){ + this._layer.getLatLngs()[0].forEach((latlng, index) => { + const marker = this._cornerMarkers.find((m) => m._index === index); + if (marker) { marker.setLatLng(latlng); } }); - }, applyOptions() { if (this.options.snappable) { @@ -52,7 +51,7 @@ Edit.Rectangle = Edit.Polygon.extend({ draggable: true, icon: L.divIcon({ className: 'marker-icon' }), }); - this._setPane(marker,'vertexPane'); + this._setPane(marker, 'vertexPane'); marker._origLatLng = latlng; marker._index = index; @@ -63,11 +62,11 @@ Edit.Rectangle = Edit.Polygon.extend({ return marker; }, // Add marker events after adding the snapping events to the markers, beacause of the execution order - _addMarkerEvents(){ - this._markers[0].forEach((marker)=>{ - marker.on('dragstart', this._onMarkerDragStart, this); - marker.on('drag', this._onMarkerDrag, this); - marker.on('dragend', this._onMarkerDragEnd, this); + _addMarkerEvents() { + this._markers[0].forEach((marker) => { + marker.on('dragstart', this._onMarkerDragStart, this); + marker.on('drag', this._onMarkerDrag, this); + marker.on('dragend', this._onMarkerDragEnd, this); // TODO: Can we remove this? The _removeMarker Event is a empty function if (!this.options.preventMarkerRemoval) { @@ -83,7 +82,7 @@ Edit.Rectangle = Edit.Polygon.extend({ }, _onMarkerDragStart(e) { - if(!this._vertexValidation('move',e)){ + if (!this._vertexValidation('move', e)) { return; } @@ -91,7 +90,9 @@ Edit.Rectangle = Edit.Polygon.extend({ const draggedMarker = e.target; // Store/update a reference to marker in opposite corner const corners = this._cornerMarkers; - draggedMarker._oppositeCornerLatLng = corners.find((m)=> m._index === ((draggedMarker._index + 2) % 4)).getLatLng(); + draggedMarker._oppositeCornerLatLng = corners + .find((m) => m._index === (draggedMarker._index + 2) % 4) + .getLatLng(); // Automatically unsnap all markers on drag start (they'll snap back if close enough to another snappable object) // (Without this, it's occasionally possible for a marker to get stuck as 'snapped,' which prevents Rectangle resizing) @@ -104,7 +105,7 @@ Edit.Rectangle = Edit.Polygon.extend({ // dragged marker const draggedMarker = e.target; - if(!this._vertexValidationDrag(draggedMarker)){ + if (!this._vertexValidationDrag(draggedMarker)) { return; } @@ -121,12 +122,12 @@ Edit.Rectangle = Edit.Polygon.extend({ _onMarkerDragEnd(e) { // dragged marker const draggedMarker = e.target; - if(!this._vertexValidationDragEnd(draggedMarker)){ + if (!this._vertexValidationDragEnd(draggedMarker)) { return; } // Clean-up data attributes - this._cornerMarkers.forEach(m => { + this._cornerMarkers.forEach((m) => { delete m._oppositeCornerLatLng; }); @@ -144,7 +145,12 @@ Edit.Rectangle = Edit.Polygon.extend({ L.extend(movedMarker._origLatLng, movedMarker._latlng); // update rectangle boundaries, based on moved marker's new LatLng and cached opposite corner's LatLng - const corners = L.PM.Utils._getRotatedRectangle(movedMarker.getLatLng(),movedMarker._oppositeCornerLatLng, this._angle || 0, this._map); + const corners = L.PM.Utils._getRotatedRectangle( + movedMarker.getLatLng(), + movedMarker._oppositeCornerLatLng, + this._angle || 0, + this._map + ); this._layer.setLatLngs(corners); // Reposition the markers at each corner @@ -159,37 +165,45 @@ Edit.Rectangle = Edit.Polygon.extend({ _adjustAllMarkers() { const markerLatLngs = this._layer.getLatLngs()[0]; - if(markerLatLngs && markerLatLngs.length !== 4 && markerLatLngs.length > 0){ + if ( + markerLatLngs && + markerLatLngs.length !== 4 && + markerLatLngs.length > 0 + ) { // The layers is currently to small and has not enough latlngs. // Leaflet destroys the valid Rectangle by removing the last latlng if the last and first latlng are equal. See: Leaflet#7464 V1.7.1 // update all possible markers - markerLatLngs.forEach((latlng, index)=>{ + markerLatLngs.forEach((latlng, index) => { this._cornerMarkers[index].setLatLng(latlng); }); // apply to all markers with no latlng on the layer, the first latlng const restMarkers = this._cornerMarkers.slice(markerLatLngs.length); - restMarkers.forEach((marker)=>{ + restMarkers.forEach((marker) => { marker.setLatLng(markerLatLngs[0]); }); } else if (!markerLatLngs || !markerLatLngs.length) { - console.error("The layer has no LatLngs"); + console.error('The layer has no LatLngs'); } else { this._cornerMarkers.forEach((marker) => { marker.setLatLng(markerLatLngs[marker._index]); }); } - }, // finds the 4 corners of the current bounding box // returns array of 4 LatLng objects in this order: Northwest corner, Northeast corner, Southeast corner, Southwest corner _findCorners() { - //TODO What should we do here???? + // TODO What should we do here???? const corners = this._layer.getBounds(); const latlngs = this._layer.getLatLngs()[0]; - return L.PM.Utils._getRotatedRectangle(latlngs[0],latlngs[2], this._angle || 0, this._map); + return L.PM.Utils._getRotatedRectangle( + latlngs[0], + latlngs[2], + this._angle || 0, + this._map + ); const northwest = corners.getNorthWest(); const northeast = corners.getNorthEast(); @@ -198,5 +212,4 @@ Edit.Rectangle = Edit.Polygon.extend({ return [northwest, northeast, southeast, southwest]; }, - }); diff --git a/src/js/Edit/L.PM.Edit.js b/src/js/Edit/L.PM.Edit.js index 90a3adc9..2e0cd7f4 100644 --- a/src/js/Edit/L.PM.Edit.js +++ b/src/js/Edit/L.PM.Edit.js @@ -1,12 +1,12 @@ import SnapMixin from '../Mixins/Snapping'; import DragMixin from '../Mixins/Dragging'; -import RotateMixin from "../Mixins/Rotating"; -import EventMixin from "../Mixins/Events"; +import RotateMixin from '../Mixins/Rotating'; +import EventMixin from '../Mixins/Events'; const Edit = L.Class.extend({ includes: [DragMixin, SnapMixin, RotateMixin, EventMixin], options: { - snappable: true, //TODO: next major Release, rename it to allowSnapping + snappable: true, // TODO: next major Release, rename it to allowSnapping snapDistance: 20, allowSelfIntersection: true, allowSelfIntersectionEdit: false, @@ -16,7 +16,7 @@ const Edit = L.Class.extend({ hideMiddleMarkers: false, snapSegment: true, syncLayersOnDrag: false, - draggable: true, //TODO: next major Release, rename it to allowDragging + draggable: true, // TODO: next major Release, rename it to allowDragging allowEditing: true, // disable all interactions on a layer which are activated with `enable()`. For example a Circle can't be dragged in Edit-Mode allowRemoval: true, allowCutting: true, @@ -33,43 +33,56 @@ const Edit = L.Class.extend({ getOptions() { return this.options; }, - applyOptions() { }, + applyOptions() {}, isPolygon() { // if it's a polygon, it means the coordinates array is multi dimensional return this._layer instanceof L.Polygon; }, - getShape(){ + getShape() { return this._shape; }, - _setPane(layer,type){ - if(type === "layerPane"){ - layer.options.pane = this._map.pm.globalOptions.panes && this._map.pm.globalOptions.panes.layerPane || 'overlayPane'; - }else if(type === "vertexPane"){ - layer.options.pane = this._map.pm.globalOptions.panes && this._map.pm.globalOptions.panes.vertexPane || 'markerPane'; - }else if(type === "markerPane"){ - layer.options.pane = this._map.pm.globalOptions.panes && this._map.pm.globalOptions.panes.markerPane || 'markerPane'; + _setPane(layer, type) { + if (type === 'layerPane') { + layer.options.pane = + (this._map.pm.globalOptions.panes && + this._map.pm.globalOptions.panes.layerPane) || + 'overlayPane'; + } else if (type === 'vertexPane') { + layer.options.pane = + (this._map.pm.globalOptions.panes && + this._map.pm.globalOptions.panes.vertexPane) || + 'markerPane'; + } else if (type === 'markerPane') { + layer.options.pane = + (this._map.pm.globalOptions.panes && + this._map.pm.globalOptions.panes.markerPane) || + 'markerPane'; } }, - remove(){ + remove() { const map = this._map || this._layer._map; - map.pm.removeLayer({target: this._layer}); + map.pm.removeLayer({ target: this._layer }); }, - _vertexValidation(type, e){ + _vertexValidation(type, e) { const marker = e.target; - const args = {layer: this._layer, marker, event: e }; + const args = { layer: this._layer, marker, event: e }; - let validationFnc = ""; - if(type === 'move') { - validationFnc = "moveVertexValidation"; - } else if(type === 'add') { - validationFnc = "addVertexValidation"; - } else if(type === 'remove') { - validationFnc = "removeVertexValidation"; + let validationFnc = ''; + if (type === 'move') { + validationFnc = 'moveVertexValidation'; + } else if (type === 'add') { + validationFnc = 'addVertexValidation'; + } else if (type === 'remove') { + validationFnc = 'removeVertexValidation'; } // if validation goes wrong, we return false - if (this.options[validationFnc] && typeof this.options[validationFnc] === "function" && !this.options[validationFnc](args)) { - if(type === 'move') { + if ( + this.options[validationFnc] && + typeof this.options[validationFnc] === 'function' && + !this.options[validationFnc](args) + ) { + if (type === 'move') { marker._cancelDragEventChain = marker.getLatLng(); } return false; @@ -78,23 +91,22 @@ const Edit = L.Class.extend({ marker._cancelDragEventChain = null; return true; }, - _vertexValidationDrag(marker){ + _vertexValidationDrag(marker) { // we reset the marker to the place before it was dragged. We need this, because we can't stop the drag process in a `dragstart` | `movestart` listener - if(marker._cancelDragEventChain){ + if (marker._cancelDragEventChain) { marker._latlng = marker._cancelDragEventChain; marker.update(); return false; } return true; }, - _vertexValidationDragEnd(marker){ - if(marker._cancelDragEventChain){ + _vertexValidationDragEnd(marker) { + if (marker._cancelDragEventChain) { marker._cancelDragEventChain = null; return false; } return true; - } - + }, }); export default Edit; diff --git a/src/js/L.PM.Map.js b/src/js/L.PM.Map.js index 749e8a5d..3763e41e 100644 --- a/src/js/L.PM.Map.js +++ b/src/js/L.PM.Map.js @@ -3,12 +3,18 @@ import translations from '../assets/translations'; import GlobalEditMode from './Mixins/Modes/Mode.Edit'; import GlobalDragMode from './Mixins/Modes/Mode.Drag'; import GlobalRemovalMode from './Mixins/Modes/Mode.Removal'; -import GlobalRotateMode from "./Mixins/Modes/Mode.Rotate"; -import EventMixin from "./Mixins/Events"; -import KeyboardMixins from "./Mixins/Keyboard"; +import GlobalRotateMode from './Mixins/Modes/Mode.Rotate'; +import EventMixin from './Mixins/Events'; +import KeyboardMixins from './Mixins/Keyboard'; const Map = L.Class.extend({ - includes: [GlobalEditMode, GlobalDragMode, GlobalRemovalMode, GlobalRotateMode, EventMixin], + includes: [ + GlobalEditMode, + GlobalDragMode, + GlobalRemovalMode, + GlobalRotateMode, + EventMixin, + ], initialize(map) { this.map = map; this.Draw = new L.PM.Draw(map); @@ -18,12 +24,19 @@ const Map = L.Class.extend({ this.globalOptions = { snappable: true, layerGroup: undefined, - snappingOrder: ['Marker','CircleMarker','Circle','Line','Polygon','Rectangle'], + snappingOrder: [ + 'Marker', + 'CircleMarker', + 'Circle', + 'Line', + 'Polygon', + 'Rectangle', + ], panes: { vertexPane: 'markerPane', layerPane: 'overlayPane', - markerPane: 'markerPane' - } + markerPane: 'markerPane', + }, }; this.Keyboard._initKeyListener(map); @@ -71,11 +84,11 @@ const Map = L.Class.extend({ const ignore = optionsModifier.ignoreShapes || []; const mergeOptions = optionsModifier.merge || false; - this.map.pm.Draw.shapes.forEach(shape => { + this.map.pm.Draw.shapes.forEach((shape) => { if (ignore.indexOf(shape) === -1) { this.map.pm.Draw[shape].setPathOptions(options, mergeOptions); } - }) + }); }, getGlobalOptions() { @@ -83,27 +96,30 @@ const Map = L.Class.extend({ }, setGlobalOptions(o) { // merge passed and existing options - const options = merge(this.globalOptions,o); + const options = merge(this.globalOptions, o); // check if switched the editable mode for CircleMarker while drawing let reenableCircleMarker = false; - if(this.map.pm.Draw.CircleMarker.enabled() && this.map.pm.Draw.CircleMarker.options.editable !== options.editable){ + if ( + this.map.pm.Draw.CircleMarker.enabled() && + this.map.pm.Draw.CircleMarker.options.editable !== options.editable + ) { this.map.pm.Draw.CircleMarker.disable(); reenableCircleMarker = true; } // enable options for Drawing Shapes - this.map.pm.Draw.shapes.forEach(shape => { - this.map.pm.Draw[shape].setOptions(options) + this.map.pm.Draw.shapes.forEach((shape) => { + this.map.pm.Draw[shape].setOptions(options); }); - if(reenableCircleMarker){ + if (reenableCircleMarker) { this.map.pm.Draw.CircleMarker.enable(); } // enable options for Editing const layers = L.PM.Utils.findLayers(this.map); - layers.forEach(layer => { + layers.forEach((layer) => { layer.pm.setOptions(options); }); @@ -115,7 +131,7 @@ const Map = L.Class.extend({ }, applyGlobalOptions() { const layers = L.PM.Utils.findLayers(this.map); - layers.forEach(layer => { + layers.forEach((layer) => { if (layer.pm.enabled()) { layer.pm.applyOptions(); } @@ -136,9 +152,9 @@ const Map = L.Class.extend({ disableGlobalCutMode() { return this.Draw.Cut.disable(); }, - getGeomanLayers(asGroup = false){ + getGeomanLayers(asGroup = false) { const layers = L.PM.Utils.findLayers(this.map); - if(!asGroup) { + if (!asGroup) { return layers; } const group = L.featureGroup(); @@ -148,9 +164,11 @@ const Map = L.Class.extend({ }); return group; }, - getGeomanDrawLayers(asGroup = false){ - const layers = L.PM.Utils.findLayers(this.map).filter(l => l._drawnByGeoman === true); - if(!asGroup) { + getGeomanDrawLayers(asGroup = false) { + const layers = L.PM.Utils.findLayers(this.map).filter( + (l) => l._drawnByGeoman === true + ); + if (!asGroup) { return layers; } const group = L.featureGroup(); @@ -161,10 +179,12 @@ const Map = L.Class.extend({ return group; }, // returns the map instance by default or a layergroup is set through global options - _getContainingLayer(){ - return this.globalOptions.layerGroup && this.globalOptions.layerGroup instanceof L.LayerGroup ? this.globalOptions.layerGroup : this.map; - } - + _getContainingLayer() { + return this.globalOptions.layerGroup && + this.globalOptions.layerGroup instanceof L.LayerGroup + ? this.globalOptions.layerGroup + : this.map; + }, }); export default Map; diff --git a/src/js/L.PM.Utils.js b/src/js/L.PM.Utils.js index a6676b95..e001d083 100644 --- a/src/js/L.PM.Utils.js +++ b/src/js/L.PM.Utils.js @@ -1,5 +1,5 @@ -import { createGeodesicPolygon, getTranslation } from "./helpers"; -import {_toLatLng, _toPoint} from "./helpers/ModeHelper"; +import { createGeodesicPolygon, getTranslation } from './helpers'; +import { _toLatLng, _toPoint } from './helpers/ModeHelper'; const Utils = { calcMiddleLatLng(map, latlng1, latlng2) { @@ -12,7 +12,7 @@ const Utils = { }, findLayers(map) { let layers = []; - map.eachLayer(layer => { + map.eachLayer((layer) => { if ( layer instanceof L.Polyline || layer instanceof L.Marker || @@ -25,16 +25,16 @@ const Utils = { }); // filter out layers that don't have the leaflet-geoman instance - layers = layers.filter(layer => !!layer.pm); + layers = layers.filter((layer) => !!layer.pm); // filter out everything that's leaflet-geoman specific temporary stuff - layers = layers.filter(layer => !layer._pmTempLayer); + layers = layers.filter((layer) => !layer._pmTempLayer); // filter out everything that ignore leaflet-geoman - layers = layers.filter(layer => ( + layers = layers.filter( + (layer) => (!L.PM.optIn && !layer.options.pmIgnore) || // if optIn is not set / true and pmIgnore is not set / true (default) (L.PM.optIn && layer.options.pmIgnore === false) // if optIn is true and pmIgnore is false); - ) ); return layers; @@ -50,61 +50,64 @@ const Utils = { } return L.polygon(polygon, circle.options); }, - disablePopup(layer){ - if(layer.getPopup()){ + disablePopup(layer) { + if (layer.getPopup()) { layer._tempPopupCopy = layer.getPopup(); layer.unbindPopup(); } }, - enablePopup(layer){ - if(layer._tempPopupCopy){ + enablePopup(layer) { + if (layer._tempPopupCopy) { layer.bindPopup(layer._tempPopupCopy); delete layer._tempPopupCopy; } }, - _fireEvent(layer,type,data,propagate = false) { + _fireEvent(layer, type, data, propagate = false) { layer.fire(type, data, propagate); // fire event to all parent layers - const {groups} = this.getAllParentGroups(layer); + const { groups } = this.getAllParentGroups(layer); groups.forEach((group) => { group.fire(type, data, propagate); }); }, - getAllParentGroups(layer){ + getAllParentGroups(layer) { const groupIds = []; const groups = []; // get every group layer once const loopThroughParents = (_layer) => { for (const _id in _layer._eventParents) { - if(groupIds.indexOf(_id) === -1){ + if (groupIds.indexOf(_id) === -1) { groupIds.push(_id); const group = _layer._eventParents[_id]; groups.push(group); - loopThroughParents(group) + loopThroughParents(group); } } }; // check if the last group fetch is under 1 sec, then we use the groups from before - if(!layer._pmLastGroupFetch || !layer._pmLastGroupFetch.time || (new Date().getTime() - layer._pmLastGroupFetch.time)> 1000){ + if ( + !layer._pmLastGroupFetch || + !layer._pmLastGroupFetch.time || + new Date().getTime() - layer._pmLastGroupFetch.time > 1000 + ) { loopThroughParents(layer); layer._pmLastGroupFetch = { time: new Date().getTime(), groups, - groupIds - } ; + groupIds, + }; return { groupIds, - groups - } - }else{ - return { - groups: layer._pmLastGroupFetch.groups, - groupIds: layer._pmLastGroupFetch.groupIds - } + groups, + }; } + return { + groups: layer._pmLastGroupFetch.groups, + groupIds: layer._pmLastGroupFetch.groupIds, + }; }, createGeodesicPolygon, getTranslation, @@ -113,7 +116,7 @@ const Utils = { // thanks for the function, Felix Heck let result; - const run = path => (v, i) => { + const run = (path) => (v, i) => { const iRes = path.concat(i); if (v.lat && v.lat === latlng.lat && v.lng === latlng.lng) { @@ -143,7 +146,7 @@ const Utils = { const indexB = this.findDeepCoordIndex(coords, segment[1]); let newIndex = Math.max(indexA.index, indexB.index); if ((indexA.index === 0 || indexB.index === 0) && newIndex !== 1) { - newIndex+=1; + newIndex += 1; } return { indexA, @@ -158,23 +161,25 @@ const Utils = { // Returns the corners of the rectangle with a given rotation // degrees: Between marker A and the marker counterclockwise before. Same for marker B _getRotatedRectangle(A, B, rotation, map) { - const startPoint = _toPoint(map,A); - const endPoint = _toPoint(map,B); + const startPoint = _toPoint(map, A); + const endPoint = _toPoint(map, B); const theta = (rotation * Math.PI) / 180; const cos = Math.cos(theta); const sin = Math.sin(theta); - const width = ((endPoint.x - startPoint.x) * cos) + ((endPoint.y - startPoint.y) * sin); - const height = ((endPoint.y - startPoint.y) * cos) - ((endPoint.x - startPoint.x) * sin); - const x0 = (width * cos) + startPoint.x; - const y0 = (width * sin) + startPoint.y; - const x1 = (-height * sin) + startPoint.x; - const y1 = (height * cos) + startPoint.y; - - const p0 = _toLatLng(map,startPoint); - const p1 = _toLatLng(map,{ x: x0, y: y0 }); - const p2 = _toLatLng(map,endPoint); - const p3 = _toLatLng(map,{ x: x1, y: y1 }); + const width = + (endPoint.x - startPoint.x) * cos + (endPoint.y - startPoint.y) * sin; + const height = + (endPoint.y - startPoint.y) * cos - (endPoint.x - startPoint.x) * sin; + const x0 = width * cos + startPoint.x; + const y0 = width * sin + startPoint.y; + const x1 = -height * sin + startPoint.x; + const y1 = height * cos + startPoint.y; + + const p0 = _toLatLng(map, startPoint); + const p1 = _toLatLng(map, { x: x0, y: y0 }); + const p2 = _toLatLng(map, endPoint); + const p3 = _toLatLng(map, { x: x1, y: y1 }); return [p0, p1, p2, p3]; }, }; diff --git a/src/js/Mixins/Dragging.js b/src/js/Mixins/Dragging.js index 65e261c7..d0c409b4 100644 --- a/src/js/Mixins/Dragging.js +++ b/src/js/Mixins/Dragging.js @@ -1,7 +1,7 @@ const DragMixin = { enableLayerDrag() { // layer is not allowed to dragged - if(!this.options.draggable){ + if (!this.options.draggable) { return; } @@ -15,13 +15,16 @@ const DragMixin = { this._map = this._layer._map; } - if (this._layer instanceof L.Marker || this._layer instanceof L.ImageOverlay) { + if ( + this._layer instanceof L.Marker || + this._layer instanceof L.ImageOverlay + ) { // prevents dragging the DOM image instead of the marker - L.DomEvent.on(this._getDOMElem(),'dragstart',this._stopDOMImageDrag); + L.DomEvent.on(this._getDOMElem(), 'dragstart', this._stopDOMImageDrag); } // Disable Leaflet Dragging of Markers - if(this._layer.dragging){ + if (this._layer.dragging) { this._layer.dragging.disable(); } @@ -61,7 +64,7 @@ const DragMixin = { this._safeToCacheDragState = false; // Disable Leaflet Dragging of Markers - if(this._layer.dragging){ + if (this._layer.dragging) { this._layer.dragging.disable(); } @@ -72,7 +75,7 @@ const DragMixin = { dragging() { return this._dragging; }, - layerDragEnabled(){ + layerDragEnabled() { return !!this._layerDragEnabled; }, _dragMixinOnMouseDown(e) { @@ -85,7 +88,7 @@ const DragMixin = { const fromLayerSync = e._fromLayerSync; // if other layers found, snapping will be disabled - const layersToSyncFound = this._syncLayers("_dragMixinOnMouseDown",e); + const layersToSyncFound = this._syncLayers('_dragMixinOnMouseDown', e); if (this._layer instanceof L.Marker) { if (this.options.snappable && !fromLayerSync && !layersToSyncFound) { @@ -96,12 +99,15 @@ const DragMixin = { } // we need to disable snapping for CircleMarker because they are snapping because of the check in onLayerDrag -> if(_snapped) - if(this._layer instanceof L.CircleMarker && !(this._layer instanceof L.Circle)){ - if(this.options.snappable && !fromLayerSync && !layersToSyncFound){ + if ( + this._layer instanceof L.CircleMarker && + !(this._layer instanceof L.Circle) + ) { + if (this.options.snappable && !fromLayerSync && !layersToSyncFound) { if (!this._layer.pm.options.editable) { this._initSnappableMarkersDrag(); } - }else{ + } else { if (this._layer.pm.options.editable) { this._layer.pm._disableSnapping(); } else { @@ -131,14 +137,14 @@ const DragMixin = { this._overwriteEventIfItComesFromMarker(e); const el = this._getDOMElem(); - this._syncLayers("_dragMixinOnMouseMove",e); + this._syncLayers('_dragMixinOnMouseMove', e); if (!this._dragging) { // set state this._dragging = true; L.DomUtil.addClass(el, 'leaflet-pm-dragging'); - if(!(this._layer instanceof L.Marker)) { + if (!(this._layer instanceof L.Marker)) { // bring it to front to prevent drag interception this._layer.bringToFront(); } @@ -155,14 +161,14 @@ const DragMixin = { this._onLayerDrag(e); // update the hidden circle border after dragging - if(this._layer instanceof L.CircleMarker){ + if (this._layer instanceof L.CircleMarker) { this._layer.pm._updateHiddenPolyCircle(); } }, _dragMixinOnMouseUp(e) { const el = this._getDOMElem(); - this._syncLayers("_dragMixinOnMouseUp",e); + this._syncLayers('_dragMixinOnMouseUp', e); // re-enable map drag if (this._originalMapDragState) { @@ -184,7 +190,7 @@ const DragMixin = { } // update the hidden circle border after dragging - if(this._layer instanceof L.CircleMarker){ + if (this._layer instanceof L.CircleMarker) { this._layer.pm._updateHiddenPolyCircle(); } @@ -216,9 +222,9 @@ const DragMixin = { }; // move the coordinates by the delta - const moveCoords = coords => + const moveCoords = (coords) => // alter the coordinates - coords.map(currentLatLng => { + coords.map((currentLatLng) => { if (Array.isArray(currentLatLng)) { // do this recursively as coords might be nested return moveCoords(currentLatLng); @@ -231,14 +237,20 @@ const DragMixin = { }; }); - if (this._layer instanceof L.Circle || (this._layer instanceof L.CircleMarker && this._layer.options.editable)) { + if ( + this._layer instanceof L.Circle || + (this._layer instanceof L.CircleMarker && this._layer.options.editable) + ) { // create the new coordinates array const newCoords = moveCoords([this._layer.getLatLng()]); // set new coordinates and redraw this._layer.setLatLng(newCoords[0]); - } else if (this._layer instanceof L.CircleMarker || this._layer instanceof L.Marker) { + } else if ( + this._layer instanceof L.CircleMarker || + this._layer instanceof L.Marker + ) { let coordsRefernce = this._layer.getLatLng(); - if(this._layer._snapped) { + if (this._layer._snapped) { // if layer is snapped we use the original latlng for re-calculation, else the layer will not be "unsnappable" anymore coordsRefernce = this._layer._orgLatLng; } @@ -246,9 +258,12 @@ const DragMixin = { const newCoords = moveCoords([coordsRefernce]); // set new coordinates and redraw this._layer.setLatLng(newCoords[0]); - } else if( this._layer instanceof L.ImageOverlay){ + } else if (this._layer instanceof L.ImageOverlay) { // create the new coordinates array - const newCoords = moveCoords([this._layer.getBounds().getNorthWest(),this._layer.getBounds().getSouthEast()]); + const newCoords = moveCoords([ + this._layer.getBounds().getNorthWest(), + this._layer.getBounds().getSouthEast(), + ]); // set new coordinates and redraw this._layer.setBounds(newCoords); } else { @@ -268,74 +283,79 @@ const DragMixin = { }, addDraggingClass() { const el = this._getDOMElem(); - if(el) { + if (el) { L.DomUtil.addClass(el, 'leaflet-pm-draggable'); } }, removeDraggingClass() { const el = this._getDOMElem(); - if(el) { + if (el) { L.DomUtil.removeClass(el, 'leaflet-pm-draggable'); } }, - _getDOMElem(){ + _getDOMElem() { let el = null; - if(this._layer._path){ + if (this._layer._path) { el = this._layer._path; - }else if(this._layer._renderer && this._layer._renderer._container){ + } else if (this._layer._renderer && this._layer._renderer._container) { el = this._layer._renderer._container; - }else if(this._layer._image){ + } else if (this._layer._image) { el = this._layer._image; - }else if(this._layer._icon){ + } else if (this._layer._icon) { el = this._layer._icon; } return el; }, - _overwriteEventIfItComesFromMarker(e){ + _overwriteEventIfItComesFromMarker(e) { // e.latlng is not the clicked latlng if the layer is a Marker (or the radius below 10) -> Leaflet definition // https://github.com/Leaflet/Leaflet/blob/0f904a515879fcd08f69b7f51799ee7f18f23fd8/src/map/Map.js#L1416 - const isMarker = e.target.getLatLng && (!e.target._radius || e.target._radius <= 10); - if(isMarker){ + const isMarker = + e.target.getLatLng && (!e.target._radius || e.target._radius <= 10); + if (isMarker) { // we want the clicked latlng / point, so we overwrite the property e.latlng e.containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent); e.latlng = this._map.containerPointToLatLng(e.containerPoint); } }, - _syncLayers(fnc, e){ + _syncLayers(fnc, e) { // if layer is in Edit-Mode it should not be possible to drag other layers too. (Marker & CircleMarker & ImageOverlay) - if(this.enabled()){ + if (this.enabled()) { return false; } - if(!e._fromLayerSync && this._layer === e.target && this.options.syncLayersOnDrag){ + if ( + !e._fromLayerSync && + this._layer === e.target && + this.options.syncLayersOnDrag + ) { e._fromLayerSync = true; let layersToSync = []; - if(L.Util.isArray(this.options.syncLayersOnDrag)){ + if (L.Util.isArray(this.options.syncLayersOnDrag)) { // layers layersToSync = this.options.syncLayersOnDrag; - this.options.syncLayersOnDrag.forEach((layer)=>{ - if(layer instanceof L.LayerGroup){ + this.options.syncLayersOnDrag.forEach((layer) => { + if (layer instanceof L.LayerGroup) { layersToSync = layersToSync.concat(layer.pm.getLayers(true)); } - }) - - }else if(this.options.syncLayersOnDrag === true){ + }); + } else if (this.options.syncLayersOnDrag === true) { // LayerGroup - if(this._parentLayerGroup){ - for(const key in this._parentLayerGroup){ + if (this._parentLayerGroup) { + for (const key in this._parentLayerGroup) { const lg = this._parentLayerGroup[key]; - if(lg.pm) { + if (lg.pm) { layersToSync = lg.pm.getLayers(true); } } } } - if(L.Util.isArray(layersToSync) && layersToSync.length > 0) { + if (L.Util.isArray(layersToSync) && layersToSync.length > 0) { // filter out layers that don't have leaflet-geoman and not allowed to drag - layersToSync = layersToSync.filter(layer => !!layer.pm) - .filter(layer => !!layer.pm.options.draggable); + layersToSync = layersToSync + .filter((layer) => !!layer.pm) + .filter((layer) => !!layer.pm.options.draggable); layersToSync.forEach((layer) => { if (layer !== this._layer && layer.pm[fnc]) { layer._snapped = false; @@ -344,14 +364,14 @@ const DragMixin = { }); } return layersToSync.length > 0; - }else{ + } else { return false; } }, - _stopDOMImageDrag(e){ + _stopDOMImageDrag(e) { e.preventDefault(); return false; - } + }, }; export default DragMixin; diff --git a/src/js/Mixins/Events.js b/src/js/Mixins/Events.js index 1835246e..8da8cfea 100644 --- a/src/js/Mixins/Events.js +++ b/src/js/Mixins/Events.js @@ -3,316 +3,619 @@ import merge from 'lodash/merge'; const EventMixin = { // Draw Events // Fired when enableDraw() is called -> draw start - _fireDrawStart(source = "Draw", customPayload = {}){ - this.__fire(this._map,'pm:drawstart', { - shape: this._shape, - workingLayer: this._layer, - }, source, customPayload); + _fireDrawStart(source = 'Draw', customPayload = {}) { + this.__fire( + this._map, + 'pm:drawstart', + { + shape: this._shape, + workingLayer: this._layer, + }, + source, + customPayload + ); }, // Fired when disableDraw() is called -> draw stop - _fireDrawEnd(source = "Draw", customPayload = {}){ - this.__fire(this._map,'pm:drawend', { - shape: this._shape, - }, source, customPayload); + _fireDrawEnd(source = 'Draw', customPayload = {}) { + this.__fire( + this._map, + 'pm:drawend', + { + shape: this._shape, + }, + source, + customPayload + ); }, // Fired when layer is created while drawing - _fireCreate(layer, source = "Draw", customPayload = {}){ - this.__fire(this._map,'pm:create', { - shape: this._shape, - marker: layer, // TODO: Deprecated - layer, - }, source, customPayload); + _fireCreate(layer, source = 'Draw', customPayload = {}) { + this.__fire( + this._map, + 'pm:create', + { + shape: this._shape, + marker: layer, // TODO: Deprecated + layer, + }, + source, + customPayload + ); }, // Fired when Circle / CircleMarker center is placed // if source == "Draw" then `workingLayer` is passed else `layer` - _fireCenterPlaced(source = "Draw", customPayload = {}) { - const workingLayer = source === "Draw" ? this._layer : undefined; - const layer = source !== "Draw" ? this._layer : undefined; + _fireCenterPlaced(source = 'Draw', customPayload = {}) { + const workingLayer = source === 'Draw' ? this._layer : undefined; + const layer = source !== 'Draw' ? this._layer : undefined; - this.__fire(this._layer,'pm:centerplaced', { - shape: this._shape, - workingLayer, - layer, - latlng: this._layer.getLatLng(), - }, source, customPayload); + this.__fire( + this._layer, + 'pm:centerplaced', + { + shape: this._shape, + workingLayer, + layer, + latlng: this._layer.getLatLng(), + }, + source, + customPayload + ); }, // Fired when layer is cutted // TODO: is Cut "Draw" or "Edit"? The event `pm:edit` in the same scope is called as source "Edit" - _fireCut(fireLayer, layer, originalLayer, source = "Draw", customPayload = {}){ - this.__fire(fireLayer,'pm:cut', { - shape: this._shape, - layer, - originalLayer, - }, source, customPayload); + _fireCut( + fireLayer, + layer, + originalLayer, + source = 'Draw', + customPayload = {} + ) { + this.__fire( + fireLayer, + 'pm:cut', + { + shape: this._shape, + layer, + originalLayer, + }, + source, + customPayload + ); }, // Edit Events // Fired when layer is edited / changed - _fireEdit(fireLayer = this._layer, source = "Edit", customPayload = {}) { - this.__fire(fireLayer,'pm:edit', { layer: this._layer, shape: this.getShape() }, source, customPayload); + _fireEdit(fireLayer = this._layer, source = 'Edit', customPayload = {}) { + this.__fire( + fireLayer, + 'pm:edit', + { layer: this._layer, shape: this.getShape() }, + source, + customPayload + ); }, // Fired when layer is enabled for editing - _fireEnable(source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:enable', { layer: this._layer, shape: this.getShape() }, source, customPayload); + _fireEnable(source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:enable', + { layer: this._layer, shape: this.getShape() }, + source, + customPayload + ); }, // Fired when layer is disabled for editing - _fireDisable(source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:disable', { layer: this._layer, shape: this.getShape() }, source, customPayload); + _fireDisable(source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:disable', + { layer: this._layer, shape: this.getShape() }, + source, + customPayload + ); }, // Fired when layer is disabled and was edited / changed - _fireUpdate(source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:update', { layer: this._layer, shape: this.getShape() }, source, customPayload); + _fireUpdate(source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:update', + { layer: this._layer, shape: this.getShape() }, + source, + customPayload + ); }, // Fired when a vertex-marker is started dragging // indexPath is only passed from Line / Polygon - _fireMarkerDragStart(e, indexPath = undefined, source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:markerdragstart', { - layer: this._layer, - markerEvent: e, - shape: this.getShape(), - indexPath - }, source, customPayload); + _fireMarkerDragStart( + e, + indexPath = undefined, + source = 'Edit', + customPayload = {} + ) { + this.__fire( + this._layer, + 'pm:markerdragstart', + { + layer: this._layer, + markerEvent: e, + shape: this.getShape(), + indexPath, + }, + source, + customPayload + ); }, // Fired while dragging a vertex-marker // indexPath is only passed from Line / Polygon - _fireMarkerDrag(e, indexPath = undefined, source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:markerdrag', { - layer: this._layer, - markerEvent: e, - shape: this.getShape(), - indexPath - }, source, customPayload); + _fireMarkerDrag( + e, + indexPath = undefined, + source = 'Edit', + customPayload = {} + ) { + this.__fire( + this._layer, + 'pm:markerdrag', + { + layer: this._layer, + markerEvent: e, + shape: this.getShape(), + indexPath, + }, + source, + customPayload + ); }, // Fired when a vertex-marker is stopped dragging // indexPath and intersectionReset is only passed from Line / Polygon - _fireMarkerDragEnd(e, indexPath = undefined, intersectionReset = undefined, source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:markerdragend', { - layer: this._layer, - markerEvent: e, - shape: this.getShape(), - indexPath, - intersectionReset - }, source, customPayload); + _fireMarkerDragEnd( + e, + indexPath = undefined, + intersectionReset = undefined, + source = 'Edit', + customPayload = {} + ) { + this.__fire( + this._layer, + 'pm:markerdragend', + { + layer: this._layer, + markerEvent: e, + shape: this.getShape(), + indexPath, + intersectionReset, + }, + source, + customPayload + ); }, // Fired when a layer is started dragging - _fireDragStart(source = "Edit", customPayload = {}) { - this.__fire(this._layer,'pm:dragstart', { - layer: this._layer, - shape: this.getShape() - }, source, customPayload); + _fireDragStart(source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:dragstart', + { + layer: this._layer, + shape: this.getShape(), + }, + source, + customPayload + ); }, // Fired while dragging a layer - _fireDrag(e, source = "Edit", customPayload = {}) { - this.__fire(this._layer,'pm:drag', Object.assign({}, e, {shape:this.getShape()}), source, customPayload); + _fireDrag(e, source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:drag', + { ...e, shape: this.getShape() }, + source, + customPayload + ); }, // Fired when a layer is stopped dragging - _fireDragEnd(source = "Edit", customPayload = {}) { - this.__fire(this._layer,'pm:dragend', { - layer: this._layer, - shape: this.getShape() - }, source, customPayload); + _fireDragEnd(source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:dragend', + { + layer: this._layer, + shape: this.getShape(), + }, + source, + customPayload + ); }, // Fired when a layer is removed - _fireRemove(fireLayer,refLayer = fireLayer, source = "Edit", customPayload = {}){ - this.__fire(fireLayer,'pm:remove', { layer: refLayer, shape: this.getShape() }, source, customPayload); + _fireRemove( + fireLayer, + refLayer = fireLayer, + source = 'Edit', + customPayload = {} + ) { + this.__fire( + fireLayer, + 'pm:remove', + { layer: refLayer, shape: this.getShape() }, + source, + customPayload + ); }, // Fired when a vertex-marker is created - _fireVertexAdded(marker, indexPath, latlng, source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:vertexadded', { - layer: this._layer, - workingLayer: this._layer, - marker, - indexPath, - latlng, - shape: this.getShape() - }, source, customPayload); + _fireVertexAdded( + marker, + indexPath, + latlng, + source = 'Edit', + customPayload = {} + ) { + this.__fire( + this._layer, + 'pm:vertexadded', + { + layer: this._layer, + workingLayer: this._layer, + marker, + indexPath, + latlng, + shape: this.getShape(), + }, + source, + customPayload + ); }, // Fired when a vertex-marker is removed - _fireVertexRemoved(marker, indexPath, source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:vertexremoved', { - layer: this._layer, - marker, - indexPath, - shape: this.getShape() - // TODO: maybe add latlng as well? - }, source, customPayload); + _fireVertexRemoved(marker, indexPath, source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:vertexremoved', + { + layer: this._layer, + marker, + indexPath, + shape: this.getShape(), + // TODO: maybe add latlng as well? + }, + source, + customPayload + ); }, // Fired when a vertex-marker is clicked - _fireVertexClick(e, indexPath, source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:vertexclick', { - layer: this._layer, - markerEvent: e, - indexPath, - shape: this.getShape() - }, source, customPayload); + _fireVertexClick(e, indexPath, source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:vertexclick', + { + layer: this._layer, + markerEvent: e, + indexPath, + shape: this.getShape(), + }, + source, + customPayload + ); }, // Fired when a Line / Polygon has self intersection - _fireIntersect(intersection, source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:intersect', { - layer: this._layer, - intersection, - shape: this.getShape() - }, source, customPayload); + _fireIntersect(intersection, source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:intersect', + { + layer: this._layer, + intersection, + shape: this.getShape(), + }, + source, + customPayload + ); }, // Fired when a Line / Polygon is reset because of self intersection - _fireLayerReset(e, indexPath, source = "Edit", customPayload = {}){ - this.__fire(this._layer,'pm:layerreset', { - layer: this._layer, - markerEvent: e, - indexPath, - shape: this.getShape() - }, source, customPayload); + _fireLayerReset(e, indexPath, source = 'Edit', customPayload = {}) { + this.__fire( + this._layer, + 'pm:layerreset', + { + layer: this._layer, + markerEvent: e, + indexPath, + shape: this.getShape(), + }, + source, + customPayload + ); }, // Snapping Events // Fired during a marker move/drag and other layers are existing - _fireSnapDrag(fireLayer, eventInfo, source = "Snapping", customPayload = {}){ - this.__fire(fireLayer,'pm:snapdrag', eventInfo, source, customPayload); + _fireSnapDrag(fireLayer, eventInfo, source = 'Snapping', customPayload = {}) { + this.__fire(fireLayer, 'pm:snapdrag', eventInfo, source, customPayload); }, // Fired when a vertex is snapped - _fireSnap(fireLayer, eventInfo, source = "Snapping", customPayload = {}){ - this.__fire(fireLayer,'pm:snap', eventInfo, source, customPayload); + _fireSnap(fireLayer, eventInfo, source = 'Snapping', customPayload = {}) { + this.__fire(fireLayer, 'pm:snap', eventInfo, source, customPayload); }, // Fired when a vertex is unsnapped - _fireUnsnap(fireLayer, eventInfo, source = "Snapping", customPayload = {}){ - this.__fire(fireLayer,'pm:unsnap', eventInfo, source, customPayload); + _fireUnsnap(fireLayer, eventInfo, source = 'Snapping', customPayload = {}) { + this.__fire(fireLayer, 'pm:unsnap', eventInfo, source, customPayload); }, // Rotation Events // Fired when rotation is enabled - _fireRotationEnable(fireLayer, helpLayer, source = "Rotation", customPayload = {}){ - this.__fire(fireLayer,'pm:rotateenable', { - layer: this._layer, - helpLayer: this._rotatePoly - }, source, customPayload); + _fireRotationEnable( + fireLayer, + helpLayer, + source = 'Rotation', + customPayload = {} + ) { + this.__fire( + fireLayer, + 'pm:rotateenable', + { + layer: this._layer, + helpLayer: this._rotatePoly, + }, + source, + customPayload + ); }, // Fired when rotation is disabled - _fireRotationDisable(fireLayer, source = "Rotation", customPayload = {}){ - this.__fire(fireLayer,'pm:rotatedisable', { - layer: this._layer - }, source, customPayload); + _fireRotationDisable(fireLayer, source = 'Rotation', customPayload = {}) { + this.__fire( + fireLayer, + 'pm:rotatedisable', + { + layer: this._layer, + }, + source, + customPayload + ); }, // Fired when rotation starts - _fireRotationStart(fireLayer, originLatLngs, source = "Rotation", customPayload = {}){ - this.__fire(fireLayer,'pm:rotatestart', { - layer: this._rotationLayer, - helpLayer: this._layer, - startAngle: this._startAngle, - originLatLngs - }, source, customPayload); + _fireRotationStart( + fireLayer, + originLatLngs, + source = 'Rotation', + customPayload = {} + ) { + this.__fire( + fireLayer, + 'pm:rotatestart', + { + layer: this._rotationLayer, + helpLayer: this._layer, + startAngle: this._startAngle, + originLatLngs, + }, + source, + customPayload + ); }, // Fired while rotation - _fireRotation(fireLayer, angleDiff, oldLatLngs, source = "Rotation", customPayload = {}){ - this.__fire(fireLayer,'pm:rotate', { - layer: this._rotationLayer, - helpLayer: this._layer, - startAngle: this._startAngle, - angle: this._rotationLayer.pm.getAngle(), - angleDiff, - oldLatLngs, - newLatLngs: this._rotationLayer.getLatLngs() - }, source, customPayload); + _fireRotation( + fireLayer, + angleDiff, + oldLatLngs, + source = 'Rotation', + customPayload = {} + ) { + this.__fire( + fireLayer, + 'pm:rotate', + { + layer: this._rotationLayer, + helpLayer: this._layer, + startAngle: this._startAngle, + angle: this._rotationLayer.pm.getAngle(), + angleDiff, + oldLatLngs, + newLatLngs: this._rotationLayer.getLatLngs(), + }, + source, + customPayload + ); }, // Fired when rotation ends - _fireRotationEnd(fireLayer, startAngle, originLatLngs, source = "Rotation", customPayload = {}){ - this.__fire(fireLayer,'pm:rotateend', { - layer: this._rotationLayer, - helpLayer: this._layer, - startAngle, - angle: this._rotationLayer.pm.getAngle(), - originLatLngs, - newLatLngs: this._rotationLayer.getLatLngs() - }, source, customPayload); + _fireRotationEnd( + fireLayer, + startAngle, + originLatLngs, + source = 'Rotation', + customPayload = {} + ) { + this.__fire( + fireLayer, + 'pm:rotateend', + { + layer: this._rotationLayer, + helpLayer: this._layer, + startAngle, + angle: this._rotationLayer.pm.getAngle(), + originLatLngs, + newLatLngs: this._rotationLayer.getLatLngs(), + }, + source, + customPayload + ); }, // Global Events // Fired when a Toolbar action is clicked - _fireActionClick(action, btnName, button, source = "Toolbar", customPayload = {}){ + _fireActionClick( + action, + btnName, + button, + source = 'Toolbar', + customPayload = {} + ) { // this._map is used because this is fired from L.Controls (PMButton) - this.__fire(this._map,'pm:actionclick', { - text: action.text, - action, - btnName, - button - }, source, customPayload); + this.__fire( + this._map, + 'pm:actionclick', + { + text: action.text, + action, + btnName, + button, + }, + source, + customPayload + ); }, // Fired when a Toolbar button is clicked - _fireButtonClick(btnName, button, source = "Toolbar", customPayload = {}){ + _fireButtonClick(btnName, button, source = 'Toolbar', customPayload = {}) { // this._map is used because this is fired from L.Controls (PMButton) - this.__fire(this._map,'pm:buttonclick', {btnName, button}, source, customPayload); + this.__fire( + this._map, + 'pm:buttonclick', + { btnName, button }, + source, + customPayload + ); }, // Fired when language is changed - _fireLangChange(oldLang, activeLang, fallback, translations, source = "Global", customPayload = {} ){ - this.__fire(this.map,"pm:langchange", { - oldLang, - activeLang, - fallback, - translations - }, source, customPayload); + _fireLangChange( + oldLang, + activeLang, + fallback, + translations, + source = 'Global', + customPayload = {} + ) { + this.__fire( + this.map, + 'pm:langchange', + { + oldLang, + activeLang, + fallback, + translations, + }, + source, + customPayload + ); }, // Fired when Drag Mode is toggled. - _fireGlobalDragModeToggled(enabled, source = "Global", customPayload = {}) { - this.__fire(this.map,'pm:globaldragmodetoggled', { - enabled, - map: this.map, - }, source, customPayload); + _fireGlobalDragModeToggled(enabled, source = 'Global', customPayload = {}) { + this.__fire( + this.map, + 'pm:globaldragmodetoggled', + { + enabled, + map: this.map, + }, + source, + customPayload + ); }, // Fired when Edit Mode is toggled. - _fireGlobalEditModeToggled(enabled, source = "Global", customPayload = {}) { - this.__fire(this.map,'pm:globaleditmodetoggled', { - enabled, - map: this.map, - }, source, customPayload); + _fireGlobalEditModeToggled(enabled, source = 'Global', customPayload = {}) { + this.__fire( + this.map, + 'pm:globaleditmodetoggled', + { + enabled, + map: this.map, + }, + source, + customPayload + ); }, // Fired when Removal Mode is toggled. - _fireGlobalRemovalModeToggled(enabled, source = "Global", customPayload = {}) { - this.__fire(this.map,'pm:globalremovalmodetoggled', { - enabled, - map: this.map, - }, source, customPayload); + _fireGlobalRemovalModeToggled( + enabled, + source = 'Global', + customPayload = {} + ) { + this.__fire( + this.map, + 'pm:globalremovalmodetoggled', + { + enabled, + map: this.map, + }, + source, + customPayload + ); }, // Fired when Cut Mode is toggled. - _fireGlobalCutModeToggled(source = "Global", customPayload = {}){ - this.__fire(this._map,'pm:globalcutmodetoggled', { - enabled: !!this._enabled, - map: this._map, - }, source, customPayload); + _fireGlobalCutModeToggled(source = 'Global', customPayload = {}) { + this.__fire( + this._map, + 'pm:globalcutmodetoggled', + { + enabled: !!this._enabled, + map: this._map, + }, + source, + customPayload + ); }, // Fired when Draw Mode is toggled. - _fireGlobalDrawModeToggled(source = "Global", customPayload = {}){ - this.__fire(this._map,'pm:globaldrawmodetoggled', { - enabled: this._enabled, - shape: this._shape, - map: this._map, - }, source, customPayload); + _fireGlobalDrawModeToggled(source = 'Global', customPayload = {}) { + this.__fire( + this._map, + 'pm:globaldrawmodetoggled', + { + enabled: this._enabled, + shape: this._shape, + map: this._map, + }, + source, + customPayload + ); }, // Fired when Rotation Mode is toggled. - _fireGlobalRotateModeToggled(source = "Global", customPayload = {}){ - this.__fire(this.map,'pm:globalrotatemodetoggled', { - enabled: this.globalRotateModeEnabled(), - map: this.map, - }, source, customPayload); + _fireGlobalRotateModeToggled(source = 'Global', customPayload = {}) { + this.__fire( + this.map, + 'pm:globalrotatemodetoggled', + { + enabled: this.globalRotateModeEnabled(), + map: this.map, + }, + source, + customPayload + ); }, // Fired when LayerGroup is removed - _fireRemoveLayerGroup(fireLayer, refLayer = fireLayer, source = "Edit", customPayload = {}) { - this.__fire(fireLayer,'pm:remove', { layer: refLayer, shape: undefined }, source, customPayload); + _fireRemoveLayerGroup( + fireLayer, + refLayer = fireLayer, + source = 'Edit', + customPayload = {} + ) { + this.__fire( + fireLayer, + 'pm:remove', + { layer: refLayer, shape: undefined }, + source, + customPayload + ); }, // Fired when `keydown` or `keyup` on the document is fired. - _fireKeyeventEvent(event, eventType, focusOn, source = "Global", customPayload = {}){ - this.__fire(this.map,'pm:keyevent', { - event, - eventType, - focusOn - }, source, customPayload); + _fireKeyeventEvent( + event, + eventType, + focusOn, + source = 'Global', + customPayload = {} + ) { + this.__fire( + this.map, + 'pm:keyevent', + { + event, + eventType, + focusOn, + }, + source, + customPayload + ); }, - // private (very private) fire function - __fire(fireLayer, type, payload, source, customPayload = {}){ - payload = merge(payload, customPayload, {source}); - L.PM.Utils._fireEvent(fireLayer,type,payload); - } - + __fire(fireLayer, type, payload, source, customPayload = {}) { + payload = merge(payload, customPayload, { source }); + L.PM.Utils._fireEvent(fireLayer, type, payload); + }, }; export default EventMixin; diff --git a/src/js/Mixins/Keyboard.js b/src/js/Mixins/Keyboard.js index 9362554f..9156da8e 100644 --- a/src/js/Mixins/Keyboard.js +++ b/src/js/Mixins/Keyboard.js @@ -1,5 +1,5 @@ const KeyboardMixins = { - _lastEvents: {keydown: undefined, keyup: undefined, current: undefined}, + _lastEvents: { keydown: undefined, keyup: undefined, current: undefined }, _initKeyListener(map) { this.map = map; L.DomEvent.on(document, 'keydown keyup', this._onKeyListener, this); @@ -9,15 +9,15 @@ const KeyboardMixins = { // .contains only supported since IE9, if you want to use Geoman with IE8 or lower you need to implement a polyfill for .contains // with focusOn the user can add a check if the key was pressed while the user interacts with the map - if (this.map.getContainer().contains(e.target)){ + if (this.map.getContainer().contains(e.target)) { focusOn = 'map'; } - const data = {event: e, eventType: e.type, focusOn}; + const data = { event: e, eventType: e.type, focusOn }; this._lastEvents[e.type] = data; this._lastEvents.current = data; - this.map.pm._fireKeyeventEvent(e,e.type,focusOn); + this.map.pm._fireKeyeventEvent(e, e.type, focusOn); }, getLastKeyEvent(type = 'current') { return this._lastEvents[type]; @@ -34,9 +34,9 @@ const KeyboardMixins = { isMetaKeyPressed() { return this._lastEvents.current?.event.metaKey; }, - getPressedKey(){ + getPressedKey() { return this._lastEvents.current?.event.key; - } + }, }; export default KeyboardMixins; diff --git a/src/js/Mixins/MarkerLimits.js b/src/js/Mixins/MarkerLimits.js index e84d5f82..ea9b41a0 100644 --- a/src/js/Mixins/MarkerLimits.js +++ b/src/js/Mixins/MarkerLimits.js @@ -7,9 +7,7 @@ const MarkerLimits = { this.createCache(); // refresh cache when layer was edited (e.g. when a vertex was added or removed) - this._layer.on('pm:edit', this.createCache, this) - - + this._layer.on('pm:edit', this.createCache, this); // apply filter for the first time this.applyLimitFilters({}); @@ -17,21 +15,20 @@ const MarkerLimits = { // remove events when edit mode is disabled this._layer.on('pm:disable', this._removeMarkerLimitEvents, this); - // add markers closest to the mouse if (this.options.limitMarkersToCount > -1) { // re-init markers when a vertex is removed. // The reason is that syncing this cache with a removed marker was impossible to do - this._layer.on('pm:vertexremoved', this._initMarkers, this) + this._layer.on('pm:vertexremoved', this._initMarkers, this); this._map.on('mousemove', this.applyLimitFilters, this); } }, _removeMarkerLimitEvents() { this._map.off('mousemove', this.applyLimitFilters, this); - this._layer.off('pm:edit', this.createCache, this) + this._layer.off('pm:edit', this.createCache, this); this._layer.off('pm:disable', this._removeMarkerLimitEvents, this); - this._layer.off('pm:vertexremoved', this._initMarkers, this) + this._layer.off('pm:vertexremoved', this._initMarkers, this); }, createCache() { const allMarkers = [...this._markerGroup.getLayers(), ...this.markerCache]; @@ -40,18 +37,18 @@ const MarkerLimits = { renderLimits(markers) { this.markerCache.forEach((l) => { if (markers.includes(l)) { - this._markerGroup.addLayer(l) + this._markerGroup.addLayer(l); } else { - this._markerGroup.removeLayer(l) + this._markerGroup.removeLayer(l); } - }) + }); }, applyLimitFilters({ latlng = { lat: 0, lng: 0 } }) { - if(this._preventRenderMarkers){ + if (this._preventRenderMarkers) { return; } // find markers near the cursor - const makersNearCursor = this._filterClosestMarkers(latlng) + const makersNearCursor = this._filterClosestMarkers(latlng); // all markers that we want to show const markersToAdd = [...makersNearCursor]; @@ -68,17 +65,17 @@ const MarkerLimits = { const distanceB = t._latlng.distanceTo(latlng); return distanceA - distanceB; - }) + }); // reduce markers to number of limit - const closest = markers.filter((l, i) => limit > -1 ? i < limit : true) + const closest = markers.filter((l, i) => (limit > -1 ? i < limit : true)); return closest; }, _preventRenderMarkers: false, - _preventRenderingMarkers(value){ + _preventRenderingMarkers(value) { this._preventRenderMarkers = !!value; - } -} + }, +}; -export default MarkerLimits +export default MarkerLimits; diff --git a/src/js/Mixins/Modes/Mode.Drag.js b/src/js/Mixins/Modes/Mode.Drag.js index 073a784b..43cec353 100644 --- a/src/js/Mixins/Modes/Mode.Drag.js +++ b/src/js/Mixins/Modes/Mode.Drag.js @@ -5,12 +5,16 @@ const GlobalDragMode = { this._globalDragModeEnabled = true; - layers.forEach(layer => { + layers.forEach((layer) => { layer.pm.enableLayerDrag(); }); if (!this.throttledReInitDrag) { - this.throttledReInitDrag = L.Util.throttle(this.reinitGlobalDragMode, 100, this) + this.throttledReInitDrag = L.Util.throttle( + this.reinitGlobalDragMode, + 100, + this + ); } // add map handler @@ -26,7 +30,7 @@ const GlobalDragMode = { this._globalDragModeEnabled = false; - layers.forEach(layer => { + layers.forEach((layer) => { layer.pm.disableLayerDrag(); }); @@ -61,6 +65,6 @@ const GlobalDragMode = { this.enableGlobalDragMode(); } }, -} +}; -export default GlobalDragMode +export default GlobalDragMode; diff --git a/src/js/Mixins/Modes/Mode.Edit.js b/src/js/Mixins/Modes/Mode.Edit.js index 1e90a287..68a9c01b 100644 --- a/src/js/Mixins/Modes/Mode.Edit.js +++ b/src/js/Mixins/Modes/Mode.Edit.js @@ -12,12 +12,16 @@ const GlobalEditMode = { const layers = L.PM.Utils.findLayers(this.map); // enable all layers - layers.forEach(layer => { + layers.forEach((layer) => { layer.pm.enable(options); }); if (!this.throttledReInitEdit) { - this.throttledReInitEdit = L.Util.throttle(this.handleLayerAdditionInGlobalEditMode, 100, this) + this.throttledReInitEdit = L.Util.throttle( + this.handleLayerAdditionInGlobalEditMode, + 100, + this + ); } // save the added layers into the _addedLayers array, to read it later out @@ -37,7 +41,7 @@ const GlobalEditMode = { const layers = L.PM.Utils.findLayers(this.map); // disable all layers - layers.forEach(layer => { + layers.forEach((layer) => { layer.pm.disable(); }); @@ -70,7 +74,7 @@ const GlobalEditMode = { handleLayerAdditionInGlobalEditMode() { const layers = this._addedLayers; this._addedLayers = []; - layers.forEach((layer)=> { + layers.forEach((layer) => { // when global edit mode is enabled and a layer is added to the map, // enable edit for that layer if it's relevant @@ -81,13 +85,13 @@ const GlobalEditMode = { } if (this.globalEditModeEnabled()) { - layer.pm.enable({...this.globalOptions}); + layer.pm.enable({ ...this.globalOptions }); } }); }, - _layerAdded({layer}){ + _layerAdded({ layer }) { this._addedLayers.push(layer); }, }; -export default GlobalEditMode +export default GlobalEditMode; diff --git a/src/js/Mixins/Modes/Mode.Removal.js b/src/js/Mixins/Modes/Mode.Removal.js index 64bded04..7aa7ce16 100644 --- a/src/js/Mixins/Modes/Mode.Removal.js +++ b/src/js/Mixins/Modes/Mode.Removal.js @@ -3,7 +3,7 @@ const GlobalRemovalMode = { enableGlobalRemovalMode() { this._globalRemovalModeEnabled = true; // handle existing layers - this.map.eachLayer(layer => { + this.map.eachLayer((layer) => { if (this._isRelevantForRemoval(layer)) { layer.pm.disable(); layer.on('click', this.removeLayer, this); @@ -11,7 +11,11 @@ const GlobalRemovalMode = { }); if (!this.throttledReInitRemoval) { - this.throttledReInitRemoval = L.Util.throttle(this.reinitGlobalRemovalMode, 100, this) + this.throttledReInitRemoval = L.Util.throttle( + this.reinitGlobalRemovalMode, + 100, + this + ); } // handle layers that are added while in removal mode @@ -24,7 +28,7 @@ const GlobalRemovalMode = { }, disableGlobalRemovalMode() { this._globalRemovalModeEnabled = false; - this.map.eachLayer(layer => { + this.map.eachLayer((layer) => { layer.off('click', this.removeLayer, this); }); @@ -67,30 +71,31 @@ const GlobalRemovalMode = { const layer = e.target; // only remove layer, if it's handled by leaflet-geoman, // not a tempLayer and not currently being dragged - const removeable = this._isRelevantForRemoval(layer) && !layer.pm.dragging(); + const removeable = + this._isRelevantForRemoval(layer) && !layer.pm.dragging(); if (removeable) { layer.removeFrom(this.map.pm._getContainingLayer()); layer.remove(); - if(layer instanceof L.LayerGroup){ + if (layer instanceof L.LayerGroup) { this._fireRemoveLayerGroup(layer); this._fireRemoveLayerGroup(this.map, layer); - }else{ + } else { layer.pm._fireRemove(layer); layer.pm._fireRemove(this.map, layer); } } }, - _isRelevantForRemoval(layer){ - return layer.pm - && !(layer instanceof L.LayerGroup) - && ( - (!L.PM.optIn && !layer.options.pmIgnore) || // if optIn is not set / true and pmIgnore is not set / true (default) - (L.PM.optIn && layer.options.pmIgnore === false) // if optIn is true and pmIgnore is false - ) - && !layer._pmTempLayer - && layer.pm.options.allowRemoval - } + _isRelevantForRemoval(layer) { + return ( + layer.pm && + !(layer instanceof L.LayerGroup) && + ((!L.PM.optIn && !layer.options.pmIgnore) || // if optIn is not set / true and pmIgnore is not set / true (default) + (L.PM.optIn && layer.options.pmIgnore === false)) && // if optIn is true and pmIgnore is false + !layer._pmTempLayer && + layer.pm.options.allowRemoval + ); + }, }; -export default GlobalRemovalMode +export default GlobalRemovalMode; diff --git a/src/js/Mixins/Modes/Mode.Rotate.js b/src/js/Mixins/Modes/Mode.Rotate.js index d323e4a3..4f03b8d3 100644 --- a/src/js/Mixins/Modes/Mode.Rotate.js +++ b/src/js/Mixins/Modes/Mode.Rotate.js @@ -2,15 +2,21 @@ const GlobalRotateMode = { _globalRotateModeEnabled: false, enableGlobalRotateMode() { this._globalRotateModeEnabled = true; - const layers = L.PM.Utils.findLayers(this.map).filter(l => l instanceof L.Polyline); - layers.forEach(layer => { - if(this._isRelevantForRotate(layer)) { + const layers = L.PM.Utils.findLayers(this.map).filter( + (l) => l instanceof L.Polyline + ); + layers.forEach((layer) => { + if (this._isRelevantForRotate(layer)) { layer.pm.enableRotate(); } }); if (!this.throttledReInitRotate) { - this.throttledReInitRotate = L.Util.throttle(this._reinitGlobalRotateMode, 100, this) + this.throttledReInitRotate = L.Util.throttle( + this._reinitGlobalRotateMode, + 100, + this + ); } // handle layers that are added while in rotate mode this.map.on('layeradd', this.throttledReInitRotate, this); @@ -21,8 +27,10 @@ const GlobalRotateMode = { }, disableGlobalRotateMode() { this._globalRotateModeEnabled = false; - const layers = L.PM.Utils.findLayers(this.map).filter(l => l instanceof L.Polyline); - layers.forEach(layer => { + const layers = L.PM.Utils.findLayers(this.map).filter( + (l) => l instanceof L.Polyline + ); + layers.forEach((layer) => { layer.pm.disableRotate(); }); @@ -55,16 +63,15 @@ const GlobalRotateMode = { this.enableGlobalRotateMode(); } }, - _isRelevantForRotate(layer){ - return layer.pm - && !(layer instanceof L.LayerGroup) - && ( - (!L.PM.optIn && !layer.options.pmIgnore) || // if optIn is not set / true and pmIgnore is not set / true (default) - (L.PM.optIn && layer.options.pmIgnore === false) // if optIn is true and pmIgnore is false - ) - && !layer._pmTempLayer - && layer.pm.options.allowRotation - } - + _isRelevantForRotate(layer) { + return ( + layer.pm && + !(layer instanceof L.LayerGroup) && + ((!L.PM.optIn && !layer.options.pmIgnore) || // if optIn is not set / true and pmIgnore is not set / true (default) + (L.PM.optIn && layer.options.pmIgnore === false)) && // if optIn is true and pmIgnore is false + !layer._pmTempLayer && + layer.pm.options.allowRotation + ); + }, }; export default GlobalRotateMode; diff --git a/src/js/Mixins/Rotating.js b/src/js/Mixins/Rotating.js index c0ae5cd1..0bcd5177 100644 --- a/src/js/Mixins/Rotating.js +++ b/src/js/Mixins/Rotating.js @@ -1,5 +1,5 @@ -import {_convertLatLngs, _toPoint} from "../helpers/ModeHelper"; -import get from "lodash/get"; +import get from 'lodash/get'; +import { _convertLatLngs, _toPoint } from '../helpers/ModeHelper'; import { copyLatLngs } from '../helpers'; /** @@ -10,17 +10,20 @@ import { copyLatLngs } from '../helpers'; */ const RotateMixin = { - _onRotateStart(e){ + _onRotateStart(e) { // prevent that the limit Markers are calculated new this._preventRenderingMarkers(true); this._rotationOriginLatLng = this._getRotationCenter().clone(); - this._rotationOriginPoint = _toPoint(this._map,this._rotationOriginLatLng); - this._rotationStartPoint = _toPoint(this._map,e.target.getLatLng()); + this._rotationOriginPoint = _toPoint(this._map, this._rotationOriginLatLng); + this._rotationStartPoint = _toPoint(this._map, e.target.getLatLng()); // we need to store the initial latlngs so we can always re-calc from the origin latlngs this._initialRotateLatLng = copyLatLngs(this._layer); this._startAngle = this.getAngle(); - const originLatLngs = copyLatLngs(this._rotationLayer,this._rotationLayer.pm._rotateOrgLatLng); + const originLatLngs = copyLatLngs( + this._rotationLayer, + this._rotationLayer.pm._rotateOrgLatLng + ); this._fireRotationStart(this._rotationLayer, originLatLngs); this._fireRotationStart(this._map, originLatLngs); @@ -31,35 +34,52 @@ const RotateMixin = { const origin = this._rotationOriginPoint; // rotation diff angle (radiant) - const angleDiffRadiant = Math.atan2(position.y - origin.y, position.x - origin.x) - + const angleDiffRadiant = + Math.atan2(position.y - origin.y, position.x - origin.x) - Math.atan2(previous.y - origin.y, previous.x - origin.x); // rotate the temp polygon - this._layer.setLatLngs(this._rotateLayer(angleDiffRadiant, this._initialRotateLatLng, this._rotationOriginLatLng, L.PM.Matrix.init(), this._map)); + this._layer.setLatLngs( + this._rotateLayer( + angleDiffRadiant, + this._initialRotateLatLng, + this._rotationOriginLatLng, + L.PM.Matrix.init(), + this._map + ) + ); // move the helper markers const that = this; - function forEachLatLng(latlng,path = [], _i = -1){ - if(_i > -1) { + function forEachLatLng(latlng, path = [], _i = -1) { + if (_i > -1) { path.push(_i); } - if(L.Util.isArray(latlng[0])){ - latlng.forEach((x,i) => forEachLatLng(x,path.slice(), i)); - }else{ + if (L.Util.isArray(latlng[0])) { + latlng.forEach((x, i) => forEachLatLng(x, path.slice(), i)); + } else { const markers = get(that._markers, path); - latlng.forEach((_latlng,j)=>{ + latlng.forEach((_latlng, j) => { const marker = markers[j]; marker.setLatLng(_latlng); - }) + }); } } forEachLatLng(this._layer.getLatLngs()); const oldLatLngs = copyLatLngs(this._rotationLayer); // rotate the origin layer - this._rotationLayer.setLatLngs(this._rotateLayer(angleDiffRadiant, this._rotationLayer.pm._rotateOrgLatLng, this._rotationOriginLatLng, L.PM.Matrix.init(), this._map)); + this._rotationLayer.setLatLngs( + this._rotateLayer( + angleDiffRadiant, + this._rotationLayer.pm._rotateOrgLatLng, + this._rotationOriginLatLng, + L.PM.Matrix.init(), + this._map + ) + ); // convert the difference radiant to degrees and add it to the angle before rotation starts - let angleDiff = (angleDiffRadiant * 180 / Math.PI); + let angleDiff = (angleDiffRadiant * 180) / Math.PI; angleDiff = angleDiff < 0 ? angleDiff + 360 : angleDiff; const angle = angleDiff + this._startAngle; this._setAngle(angle); @@ -68,7 +88,7 @@ const RotateMixin = { this._fireRotation(this._rotationLayer, angleDiff, oldLatLngs); this._fireRotation(this._map, angleDiff, oldLatLngs); }, - _onRotateEnd(){ + _onRotateEnd() { const startAngle = this._startAngle; delete this._rotationOriginLatLng; delete this._rotationOriginPoint; @@ -76,55 +96,69 @@ const RotateMixin = { delete this._initialRotateLatLng; delete this._startAngle; - const originLatLngs = copyLatLngs(this._rotationLayer,this._rotationLayer.pm._rotateOrgLatLng); + const originLatLngs = copyLatLngs( + this._rotationLayer, + this._rotationLayer.pm._rotateOrgLatLng + ); // store the new latlngs this._rotationLayer.pm._rotateOrgLatLng = copyLatLngs(this._rotationLayer); - this._fireRotationEnd(this._rotationLayer,startAngle,originLatLngs); - this._fireRotationEnd(this._map,startAngle,originLatLngs); - this._rotationLayer.pm._fireEdit(this._rotationLayer,"Rotation"); + this._fireRotationEnd(this._rotationLayer, startAngle, originLatLngs); + this._fireRotationEnd(this._map, startAngle, originLatLngs); + this._rotationLayer.pm._fireEdit(this._rotationLayer, 'Rotation'); this._preventRenderingMarkers(false); }, - _rotateLayer(radiant, latlngs, origin, _matrix, map){ - const originPoint =_toPoint(map,origin); - this._matrix = _matrix - .clone() - .rotate(radiant, originPoint) - .flip(); + _rotateLayer(radiant, latlngs, origin, _matrix, map) { + const originPoint = _toPoint(map, origin); + this._matrix = _matrix.clone().rotate(radiant, originPoint).flip(); return _convertLatLngs(latlngs, this._matrix, map); }, - _setAngle(angle){ + _setAngle(angle) { angle = angle < 0 ? angle + 360 : angle; this._angle = angle % 360; }, - _getRotationCenter(){ - var polygon = L.polygon(this._layer.getLatLngs(),{stroke: false, fill: false, pmIgnore: true}).addTo(this._layer._map); + _getRotationCenter() { + const polygon = L.polygon(this._layer.getLatLngs(), { + stroke: false, + fill: false, + pmIgnore: true, + }).addTo(this._layer._map); const center = polygon.getCenter(); polygon.removeFrom(this._layer._map); return center; }, /* - * - * Public functions f.ex. to disable and enable rotation on the layer directly - * - */ - enableRotate(){ - - if(!this.options.allowRotation){ + * + * Public functions f.ex. to disable and enable rotation on the layer directly + * + */ + enableRotate() { + if (!this.options.allowRotation) { this.disableRotate(); return; } // We create an hidden polygon. We set pmIgnore to false, so that the `pm` property will be always create, also if OptIn == true - const options = {fill: false, stroke: false, pmIgnore: false, snapIgnore: true}; + const options = { + fill: false, + stroke: false, + pmIgnore: false, + snapIgnore: true, + }; // we create a temp polygon for rotation - this._rotatePoly = L.polygon(this._layer.getLatLngs(), options).addTo(this._layer._map); + this._rotatePoly = L.polygon(this._layer.getLatLngs(), options).addTo( + this._layer._map + ); this._rotatePoly.pm._setAngle(this.getAngle()); this._rotatePoly.pm.setOptions(this._layer._map.pm.getGlobalOptions()); - this._rotatePoly.pm.setOptions({rotate: true, snappable: false, hideMiddleMarkers: true}); + this._rotatePoly.pm.setOptions({ + rotate: true, + snappable: false, + hideMiddleMarkers: true, + }); // we connect the temp polygon (that will be enabled for rotation) with the current layer, so that we can rotate the current layer too this._rotatePoly.pm._rotationLayer = this._layer; this._rotatePoly.pm.enable(); @@ -138,12 +172,12 @@ const RotateMixin = { // we need to use this._layer._map because this._map can be undefined if layer was never enabled for editing before this._fireRotationEnable(this._layer._map); }, - disableRotate(){ - if(this.rotateEnabled()){ + disableRotate() { + if (this.rotateEnabled()) { // delete the temp polygon this._rotatePoly.pm.disable(); this._rotatePoly.remove(); - this._rotatePoly.pm.setOptions({rotate: false}); + this._rotatePoly.pm.setOptions({ rotate: false }); this._rotatePoly = undefined; this._rotateOrgLatLng = undefined; @@ -154,29 +188,49 @@ const RotateMixin = { this._fireRotationDisable(this._layer._map); } }, - rotateEnabled(){ + rotateEnabled() { return this._rotateEnabled; }, // angle is clockwise (0-360) - rotateLayer(angle){ + rotateLayer(angle) { const rads = angle * (Math.PI / 180); - this._layer.setLatLngs(this._rotateLayer(rads,this._layer.getLatLngs(), this._getRotationCenter(), L.PM.Matrix.init(), this._layer._map)); + this._layer.setLatLngs( + this._rotateLayer( + rads, + this._layer.getLatLngs(), + this._getRotationCenter(), + L.PM.Matrix.init(), + this._layer._map + ) + ); // store the new latlngs this._rotateOrgLatLng = L.polygon(this._layer.getLatLngs()).getLatLngs(); this._setAngle(this.getAngle() + angle); - if(this.rotateEnabled() && this._rotatePoly && this._rotatePoly.pm.enabled()){ - this._rotatePoly.setLatLngs(this._rotateLayer(rads,this._rotatePoly.getLatLngs(), this._getRotationCenter(), L.PM.Matrix.init(), this._rotatePoly._map)); + if ( + this.rotateEnabled() && + this._rotatePoly && + this._rotatePoly.pm.enabled() + ) { + this._rotatePoly.setLatLngs( + this._rotateLayer( + rads, + this._rotatePoly.getLatLngs(), + this._getRotationCenter(), + L.PM.Matrix.init(), + this._rotatePoly._map + ) + ); this._rotatePoly.pm._initMarkers(); } }, - rotateLayerToAngle(angle){ + rotateLayerToAngle(angle) { const newAnlge = angle - this.getAngle(); this.rotateLayer(newAnlge); }, // angle is clockwise (0-360) - getAngle(){ + getAngle() { return this._angle || 0; - } + }, }; export default RotateMixin; diff --git a/src/js/Mixins/Snapping.js b/src/js/Mixins/Snapping.js index a8b695fc..19331914 100644 --- a/src/js/Mixins/Snapping.js +++ b/src/js/Mixins/Snapping.js @@ -1,9 +1,10 @@ -import {isEmptyDeep, prioritiseSort} from "../helpers"; +import { isEmptyDeep, prioritiseSort } from '../helpers'; const SnapMixin = { _initSnappableMarkers() { this.options.snapDistance = this.options.snapDistance || 30; - this.options.snapSegment = this.options.snapSegment === undefined ? true : this.options.snapSegment; + this.options.snapSegment = + this.options.snapSegment === undefined ? true : this.options.snapSegment; this._assignEvents(this._markers); @@ -15,7 +16,7 @@ const SnapMixin = { }, _assignEvents(markerArr) { // loop through marker array and assign events to the markers - markerArr.forEach(marker => { + markerArr.forEach((marker) => { // if the marker is another array (Multipolygon stuff), recursively do this again if (Array.isArray(marker)) { this._assignEvents(marker); @@ -45,25 +46,28 @@ const SnapMixin = { this._map.off('pm:remove', this._handleSnapLayerRemoval, this); if (this.debugIndicatorLines) { - this.debugIndicatorLines.forEach(line => { + this.debugIndicatorLines.forEach((line) => { line.remove(); }); } }, - _handleThrottleSnapping(){ + _handleThrottleSnapping() { // we check if the throttledList is existing, else the function is deleted but the `layeradd` event calls it. // this made problems when layer was removed and added to the map in the `pm:create` event - if(this.throttledList){ + if (this.throttledList) { this._createSnapList(); } }, _handleSnapping(e) { - const marker = e.target; marker._snapped = false; if (!this.throttledList) { - this.throttledList = L.Util.throttle(this._handleThrottleSnapping, 100, this); + this.throttledList = L.Util.throttle( + this._handleThrottleSnapping, + 100, + this + ); } // if snapping is disabled via holding ALT during drag, stop right here @@ -87,7 +91,6 @@ const SnapMixin = { return false; } - // get the closest layer, it's closest latlng, segment and the distance const closestLayer = this._calcClosestLayer( marker.getLatLng(), @@ -178,7 +181,7 @@ const SnapMixin = { // find all layers that are or inherit from Polylines... and markers that are not // temporary markers of polygon-edits - map.eachLayer(layer => { + map.eachLayer((layer) => { if ( (layer instanceof L.Polyline || layer instanceof L.Marker || @@ -186,18 +189,21 @@ const SnapMixin = { layer instanceof L.ImageOverlay) && layer.options.snapIgnore !== true ) { - // if snapIgnore === false the layer will be always snappable - if(layer.options.snapIgnore === undefined && ( - (!L.PM.optIn && layer.options.pmIgnore === true) || // if optIn is not set and pmIgnore is true, the layer will be ignored - (L.PM.optIn && layer.options.pmIgnore !== false) // if optIn is true and pmIgnore is not false, the layer will be ignored - ) - ){ + if ( + layer.options.snapIgnore === undefined && + ((!L.PM.optIn && layer.options.pmIgnore === true) || // if optIn is not set and pmIgnore is true, the layer will be ignored + (L.PM.optIn && layer.options.pmIgnore !== false)) // if optIn is true and pmIgnore is not false, the layer will be ignored + ) { return; } // adds a hidden polygon which matches the border of the circle - if ((layer instanceof L.Circle || layer instanceof L.CircleMarker) && layer.pm && layer.pm._hiddenPolyCircle) { + if ( + (layer instanceof L.Circle || layer instanceof L.CircleMarker) && + layer.pm && + layer.pm._hiddenPolyCircle + ) { layers.push(layer.pm._hiddenPolyCircle); } else if (layer instanceof L.ImageOverlay) { layer = L.rectangle(layer.getBounds()); @@ -205,7 +211,7 @@ const SnapMixin = { layers.push(layer); // this is for debugging - const debugLine = L.polyline([], {color: 'red', pmIgnore: true}); + const debugLine = L.polyline([], { color: 'red', pmIgnore: true }); debugLine._pmTempLayer = true; debugIndicatorLines.push(debugLine); if (layer instanceof L.Circle || layer instanceof L.CircleMarker) { @@ -218,24 +224,25 @@ const SnapMixin = { }); // ...except myself - layers = layers.filter(layer => this._layer !== layer); + layers = layers.filter((layer) => this._layer !== layer); // also remove everything that has no coordinates yet layers = layers.filter( - layer => layer._latlng || (layer._latlngs && !isEmptyDeep(layer._latlngs)) + (layer) => + layer._latlng || (layer._latlngs && !isEmptyDeep(layer._latlngs)) ); // finally remove everything that's leaflet-geoman specific temporary stuff - layers = layers.filter(layer => !layer._pmTempLayer); + layers = layers.filter((layer) => !layer._pmTempLayer); // save snaplist from layers and the other snap layers added from other classes/scripts if (this._otherSnapLayers) { - this._otherSnapLayers.forEach(()=>{ + this._otherSnapLayers.forEach(() => { // this is for debugging - const debugLine = L.polyline([], {color: 'red', pmIgnore: true}); + const debugLine = L.polyline([], { color: 'red', pmIgnore: true }); debugLine._pmTempLayer = true; debugIndicatorLines.push(debugLine); - }) + }); this._snapList = layers.concat(this._otherSnapLayers); } else { this._snapList = layers; @@ -243,10 +250,10 @@ const SnapMixin = { this.debugIndicatorLines = debugIndicatorLines; }, - _handleSnapLayerRemoval({layer}) { + _handleSnapLayerRemoval({ layer }) { // find the layers index in snaplist const index = this._snapList.findIndex( - e => e._leaflet_id === layer._leaflet_id + (e) => e._leaflet_id === layer._leaflet_id ); // remove it from the snaplist this._snapList.splice(index, 1); @@ -265,7 +272,7 @@ const SnapMixin = { // find the closest latlng, segment and the distance of this layer to the dragged marker latlng const results = this._calcLayerDistances(latlng, layer); - if(this.debugIndicatorLines[index]) { + if (this.debugIndicatorLines[index]) { // show indicator lines, it's for debugging this.debugIndicatorLines[index].setLatLngs([latlng, results.latlng]); } @@ -307,7 +314,7 @@ const SnapMixin = { if (isMarker) { // return the info for the marker, no more calculations needed return { - latlng: Object.assign({}, latlngs), + latlng: { ...latlngs }, distance: this._getDistance(map, latlngs, P), }; } @@ -321,7 +328,7 @@ const SnapMixin = { // the closest segment (line between two points) of the layer let closestSegment; - const loopThroughCoords = coords => { + const loopThroughCoords = (coords) => { coords.forEach((coord, index) => { if (Array.isArray(coord)) { loopThroughCoords(coord); @@ -351,23 +358,24 @@ const SnapMixin = { closestSegment = [A, B]; } } - - }else{ + } else { // Only snap on the coords const distancePoint = this._getDistance(map, P, coord); - if (shortestDistance === undefined || distancePoint < shortestDistance) { + if ( + shortestDistance === undefined || + distancePoint < shortestDistance + ) { shortestDistance = distancePoint; closestCoord = coord; } } - }); }; loopThroughCoords(latlngs); - if(this.options.snapSegment){ + if (this.options.snapSegment) { // now, take the closest segment (closestSegment) and calc the closest point to P on it. const C = this._getClosestPointOnSegment( map, @@ -378,7 +386,7 @@ const SnapMixin = { // return the latlng of that sucker return { - latlng: Object.assign({}, C), + latlng: { ...C }, segment: closestSegment, distance: shortestDistance, }; @@ -389,13 +397,19 @@ const SnapMixin = { latlng: closestCoord, distance: shortestDistance, }; - }, _getClosestLayerByPriority(layers) { // sort the layers by creation, so it is snapping to the oldest layer from the same shape layers = layers.sort((a, b) => a._leaflet_id - b._leaflet_id); - const shapes = ['Marker', 'CircleMarker', 'Circle', 'Line', 'Polygon', 'Rectangle']; + const shapes = [ + 'Marker', + 'CircleMarker', + 'Circle', + 'Line', + 'Polygon', + 'Rectangle', + ]; const order = this._map.pm.globalOptions.snappingOrder || []; let lastIndex = 0; @@ -462,7 +476,7 @@ const SnapMixin = { } // return the copy of snapping point - return Object.assign({}, snapLatlng); + return { ...snapLatlng }; }, _unsnap() { // delete the last snap diff --git a/src/js/Toolbar/L.Controls.js b/src/js/Toolbar/L.Controls.js index c62537b0..009d176b 100644 --- a/src/js/Toolbar/L.Controls.js +++ b/src/js/Toolbar/L.Controls.js @@ -1,5 +1,5 @@ import { getTranslation } from '../helpers'; -import EventMixin from "../Mixins/Events"; +import EventMixin from '../Mixins/Events'; const PMButton = L.Control.extend({ includes: [EventMixin], @@ -9,7 +9,7 @@ const PMButton = L.Control.extend({ // TODO: clean up variable names like _button should be _options and that domNodeVariable stuff initialize(options) { // replaced setOptions with this because classNames returned undefined 🤔 - this._button = Object.assign({}, this.options, options); + this._button = { ...this.options, ...options }; }, onAdd(map) { this._map = map; @@ -24,7 +24,9 @@ const PMButton = L.Control.extend({ this._container = this._map.pm.Toolbar.drawContainer; } } else { - this._container = this._map.pm.Toolbar._createContainer(this.options.position); + this._container = this._map.pm.Toolbar._createContainer( + this.options.position + ); } this.buttonsDomNode = this._makeButton(this._button); this._container.appendChild(this.buttonsDomNode); @@ -63,7 +65,7 @@ const PMButton = L.Control.extend({ this.toggle(false); }, _triggerClick(e) { - if(e) { + if (e) { // is needed to prevent scrolling when clicking on a-element with href="a" e.preventDefault(); } @@ -73,7 +75,7 @@ const PMButton = L.Control.extend({ this._button.afterClick(e, { button: this, event: e }); }, _makeButton(button) { - const pos = this.options.position.indexOf("right") > -1 ? "pos-right" : ""; + const pos = this.options.position.indexOf('right') > -1 ? 'pos-right' : ''; // button container const buttonContainer = L.DomUtil.create( @@ -88,8 +90,8 @@ const PMButton = L.Control.extend({ 'leaflet-buttons-control-button', buttonContainer ); - newButton.setAttribute('role','button'); - newButton.setAttribute('tabindex','0'); + newButton.setAttribute('role', 'button'); + newButton.setAttribute('tabindex', '0'); newButton.href = '#'; // the buttons actions @@ -128,8 +130,8 @@ const PMButton = L.Control.extend({ }, }; - activeActions.forEach(_action => { - const name = typeof _action === "string" ? _action : _action.name; + activeActions.forEach((_action) => { + const name = typeof _action === 'string' ? _action : _action.name; let action; if (actions[name]) { action = actions[name]; @@ -143,19 +145,19 @@ const PMButton = L.Control.extend({ `leaflet-pm-action ${pos} action-${name}`, actionContainer ); - actionNode.setAttribute('role','button'); - actionNode.setAttribute('tabindex','0'); + actionNode.setAttribute('role', 'button'); + actionNode.setAttribute('tabindex', '0'); actionNode.href = '#'; actionNode.innerHTML = action.text; - if(!button.disabled) { + if (!button.disabled) { if (action.onClick) { const actionClick = (e) => { // is needed to prevent scrolling when clicking on a-element with href="a" e.preventDefault(); - let btnName = ""; - const {buttons} = this._map.pm.Toolbar; + let btnName = ''; + const { buttons } = this._map.pm.Toolbar; for (const btn in buttons) { if (buttons[btn]._button === button) { btnName = btn; @@ -188,15 +190,15 @@ const PMButton = L.Control.extend({ if (button.className) { L.DomUtil.addClass(image, button.className); } - if(!button.disabled) { + if (!button.disabled) { // before the actual click, trigger a click on currently toggled buttons to // untoggle them and their functionality L.DomEvent.addListener(newButton, 'click', () => { if (this._button.disableOtherButtons) { this._map.pm.Toolbar.triggerClickOnToggledButtons(this); } - let btnName = ""; - const {buttons} = this._map.pm.Toolbar; + let btnName = ''; + const { buttons } = this._map.pm.Toolbar; for (const btn in buttons) { if (buttons[btn]._button === button) { btnName = btn; @@ -208,7 +210,7 @@ const PMButton = L.Control.extend({ L.DomEvent.addListener(newButton, 'click', this._triggerClick, this); } - if(button.disabled){ + if (button.disabled) { L.DomUtil.addClass(newButton, 'pm-disabled'); L.DomUtil.addClass(image, 'pm-disabled'); } diff --git a/src/js/Toolbar/L.PM.Toolbar.js b/src/js/Toolbar/L.PM.Toolbar.js index 0b1030be..c0672bec 100644 --- a/src/js/Toolbar/L.PM.Toolbar.js +++ b/src/js/Toolbar/L.PM.Toolbar.js @@ -29,7 +29,7 @@ const Toolbar = L.Class.extend({ edit: '', options: '', custom: '', - } + }, }, customButtons: [], initialize(map) { @@ -69,9 +69,9 @@ const Toolbar = L.Class.extend({ this._defineButtons(); }, - _createContainer(name){ + _createContainer(name) { const container = `${name}Container`; - if(!this[container]) { + if (!this[container]) { this[container] = L.DomUtil.create( 'div', `leaflet-pm-toolbar leaflet-pm-${name} leaflet-bar leaflet-control` @@ -162,7 +162,7 @@ const Toolbar = L.Class.extend({ // the options toolbar should not be disabled during the different modes // TODO: probably need to abstract this a bit so different options are automatically // disabled for different modes, like pinning for circles - const exceptOptionButtons = ['snappingOption'] + const exceptOptionButtons = ['snappingOption']; for (const name in this.buttons) { if ( @@ -205,7 +205,7 @@ const Toolbar = L.Class.extend({ className: 'control-icon leaflet-pm-icon-marker', title: getTranslation('buttonTitles.drawMarkerButton'), jsClass: 'Marker', - onClick: () => { }, + onClick: () => {}, afterClick: (e, ctx) => { // toggle drawing mode this.map.pm.Draw[ctx.button._button.jsClass].toggle(); @@ -221,7 +221,7 @@ const Toolbar = L.Class.extend({ title: getTranslation('buttonTitles.drawPolyButton'), className: 'control-icon leaflet-pm-icon-polygon', jsClass: 'Polygon', - onClick: () => { }, + onClick: () => {}, afterClick: (e, ctx) => { // toggle drawing mode this.map.pm.Draw[ctx.button._button.jsClass].toggle(); @@ -237,7 +237,7 @@ const Toolbar = L.Class.extend({ className: 'control-icon leaflet-pm-icon-polyline', title: getTranslation('buttonTitles.drawLineButton'), jsClass: 'Line', - onClick: () => { }, + onClick: () => {}, afterClick: (e, ctx) => { // toggle drawing mode this.map.pm.Draw[ctx.button._button.jsClass].toggle(); @@ -253,7 +253,7 @@ const Toolbar = L.Class.extend({ title: getTranslation('buttonTitles.drawCircleButton'), className: 'control-icon leaflet-pm-icon-circle', jsClass: 'Circle', - onClick: () => { }, + onClick: () => {}, afterClick: (e, ctx) => { // toggle drawing mode this.map.pm.Draw[ctx.button._button.jsClass].toggle(); @@ -269,7 +269,7 @@ const Toolbar = L.Class.extend({ title: getTranslation('buttonTitles.drawCircleMarkerButton'), className: 'control-icon leaflet-pm-icon-circle-marker', jsClass: 'CircleMarker', - onClick: () => { }, + onClick: () => {}, afterClick: (e, ctx) => { // toggle drawing mode this.map.pm.Draw[ctx.button._button.jsClass].toggle(); @@ -285,7 +285,7 @@ const Toolbar = L.Class.extend({ title: getTranslation('buttonTitles.drawRectButton'), className: 'control-icon leaflet-pm-icon-rectangle', jsClass: 'Rectangle', - onClick: () => { }, + onClick: () => {}, afterClick: (e, ctx) => { // toggle drawing mode this.map.pm.Draw[ctx.button._button.jsClass].toggle(); @@ -300,7 +300,7 @@ const Toolbar = L.Class.extend({ const editButton = { title: getTranslation('buttonTitles.editButton'), className: 'control-icon leaflet-pm-icon-edit', - onClick: () => { }, + onClick: () => {}, afterClick: () => { this.map.pm.toggleGlobalEditMode(); }, @@ -315,7 +315,7 @@ const Toolbar = L.Class.extend({ const dragButton = { title: getTranslation('buttonTitles.dragButton'), className: 'control-icon leaflet-pm-icon-drag', - onClick: () => { }, + onClick: () => {}, afterClick: () => { this.map.pm.toggleGlobalDragMode(); }, @@ -331,7 +331,7 @@ const Toolbar = L.Class.extend({ title: getTranslation('buttonTitles.cutButton'), className: 'control-icon leaflet-pm-icon-cut', jsClass: 'Cut', - onClick: () => { }, + onClick: () => {}, afterClick: (e, ctx) => { // enable polygon drawing mode without snap this.map.pm.Draw[ctx.button._button.jsClass].toggle({ @@ -351,7 +351,7 @@ const Toolbar = L.Class.extend({ const deleteButton = { title: getTranslation('buttonTitles.deleteButton'), className: 'control-icon leaflet-pm-icon-delete', - onClick: () => { }, + onClick: () => {}, afterClick: () => { this.map.pm.toggleGlobalRemovalMode(); }, @@ -366,7 +366,7 @@ const Toolbar = L.Class.extend({ const rotateButton = { title: getTranslation('buttonTitles.rotateButton'), className: 'control-icon leaflet-pm-icon-rotate', - onClick: () => { }, + onClick: () => {}, afterClick: () => { this.map.pm.toggleGlobalRotateMode(); }, @@ -383,7 +383,10 @@ const Toolbar = L.Class.extend({ this._addButton('drawRectangle', new L.Control.PMButton(drawRectButton)); this._addButton('drawPolygon', new L.Control.PMButton(drawPolyButton)); this._addButton('drawCircle', new L.Control.PMButton(drawCircleButton)); - this._addButton('drawCircleMarker', new L.Control.PMButton(drawCircleMarkerButton)); + this._addButton( + 'drawCircleMarker', + new L.Control.PMButton(drawCircleMarkerButton) + ); this._addButton('editMode', new L.Control.PMButton(editButton)); this._addButton('dragMode', new L.Control.PMButton(dragButton)); this._addButton('cutPolygon', new L.Control.PMButton(cutButton)); @@ -400,23 +403,37 @@ const Toolbar = L.Class.extend({ let ignoreBtns = []; if (this.options.drawControls === false) { - ignoreBtns = ignoreBtns.concat(Object.keys(buttons).filter(btn => !buttons[btn]._button.tool)); + ignoreBtns = ignoreBtns.concat( + Object.keys(buttons).filter((btn) => !buttons[btn]._button.tool) + ); } if (this.options.editControls === false) { - ignoreBtns = ignoreBtns.concat(Object.keys(buttons).filter(btn => buttons[btn]._button.tool === 'edit')); + ignoreBtns = ignoreBtns.concat( + Object.keys(buttons).filter( + (btn) => buttons[btn]._button.tool === 'edit' + ) + ); } if (this.options.optionsControls === false) { - ignoreBtns = ignoreBtns.concat(Object.keys(buttons).filter(btn => buttons[btn]._button.tool === 'options')); + ignoreBtns = ignoreBtns.concat( + Object.keys(buttons).filter( + (btn) => buttons[btn]._button.tool === 'options' + ) + ); } if (this.options.customControls === false) { - ignoreBtns = ignoreBtns.concat(Object.keys(buttons).filter(btn => buttons[btn]._button.tool === 'custom')); + ignoreBtns = ignoreBtns.concat( + Object.keys(buttons).filter( + (btn) => buttons[btn]._button.tool === 'custom' + ) + ); } for (const btn in buttons) { if (this.options[btn] && ignoreBtns.indexOf(btn) === -1) { // if options say the button should be visible, add it to the map let block = buttons[btn]._button.tool; - if(!block) { + if (!block) { // undefined is the draw block block = 'draw'; } @@ -425,64 +442,59 @@ const Toolbar = L.Class.extend({ } } }, - _getBtnPosition(block){ - return this.options.positions && this.options.positions[block] ? this.options.positions[block] : this.options.position; + _getBtnPosition(block) { + return this.options.positions && this.options.positions[block] + ? this.options.positions[block] + : this.options.position; }, - setBlockPosition(block,position){ + setBlockPosition(block, position) { this.options.positions[block] = position; this._showHideButtons(); this.changeControlOrder(); }, - getBlockPositions(){ + getBlockPositions() { return this.options.positions; }, copyDrawControl(copyInstance, options) { - if (!options) { - throw new TypeError( - "Button has no name" - ); - } else if (typeof options !== 'object') { // if only the name is passed and no options object + throw new TypeError('Button has no name'); + } else if (typeof options !== 'object') { + // if only the name is passed and no options object options = { name: options }; } const instance = this._btnNameMapping(copyInstance); if (!options.name) { - throw new TypeError( - "Button has no name" - ); + throw new TypeError('Button has no name'); } if (this.buttons[options.name]) { - throw new TypeError( - "Button with this name already exists" - ) + throw new TypeError('Button with this name already exists'); } - const drawInstance = this.map.pm.Draw.createNewDrawInstance(options.name, instance); + const drawInstance = this.map.pm.Draw.createNewDrawInstance( + options.name, + instance + ); const btn = this.buttons[instance]._button; - options = Object.assign({}, btn, options); + options = { ...btn, ...options }; const control = this.createCustomControl(options); return { drawInstance, control }; }, createCustomControl(options) { if (!options.name) { - throw new TypeError( - "Button has no name" - ); + throw new TypeError('Button has no name'); } if (this.buttons[options.name]) { - throw new TypeError( - "Button with this name already exists" - ) + throw new TypeError('Button with this name already exists'); } if (!options.onClick) { - options.onClick = () => { }; + options.onClick = () => {}; } if (!options.afterClick) { - options.afterClick = () => { }; + options.afterClick = () => {}; } if (options.toggle !== false) { options.toggle = true; @@ -491,13 +503,13 @@ const Toolbar = L.Class.extend({ if (options.block) { options.block = options.block.toLowerCase(); } - if (!options.block || options.block === "draw") { - options.block = ""; + if (!options.block || options.block === 'draw') { + options.block = ''; } - if (!options.className){ + if (!options.className) { options.className = 'control-icon'; - }else if(options.className.indexOf('control-icon') === -1) { + } else if (options.className.indexOf('control-icon') === -1) { options.className = `control-icon ${options.className}`; } @@ -521,7 +533,10 @@ const Toolbar = L.Class.extend({ this.options[options.name] = true; } - const control = this._addButton(options.name, new L.Control.PMButton(_options)); + const control = this._addButton( + options.name, + new L.Control.PMButton(_options) + ); this.changeControlOrder(); return control; }, @@ -548,25 +563,33 @@ const Toolbar = L.Class.extend({ } }); - const drawBtns = Object.keys(buttons).filter(btn => !buttons[btn]._button.tool); + const drawBtns = Object.keys(buttons).filter( + (btn) => !buttons[btn]._button.tool + ); drawBtns.forEach((btn) => { if (_order.indexOf(btn) === -1) { newbtnorder[btn] = buttons[btn]; } }); - const editBtns = Object.keys(buttons).filter(btn => buttons[btn]._button.tool === "edit"); + const editBtns = Object.keys(buttons).filter( + (btn) => buttons[btn]._button.tool === 'edit' + ); editBtns.forEach((btn) => { if (_order.indexOf(btn) === -1) { newbtnorder[btn] = buttons[btn]; } }); - const optionsBtns = Object.keys(buttons).filter(btn => buttons[btn]._button.tool === "options"); + const optionsBtns = Object.keys(buttons).filter( + (btn) => buttons[btn]._button.tool === 'options' + ); optionsBtns.forEach((btn) => { if (_order.indexOf(btn) === -1) { newbtnorder[btn] = buttons[btn]; } }); - const customBtns = Object.keys(buttons).filter(btn => buttons[btn]._button.tool === "custom"); + const customBtns = Object.keys(buttons).filter( + (btn) => buttons[btn]._button.tool === 'custom' + ); customBtns.forEach((btn) => { if (_order.indexOf(btn) === -1) { newbtnorder[btn] = buttons[btn]; @@ -594,49 +617,43 @@ const Toolbar = L.Class.extend({ const btnName = this._btnNameMapping(name); if (!btnName) { - throw new TypeError( - "No name passed" - ); + throw new TypeError('No name passed'); } if (!actions) { - throw new TypeError( - "No actions passed" - ); + throw new TypeError('No actions passed'); } if (!this.buttons[btnName]) { - throw new TypeError( - "Button with this name not exists" - ) + throw new TypeError('Button with this name not exists'); } this.buttons[btnName]._button.actions = actions; this.changeControlOrder(); }, - setButtonDisabled(name,state){ + setButtonDisabled(name, state) { const btnName = this._btnNameMapping(name); this.buttons[btnName]._button.disabled = !!state; this._showHideButtons(); }, - _shapeMapping(){ + _shapeMapping() { return { - "Marker": "drawMarker", - "Circle": "drawCircle", - "Polygon": "drawPolygon", - "Rectangle": "drawRectangle", - "Polyline": "drawPolyline", - "Line": "drawPolyline", - "CircleMarker": "drawCircleMarker", - "Edit": "editMode", - "Drag": "dragMode", - "Cut": "cutPolygon", - "Removal": "removalMode", - "Rotate": "rotateMode", - } + Marker: 'drawMarker', + Circle: 'drawCircle', + Polygon: 'drawPolygon', + Rectangle: 'drawRectangle', + Polyline: 'drawPolyline', + Line: 'drawPolyline', + CircleMarker: 'drawCircleMarker', + Edit: 'editMode', + Drag: 'dragMode', + Cut: 'cutPolygon', + Removal: 'removalMode', + Rotate: 'rotateMode', + }; }, - _btnNameMapping(name){ + _btnNameMapping(name) { const shapeMapping = this._shapeMapping(); return shapeMapping[name] ? shapeMapping[name] : name; - } + }, }); export default Toolbar; diff --git a/src/js/helpers/Matrix.js b/src/js/helpers/Matrix.js index 0a1011b2..8cc9cc97 100644 --- a/src/js/helpers/Matrix.js +++ b/src/js/helpers/Matrix.js @@ -4,7 +4,6 @@ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ - /** * @class L.PM.Matrix * @@ -15,14 +14,14 @@ * @param {Number} e * @param {Number} f */ -const Matrix = function(a, b, c, d, e, f) { +const Matrix = function (a, b, c, d, e, f) { /** * @type {Array.} */ this._matrix = [a, b, c, d, e, f]; }; -Matrix.init = function(){ +Matrix.init = function () { return new L.PM.Matrix(1, 0, 0, 1, 0, 0); }; @@ -46,18 +45,17 @@ Matrix.prototype = { */ _transform(point) { const matrix = this._matrix; - const { x , y } = point; + const { x, y } = point; point.x = matrix[0] * x + matrix[1] * y + matrix[4]; point.y = matrix[2] * x + matrix[3] * y + matrix[5]; return point; }, - /** * @param {L.Point} point * @return {L.Point} */ - untransform (point) { + untransform(point) { const matrix = this._matrix; return new L.Point( (point.x / matrix[0] - matrix[4]) / matrix[0], @@ -71,8 +69,12 @@ Matrix.prototype = { clone() { const matrix = this._matrix; return new L.PM.Matrix( - matrix[0], matrix[1], matrix[2], - matrix[3], matrix[4], matrix[5] + matrix[0], + matrix[1], + matrix[2], + matrix[3], + matrix[4], + matrix[5] ); }, @@ -88,7 +90,7 @@ Matrix.prototype = { let translateX; let translateY; if (typeof translate === 'number') { - translateX = translate; + translateX = translate; translateY = translate; } else { translateX = translate.x; @@ -119,12 +121,16 @@ Matrix.prototype = { scaleY = scale.y; } - return this - ._add(scaleX, 0, 0, scaleY, origin.x, origin.y) - ._add(1, 0, 0, 1, -origin.x, -origin.y); + return this._add(scaleX, 0, 0, scaleY, origin.x, origin.y)._add( + 1, + 0, + 0, + 1, + -origin.x, + -origin.y + ); }, - /** * m00 m01 x - m00 * x - m01 * y * m10 m11 y - m10 * x - m11 * y @@ -138,9 +144,14 @@ Matrix.prototype = { origin = origin || new L.Point(0, 0); - return this - ._add(cos, sin, -sin, cos, origin.x, origin.y) - ._add(1, 0, 0, 1, -origin.x, -origin.y); + return this._add(cos, sin, -sin, cos, origin.x, origin.y)._add( + 1, + 0, + 0, + 1, + -origin.x, + -origin.y + ); }, /** @@ -167,12 +178,12 @@ Matrix.prototype = { const m = [ [src[0], src[2], src[4]], [src[1], src[3], src[5]], - [ 0, 0, 1] + [0, 0, 1], ]; let other = [ [a, c, e], [b, d, f], - [0, 0, 1] + [0, 0, 1], ]; let val; @@ -181,13 +192,14 @@ Matrix.prototype = { other = [ [src[0], src[2], src[4]], [src[1], src[3], src[5]], - [ 0, 0, 1]]; + [0, 0, 1], + ]; } - for (let i = 0; i < 3; i+=1) { - for (let j = 0; j < 3; j+=1) { + for (let i = 0; i < 3; i += 1) { + for (let j = 0; j < 3; j += 1) { val = 0; - for (let k = 0; k < 3; k+=1) { + for (let k = 0; k < 3; k += 1) { val += m[i][k] * other[k][j]; } result[i][j] = val; @@ -195,12 +207,15 @@ Matrix.prototype = { } this._matrix = [ - result[0][0], result[1][0], result[0][1], - result[1][1], result[0][2], result[1][2] + result[0][0], + result[1][0], + result[0][1], + result[1][1], + result[0][2], + result[1][2], ]; return this; - } + }, }; export default Matrix; - diff --git a/src/js/helpers/ModeHelper.js b/src/js/helpers/ModeHelper.js index 383e988c..b4403c5e 100644 --- a/src/js/helpers/ModeHelper.js +++ b/src/js/helpers/ModeHelper.js @@ -13,7 +13,8 @@ export function _convertLatLngs(latlng, matrix, map) { latlngs.push(_convertLatLngs(x, matrix, map)); }); return latlngs; - } else if (latlng instanceof L.LatLng) { + } + if (latlng instanceof L.LatLng) { return _convertLatLng(latlng, matrix, map, zoom); } return null; @@ -37,4 +38,3 @@ export function _toLatLng(map, point) { } return map.unproject(point, zoom); } - diff --git a/src/js/helpers/index.js b/src/js/helpers/index.js index fb633c4e..de50b81d 100644 --- a/src/js/helpers/index.js +++ b/src/js/helpers/index.js @@ -14,48 +14,50 @@ export function getTranslation(path) { export function isEmptyDeep(l) { // thanks for the function, Felix Heck - const flatten = list => + const flatten = (list) => list - .filter(x => ![null, '', undefined].includes(x)) + .filter((x) => ![null, '', undefined].includes(x)) .reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []); return !flatten(l).length; } export function removeEmptyCoordRings(arr) { - return arr.reduce((result, item)=>{ - if(item.length !== 0){ - result.push( Array.isArray(item) ? removeEmptyCoordRings(item) : item ); + return arr.reduce((result, item) => { + if (item.length !== 0) { + result.push(Array.isArray(item) ? removeEmptyCoordRings(item) : item); } return result; }, []); } // Code from https://stackoverflow.com/a/24153998/8283938 -function destinationVincenty(lonlat, brng, dist) { // rewritten to work with leaflet +function destinationVincenty(lonlat, brng, dist) { + // rewritten to work with leaflet const VincentyConstants = { a: 6378137, b: 6356752.3142, - f: 1 / 298.257223563 + f: 1 / 298.257223563, }; - const {a, b, f} = VincentyConstants; + const { a, b, f } = VincentyConstants; const lon1 = lonlat.lng; const lat1 = lonlat.lat; const s = dist; const pi = Math.PI; - const alpha1 = brng * pi / 180; // converts brng degrees to radius + const alpha1 = (brng * pi) / 180; // converts brng degrees to radius const sinAlpha1 = Math.sin(alpha1); const cosAlpha1 = Math.cos(alpha1); - const tanU1 = (1 - f) * Math.tan(lat1 * pi / 180 /* converts lat1 degrees to radius */); - const cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1)); + const tanU1 = + (1 - f) * Math.tan((lat1 * pi) / 180 /* converts lat1 degrees to radius */); + const cosU1 = 1 / Math.sqrt(1 + tanU1 * tanU1); const sinU1 = tanU1 * cosU1; const sigma1 = Math.atan2(tanU1, cosAlpha1); const sinAlpha = cosU1 * sinAlpha1; const cosSqAlpha = 1 - sinAlpha * sinAlpha; - const uSq = cosSqAlpha * (a * a - b * b) / (b * b); - const A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))); - const B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))); + const uSq = (cosSqAlpha * (a * a - b * b)) / (b * b); + const A = 1 + (uSq / 16384) * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))); + const B = (uSq / 1024) * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))); let sigma = s / (b * A); let sigmaP = 2 * Math.PI; @@ -66,21 +68,41 @@ function destinationVincenty(lonlat, brng, dist) { // rewritten to work with lea cos2SigmaM = Math.cos(2 * sigma1 + sigma); sinSigma = Math.sin(sigma); cosSigma = Math.cos(sigma); - const deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM))); + const deltaSigma = + B * + sinSigma * + (cos2SigmaM + + (B / 4) * + (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - + (B / 6) * + cos2SigmaM * + (-3 + 4 * sinSigma * sinSigma) * + (-3 + 4 * cos2SigmaM * cos2SigmaM))); sigmaP = sigma; sigma = s / (b * A) + deltaSigma; } const tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1; - const lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, - (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp)); - const lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1); - const C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)); - const lam = lambda - (1 - C) * f * sinAlpha * - (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM))); + const lat2 = Math.atan2( + sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, + (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp) + ); + const lambda = Math.atan2( + sinSigma * sinAlpha1, + cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1 + ); + const C = (f / 16) * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)); + const lam = + lambda - + (1 - C) * + f * + sinAlpha * + (sigma + + C * + sinSigma * + (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM))); // const revAz = Math.atan2(sinAlpha, -tmp); // final bearing - const lamFunc = lon1 + (lam * 180 / pi); // converts lam radius to degrees - const lat2a = lat2 * 180 / pi; // converts lat2a radius to degrees + const lamFunc = lon1 + (lam * 180) / pi; // converts lam radius to degrees + const lat2a = (lat2 * 180) / pi; // converts lat2a radius to degrees return L.latLng(lamFunc, lat2a); } @@ -92,7 +114,7 @@ export function createGeodesicPolygon(origin, radius, sides, rotation) { const points = []; for (let i = 0; i < sides; i += 1) { - angle = (i * 360 / sides) + rotation; + angle = (i * 360) / sides + rotation; newLonlat = destinationVincenty(origin, angle, radius); geomPoint = L.latLng(newLonlat.lng, newLonlat.lat); points.push(geomPoint); @@ -114,8 +136,15 @@ function destination(latlng, heading, distance) { const cosLat1 = Math.cos(lat1); const cosDistR = Math.cos(distance / R); const sinDistR = Math.sin(distance / R); - const lat2 = Math.asin(sinLat1 * cosDistR + cosLat1 * sinDistR * Math.cos(rheading)); - let lon2 = lon1 + Math.atan2(Math.sin(rheading) * sinDistR * cosLat1, cosDistR - sinLat1 * Math.sin(lat2)); + const lat2 = Math.asin( + sinLat1 * cosDistR + cosLat1 * sinDistR * Math.cos(rheading) + ); + let lon2 = + lon1 + + Math.atan2( + Math.sin(rheading) * sinDistR * cosLat1, + cosDistR - sinLat1 * Math.sin(lat2) + ); lon2 *= radInv; lon2 = lon2 > 180 ? lon2 - 360 : lon2 < -180 ? lon2 + 360 : lon2; return L.latLng([lat2 * radInv, lon2]); @@ -124,10 +153,10 @@ function destination(latlng, heading, distance) { function angle(map, latlngA, latlngB) { const pointA = map.latLngToContainerPoint(latlngA); const pointB = map.latLngToContainerPoint(latlngB); - let angleDeg = Math.atan2(pointB.y - pointA.y, pointB.x - pointA.x) * 180 / Math.PI + 90; + let angleDeg = + (Math.atan2(pointB.y - pointA.y, pointB.x - pointA.x) * 180) / Math.PI + 90; angleDeg += angleDeg < 0 ? 360 : 0; return angleDeg; - } export function destinationOnLine(map, latlngA, latlngB, distance) { @@ -135,51 +164,54 @@ export function destinationOnLine(map, latlngA, latlngB, distance) { return destination(latlngA, angleDeg, distance); } - // this function is used with the .sort(prioritiseSort(key, sortingOrder)) function of arrays export function prioritiseSort(key, _sortingOrder, order = 'asc') { /* the sorting order has all possible keys (lowercase) with the index and then it is sorted by the key on the object */ - if(!_sortingOrder || Object.keys(_sortingOrder).length === 0) { - return (a,b)=>a-b; // default sort method + if (!_sortingOrder || Object.keys(_sortingOrder).length === 0) { + return (a, b) => a - b; // default sort method } // change the keys to lowercase const keys = Object.keys(_sortingOrder); let objKey; let n = keys.length; - const sortingOrder={}; + const sortingOrder = {}; while (n--) { objKey = keys[n]; sortingOrder[objKey.toLowerCase()] = _sortingOrder[objKey]; } - function getShape(layer){ - if(layer instanceof L.Marker){ - return "Marker"; - }else if(layer instanceof L.Circle){ - return "Circle"; - }else if(layer instanceof L.CircleMarker){ - return "CircleMarker"; - }else if(layer instanceof L.Rectangle){ - return "Rectangle"; - }else if(layer instanceof L.Polygon){ - return "Polygon"; - }else if(layer instanceof L.Polyline){ - return "Line"; - }else{ - return undefined; + function getShape(layer) { + if (layer instanceof L.Marker) { + return 'Marker'; + } + if (layer instanceof L.Circle) { + return 'Circle'; + } + if (layer instanceof L.CircleMarker) { + return 'CircleMarker'; + } + if (layer instanceof L.Rectangle) { + return 'Rectangle'; } + if (layer instanceof L.Polygon) { + return 'Polygon'; + } + if (layer instanceof L.Polyline) { + return 'Line'; + } + return undefined; } return (a, b) => { let keyA; let keyB; - if(key === "instanceofShape"){ + if (key === 'instanceofShape') { keyA = getShape(a.layer).toLowerCase(); keyB = getShape(b.layer).toLowerCase(); - if(!keyA || !keyB) return 0; - }else{ + if (!keyA || !keyB) return 0; + } else { /* eslint-disable-next-line no-prototype-builtins */ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return 0; keyA = a[key].toLowerCase(); @@ -187,26 +219,21 @@ export function prioritiseSort(key, _sortingOrder, order = 'asc') { } const first = - keyA in sortingOrder - ? sortingOrder[keyA] - : Number.MAX_SAFE_INTEGER; + keyA in sortingOrder ? sortingOrder[keyA] : Number.MAX_SAFE_INTEGER; const second = - keyB in sortingOrder - ? sortingOrder[keyB] - : Number.MAX_SAFE_INTEGER; + keyB in sortingOrder ? sortingOrder[keyB] : Number.MAX_SAFE_INTEGER; let result = 0; if (first < second) result = -1; else if (first > second) result = 1; - return order === 'desc' ? (result * -1) : result; - } + return order === 'desc' ? result * -1 : result; + }; } -export function copyLatLngs(layer, latlngs = layer.getLatLngs()){ - if(layer instanceof L.Polygon) { +export function copyLatLngs(layer, latlngs = layer.getLatLngs()) { + if (layer instanceof L.Polygon) { return L.polygon(latlngs).getLatLngs(); - }else{ - return L.polyline(latlngs).getLatLngs(); } + return L.polyline(latlngs).getLatLngs(); } diff --git a/src/js/helpers/turfHelper.js b/src/js/helpers/turfHelper.js index 651a33f6..abe85d12 100644 --- a/src/js/helpers/turfHelper.js +++ b/src/js/helpers/turfHelper.js @@ -1,13 +1,13 @@ import polygonClipping from 'polygon-clipping'; -export function feature(geom){ - const feat = {type: "Feature"}; +export function feature(geom) { + const feat = { type: 'Feature' }; feat.geometry = geom; return feat; } export function getGeometry(geojson) { - if(geojson.type === "Feature") return geojson.geometry; + if (geojson.type === 'Feature') return geojson.geometry; return geojson; } @@ -16,34 +16,37 @@ export function getCoords(geojson) { } export function turfPoint(coords) { - return feature({"type": "Point", "coordinates": coords}); + return feature({ type: 'Point', coordinates: coords }); } export function turfLineString(coords) { - return feature({"type": "LineString", "coordinates": coords}); + return feature({ type: 'LineString', coordinates: coords }); } export function turfMultiLineString(coords) { - return feature({"type": "MultiLineString", "coordinates": coords}); + return feature({ type: 'MultiLineString', coordinates: coords }); } export function turfPolygon(coords) { - return feature({"type": "Polygon", "coordinates": coords}); + return feature({ type: 'Polygon', coordinates: coords }); } export function turfMultiPolygon(coords) { - return feature({"type": "MultiPolygon", "coordinates": coords}); + return feature({ type: 'MultiPolygon', coordinates: coords }); } export function turfFeatureCollection(features) { - return {type: "FeatureCollection", "features": features}; + return { type: 'FeatureCollection', features }; } -export function intersect(poly1,poly2) { +export function intersect(poly1, poly2) { const geom1 = getGeometry(poly1); const geom2 = getGeometry(poly2); - const intersection = polygonClipping.intersection(geom1.coordinates,geom2.coordinates); + const intersection = polygonClipping.intersection( + geom1.coordinates, + geom2.coordinates + ); if (intersection.length === 0) return null; if (intersection.length === 1) return turfPolygon(intersection[0]); return turfMultiPolygon(intersection); @@ -53,7 +56,10 @@ export function difference(polygon1, polygon2) { const geom1 = getGeometry(polygon1); const geom2 = getGeometry(polygon2); - const differenced = polygonClipping.difference(geom1.coordinates, geom2.coordinates); + const differenced = polygonClipping.difference( + geom1.coordinates, + geom2.coordinates + ); if (differenced.length === 0) return null; if (differenced.length === 1) return turfPolygon(differenced[0]); return turfMultiPolygon(differenced); @@ -61,36 +67,36 @@ export function difference(polygon1, polygon2) { // LineString coords returns 1 // MultiLineString coords returns 2 -export function getDepthOfCoords(coords){ - if(Array.isArray(coords)){ +export function getDepthOfCoords(coords) { + if (Array.isArray(coords)) { return 1 + getDepthOfCoords(coords[0]); } return -1; // return -1 because this is already the lng of the lnglat (geojson) array } -export function flattenPolyline(polyline){ - if(polyline instanceof L.Polyline){ +export function flattenPolyline(polyline) { + if (polyline instanceof L.Polyline) { polyline = polyline.toGeoJSON(15); } const coords = getCoords(polyline); const depth = getDepthOfCoords(coords); const features = []; - if(depth > 1){ - coords.forEach((coord)=>{ + if (depth > 1) { + coords.forEach((coord) => { features.push(turfLineString(coord)); }); - }else{ + } else { features.push(polyline); } return features; } -export function groupToMultiLineString(group){ +export function groupToMultiLineString(group) { const coords = []; - group.eachLayer((layer)=>{ - coords.push(getCoords(layer.toGeoJSON(15))); + group.eachLayer((layer) => { + coords.push(getCoords(layer.toGeoJSON(15))); }); return turfMultiLineString(coords); } diff --git a/src/js/polyfills.js b/src/js/polyfills.js index f3a667e6..4dce75bb 100644 --- a/src/js/polyfills.js +++ b/src/js/polyfills.js @@ -92,7 +92,6 @@ if (typeof Object.assign != 'function') { if (!Array.prototype.includes) { Object.defineProperty(Array.prototype, 'includes', { value: function (searchElement, fromIndex) { - if (this == null) { throw new TypeError('"this" is null or not defined'); } @@ -120,7 +119,13 @@ if (!Array.prototype.includes) { var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); function sameValueZero(x, y) { - return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)); + return ( + x === y || + (typeof x === 'number' && + typeof y === 'number' && + isNaN(x) && + isNaN(y)) + ); } // 7. Repeat, while k < len @@ -130,12 +135,12 @@ if (!Array.prototype.includes) { if (sameValueZero(o[k], searchElement)) { return true; } - // c. Increase k by 1. + // c. Increase k by 1. k++; } // 8. Return false return false; - } + }, }); -} \ No newline at end of file +} diff --git a/webpack.build.js b/webpack.build.js index 9ce7dca6..ba8e8637 100644 --- a/webpack.build.js +++ b/webpack.build.js @@ -1,68 +1,69 @@ /* eslint import/no-extraneous-dependencies: 0 */ const webpack = require('webpack'); -const MiniCssExtractPlugin = require("mini-css-extract-plugin"); +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const path = require('path'); const TerserPlugin = require('terser-webpack-plugin'); const CopyPlugin = require('copy-webpack-plugin'); module.exports = { - watch: false, - // devtool: 'cheap-source-map', - entry: ['./src/js/L.PM.js'], - mode: 'production', - output: { - filename: 'leaflet-geoman.min.js', - path: path.resolve(__dirname, 'dist'), - }, - module: { - rules: [ - { - test: /\.mjs$/, - include: /node_modules/, - type: "javascript/auto", - }, - { - test: /\.js$/, - exclude: /(node_modules|bower_components)/, - use: { - loader: 'babel-loader', - options: { - presets: ['@babel/preset-env'], - }, - }, - }, - { - test: /\.css$/, - use: [{ - loader: MiniCssExtractPlugin.loader, - }, 'css-loader',], - }, - { - test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, - loader: 'url-loader', - }, + watch: false, + // devtool: 'cheap-source-map', + entry: ['./src/js/L.PM.js'], + mode: 'production', + output: { + filename: 'leaflet-geoman.min.js', + path: path.resolve(__dirname, 'dist'), + }, + module: { + rules: [ + { + test: /\.mjs$/, + include: /node_modules/, + type: 'javascript/auto', + }, + { + test: /\.js$/, + exclude: /(node_modules|bower_components)/, + use: { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + }, + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + }, + 'css-loader', ], - }, - plugins: [ - new MiniCssExtractPlugin({ filename: 'leaflet-geoman.css' }), - new CopyPlugin({ - patterns: [ - { from: 'leaflet-geoman.d.ts', to: 'leaflet-geoman.d.ts' }, - ], - }), + }, + { + test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, + loader: 'url-loader', + }, ], - optimization: { - minimize: true, - minimizer: [ - new TerserPlugin({ - terserOptions: { - ie8: true, - format: { - comments: false - } - }, - extractComments: false, - }), - ], - }, + }, + plugins: [ + new MiniCssExtractPlugin({ filename: 'leaflet-geoman.css' }), + new CopyPlugin({ + patterns: [{ from: 'leaflet-geoman.d.ts', to: 'leaflet-geoman.d.ts' }], + }), + ], + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + ie8: true, + format: { + comments: false, + }, + }, + extractComments: false, + }), + ], + }, }; diff --git a/webpack.dev.js b/webpack.dev.js index 50a35416..5f90b686 100644 --- a/webpack.dev.js +++ b/webpack.dev.js @@ -1,53 +1,54 @@ /* eslint import/no-extraneous-dependencies: 0 */ -const MiniCssExtractPlugin = require("mini-css-extract-plugin"); +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CopyPlugin = require('copy-webpack-plugin'); const path = require('path'); module.exports = { - watch: true, - devtool: 'eval-cheap-source-map', - mode: 'development', - entry: ['./src/js/L.PM.js'], - output: { - filename: 'leaflet-geoman.min.js', - path: path.resolve(__dirname, 'dist'), - }, - module: { - rules: [ - { - test: /\.mjs$/, - include: /node_modules/, - type: "javascript/auto", - }, - { - test: /\.js$/, - exclude: /(node_modules|bower_components)/, - use: { - loader: 'babel-loader', - options: { - presets: ['@babel/preset-env'], - }, - }, - }, - { - test: /\.css$/, - use: [{ - loader: MiniCssExtractPlugin.loader, - }, 'css-loader',], - }, - { - test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, - loader: 'url-loader', - }, + watch: true, + devtool: 'eval-cheap-source-map', + mode: 'development', + entry: ['./src/js/L.PM.js'], + output: { + filename: 'leaflet-geoman.min.js', + path: path.resolve(__dirname, 'dist'), + }, + module: { + rules: [ + { + test: /\.mjs$/, + include: /node_modules/, + type: 'javascript/auto', + }, + { + test: /\.js$/, + exclude: /(node_modules|bower_components)/, + use: { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + }, + }, + }, + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + }, + 'css-loader', ], - }, - plugins: [ - new MiniCssExtractPlugin({ filename: 'leaflet-geoman.css' }), - new CopyPlugin({ - patterns: [ - { from: 'leaflet-geoman.d.ts', to: 'leaflet-geoman.d.ts' }, - ], - }), + }, + { + test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, + loader: 'url-loader', + }, ], + }, + plugins: [ + new MiniCssExtractPlugin({ filename: 'leaflet-geoman.css' }), + new CopyPlugin({ + patterns: [{ from: 'leaflet-geoman.d.ts', to: 'leaflet-geoman.d.ts' }], + }), + ], };