Merge pull request #3820 from tchak/update-webpack

Load leaflet from separate chunks
This commit is contained in:
Paul Chavard 2019-05-02 15:57:47 +02:00 committed by GitHub
commit 7e8df41648
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 2040 additions and 2714 deletions

View file

@ -1,64 +1,47 @@
import { CREATE } from 'leaflet-freedraw';
import { delegate } from '@utils';
import {
initMap,
getCurrentMap,
geocodeAddress,
drawCadastre,
drawQuartiersPrioritaires,
drawParcellesAgricoles,
drawUserSelection,
addFreeDrawEvents
} from '../../shared/carte';
import { initMap, drawPolygons, addFreeDrawEvents } from '../../shared/carte';
function initialize() {
for (let element of document.querySelectorAll('.carte')) {
diplayMap(element, null, true);
async function initialize() {
const elements = document.querySelectorAll('.carte');
if (elements.length) {
const editable = [...elements].find(element =>
element.classList.contains('edit')
);
await loadLeaflet(editable);
for (let element of elements) {
diplayMap(element, null, true);
}
}
}
window.DS.drawMapData = (selector, data) => {
let element = document.querySelector(selector);
diplayMap(element, data);
};
// We load leaflet dynamically, ramda and freedraw and assign them to globals.
// Latest freedraw version build needs globals.
async function loadLeaflet(editable) {
window.L = await import('leaflet').then(({ default: L }) => L);
if (editable) {
window.R = await import('ramda').then(({ default: R }) => R);
await import('leaflet-freedraw/dist/leaflet-freedraw.web.js');
}
}
function diplayMap(element, data, initial = false) {
data = data || JSON.parse(element.dataset.geo);
let editable = element.classList.contains('edit');
const editable = element.classList.contains('edit');
const map = initMap(element, data.position, editable);
let map = initMap(element, data.position, editable);
drawPolygons(map, data, { initial, editable });
// draw external polygons
drawCadastre(map, data, editable);
drawQuartiersPrioritaires(map, data, editable);
drawParcellesAgricoles(map, data, editable);
// draw user polygon
if (initial) {
drawUserSelection(map, data, editable);
if (editable) {
let input = element.parentElement.querySelector('input[data-remote]');
addFreeDrawEvents(map, input);
}
if (initial && editable) {
const input = element.parentElement.querySelector('input[data-remote]');
addFreeDrawEvents(map, input);
}
}
addEventListener('turbolinks:load', initialize);
delegate('click', '.toolbar .new-area', event => {
event.preventDefault();
let map = getCurrentMap(event.target);
if (map) {
map.freeDraw.mode(CREATE);
}
});
delegate('autocomplete:select', '.toolbar [data-address]', event => {
let map = getCurrentMap(event.target);
if (map) {
geocodeAddress(map, event.detail.label);
}
addEventListener('carte:update', ({ detail: { selector, data } }) => {
const element = document.querySelector(selector);
diplayMap(element, data);
});

View file

@ -1,10 +1,8 @@
import L from 'leaflet';
import FreeDraw, { NONE, EDIT, DELETE } from 'leaflet-freedraw';
/* globals FreeDraw L */
import { fire, getJSON, delegate } from '@utils';
import polygonArea from './polygon_area';
const LAYERS = {};
const MAPS = new WeakMap();
export function initMap(element, position, editable = false) {
@ -22,7 +20,7 @@ export function initMap(element, position, editable = false) {
if (editable) {
const freeDraw = new FreeDraw({
mode: NONE,
mode: FreeDraw.NONE,
smoothFactor: 4,
mergePolygons: false
});
@ -35,81 +33,39 @@ export function initMap(element, position, editable = false) {
}
}
export function drawCadastre(map, { cadastres }, editable = false) {
drawLayer(
map,
cadastres,
editable ? CADASTRE_POLYGON_STYLE : noEditStyle(CADASTRE_POLYGON_STYLE),
'cadastres'
);
}
export function drawQuartiersPrioritaires(
map,
{ quartiersPrioritaires },
editable = false
) {
drawLayer(
map,
quartiersPrioritaires,
editable ? QP_POLYGON_STYLE : noEditStyle(QP_POLYGON_STYLE),
'quartiersPrioritaires'
);
}
export function drawParcellesAgricoles(
map,
{ parcellesAgricoles },
editable = false
) {
drawLayer(
map,
parcellesAgricoles,
editable ? RPG_POLYGON_STYLE : noEditStyle(RPG_POLYGON_STYLE),
'parcellesAgricoles'
);
export function drawPolygons(map, data, { editable, initial }) {
if (initial) {
drawUserSelection(map, data, editable);
}
clearLayers(map);
drawCadastre(map, data, editable);
drawQuartiersPrioritaires(map, data, editable);
drawParcellesAgricoles(map, data, editable);
bringToFrontUserSelection(map);
}
export function drawUserSelection(map, { selection }, editable = false) {
if (selection) {
const coordinates = toLatLngs(selection);
let polygon;
if (editable) {
coordinates.forEach(polygon => map.freeDraw.create(polygon));
const polygon = map.freeDraw.all()[0];
if (polygon) {
map.fitBounds(polygon.getBounds());
}
[polygon] = markFreeDrawLayers(map);
} else {
const polygon = L.polygon(coordinates, {
polygon = L.polygon(coordinates, {
color: 'red',
zIndex: 3
}).addTo(map);
});
polygon.addTo(map);
}
if (polygon) {
map.fitBounds(polygon.getBounds());
}
}
}
export function geocodeAddress(map, query) {
getJSON('/address/geocode', { request: query }).then(data => {
if (data.lat !== null) {
map.setView(new L.LatLng(data.lat, data.lon), data.zoom);
}
});
}
export function getCurrentMap(input) {
let element = input.closest('.toolbar').parentElement.querySelector('.carte');
if (MAPS.has(element)) {
return MAPS.get(element);
}
}
const EMPTY_GEO_JSON = '[]';
const ERROR_GEO_JSON = '';
export function addFreeDrawEvents(map, selector) {
const input = findInput(selector);
map.freeDraw.on('markers', ({ latLngs }) => {
@ -121,10 +77,65 @@ export function addFreeDrawEvents(map, selector) {
input.value = ERROR_GEO_JSON;
}
markFreeDrawLayers(map);
fire(input, 'change');
});
}
function drawCadastre(map, { cadastres }, editable = false) {
drawLayer(
map,
cadastres,
editable ? CADASTRE_POLYGON_STYLE : noEditStyle(CADASTRE_POLYGON_STYLE)
);
}
function drawQuartiersPrioritaires(
map,
{ quartiersPrioritaires },
editable = false
) {
drawLayer(
map,
quartiersPrioritaires,
editable ? QP_POLYGON_STYLE : noEditStyle(QP_POLYGON_STYLE)
);
}
function drawParcellesAgricoles(map, { parcellesAgricoles }, editable = false) {
drawLayer(
map,
parcellesAgricoles,
editable ? RPG_POLYGON_STYLE : noEditStyle(RPG_POLYGON_STYLE)
);
}
function geocodeAddress(map, query) {
getJSON('/address/geocode', { request: query }).then(data => {
if (data.lat !== null) {
map.setView(new L.LatLng(data.lat, data.lon), data.zoom);
}
});
}
function getCurrentMap(element) {
if (!element.matches('.carte')) {
const closestCarteElement = element.closest('.carte');
const closestToolbarElement = element.closest('.toolbar');
element = closestCarteElement
? closestCarteElement
: closestToolbarElement.parentElement.querySelector('.carte');
}
if (MAPS.has(element)) {
return MAPS.get(element);
}
}
const EMPTY_GEO_JSON = '[]';
const ERROR_GEO_JSON = '';
function toLatLngs({ coordinates }) {
return coordinates.map(polygon =>
polygon[0].map(point => ({ lng: point[0], lat: point[1] }))
@ -137,28 +148,40 @@ function findInput(selector) {
: selector;
}
function createLayer(map, layerName) {
const layer = (LAYERS[layerName] = new L.GeoJSON(undefined, {
function createLayer(map) {
const layer = new L.GeoJSON(undefined, {
interactive: false
}));
});
layer.addTo(map);
return layer;
}
function removeLayer(map, layerName) {
const layer = LAYERS[layerName];
if (layer) {
delete LAYERS[layerName];
map.removeLayer(layer);
}
function clearLayers(map) {
map.eachLayer(layer => {
if (layer instanceof L.GeoJSON) {
map.removeLayer(layer);
}
});
}
function drawLayer(map, data, style, layerName = 'default') {
removeLayer(map, layerName);
function bringToFrontUserSelection(map) {
map.eachLayer(layer => {
if (layer.isFreeDraw) {
layer.bringToFront();
}
});
}
function markFreeDrawLayers(map) {
return map.freeDraw.all().map(layer => {
layer.isFreeDraw = true;
return layer;
});
}
function drawLayer(map, data, style) {
if (Array.isArray(data) && data.length > 0) {
const layer = createLayer(map, layerName);
const layer = createLayer(map);
data.forEach(function(item) {
layer.addData(item.geometry);
@ -197,18 +220,33 @@ const RPG_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
});
delegate('click', '.carte.edit', event => {
let element = event.target;
let isPath = element.matches('.leaflet-container g path');
let map = element.matches('.carte') ? element : element.closest('.carte');
let freeDraw = MAPS.has(map) ? MAPS.get(map).freeDraw : null;
const map = getCurrentMap(event.target);
if (freeDraw) {
if (map) {
const isPath = event.target.matches('.leaflet-container g path');
if (isPath) {
setTimeout(() => {
freeDraw.mode(EDIT | DELETE);
map.freeDraw.mode(FreeDraw.EDIT | FreeDraw.DELETE);
}, 50);
} else {
freeDraw.mode(NONE);
map.freeDraw.mode(FreeDraw.NONE);
}
}
});
delegate('click', '.toolbar .new-area', event => {
event.preventDefault();
const map = getCurrentMap(event.target);
if (map) {
map.freeDraw.mode(FreeDraw.CREATE);
}
});
delegate('autocomplete:select', '.toolbar [data-address]', event => {
const map = getCurrentMap(event.target);
if (map) {
geocodeAddress(map, event.detail.label);
}
});

View file

@ -4,4 +4,4 @@
partial: 'shared/champs/carte/geo_areas',
locals: { champ: @champ, error: @error }) %>
DS.drawMapData("<%= @selector %>", <%= geo_data(@champ) %>);
<%= fire_event('carte:update', { selector: @selector, data: @champ.to_render_data }.to_json) %>

View file

@ -14,7 +14,8 @@
= favicon_link_tag(image_url("favicons/32x32.png"), type: "image/png", sizes: "32x32")
= favicon_link_tag(image_url("favicons/96x96.png"), type: "image/png", sizes: "96x96")
= javascript_pack_tag 'application', defer: true, 'data-turbolinks-track': 'reload'
- packs = ['application', 'track', administrateur_signed_in? ? 'sendinblue' : nil].compact
= javascript_packs_with_chunks_tag *packs, defer: true, 'data-turbolinks-track': 'reload'
= stylesheet_link_tag 'new_design/new_application', media: 'all', 'data-turbolinks-track': 'reload'
= stylesheet_link_tag 'new_design/print', media: 'print', 'data-turbolinks-track': 'reload'
@ -42,7 +43,3 @@
= javascript_include_tag :xray
= yield :charts_js
= javascript_pack_tag 'track', async: true
- if administrateur_signed_in?
= javascript_pack_tag 'sendinblue', async: true

View file

@ -12,7 +12,8 @@
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': "reload"
= stylesheet_link_tag 'print', media: 'print', 'data-turbolinks-track': "reload"
= javascript_pack_tag 'application-old', defer: true, 'data-turbolinks-track': 'reload'
- packs = ['application-old', 'track', administrateur_signed_in? ? 'sendinblue' : nil].compact
= javascript_packs_with_chunks_tag *packs, defer: true, 'data-turbolinks-track': 'reload'
= javascript_include_tag 'application', defer: true, 'data-turbolinks-track': 'reload'
= csrf_meta_tags
= Gon::Base.render_data(camel_case: true, init: true)
@ -42,6 +43,5 @@
%i.fa.fa-times{ style: 'position: fixed; top: 10; right: 30; color: white;' }
= render partial: 'layouts/footer', locals: { main_container_size: main_container_size }
= javascript_pack_tag 'track', async: true
- if administrateur_signed_in?
= javascript_pack_tag 'sendinblue', async: true

View file

@ -7,5 +7,6 @@ const resolve = {
}
};
environment.splitChunks();
environment.config.merge({ resolve });
module.exports = environment;

View file

@ -2,8 +2,4 @@ process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const environment = require('./environment');
// https://github.com/rails/webpacker/issues/1235
environment.config.optimization.minimizer[0].options.uglifyOptions.ecma = 5; // for IE 11 support
environment.config.optimization.minimizer[0].options.uglifyOptions.safari10 = true;
module.exports = environment.toWebpackConfig();

View file

@ -1,44 +1,44 @@
{
"dependencies": {
"@babel/preset-react": "^7.0.0",
"@fortawesome/fontawesome-svg-core": "^1.2.15",
"@fortawesome/free-solid-svg-icons": "^5.7.2",
"@fortawesome/fontawesome-svg-core": "^1.2.17",
"@fortawesome/free-solid-svg-icons": "^5.8.1",
"@fortawesome/react-fontawesome": "^0.1.4",
"@rails/webpacker": "4.0.0-pre.3",
"@sentry/browser": "^4.6.5",
"@rails/webpacker": "4.0.2",
"@sentry/browser": "^5.1.0",
"@turf/area": "^6.0.1",
"activestorage": "^5.2.2",
"activestorage": "^5.2.3",
"autocomplete.js": "^0.36.0",
"babel-plugin-macros": "^2.5.0",
"babel-plugin-macros": "^2.5.1",
"babel-plugin-transform-react-remove-prop-types": "^0.4.24",
"chartkick": "^3.0.1",
"chartkick": "^3.0.2",
"debounce": "^1.2.0",
"dom4": "^2.1.3",
"dom4": "^2.1.4",
"highcharts": "^6.1.2",
"jquery": "^3.3.1",
"leaflet-freedraw": "^2.9.0",
"leaflet": "^1.3.4",
"jquery": "^3.4.0",
"leaflet": "^1.4.0",
"leaflet-freedraw": "^2.10.0",
"prop-types": "^15.7.2",
"rails-ujs": "^5.2.2",
"ramda": "^0.25.0",
"react_ujs": "^2.4.4",
"react-dom": "^16.8.4",
"rails-ujs": "^5.2.3",
"ramda": "=0.24.1",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scroll-to-component": "^1.0.2",
"react-sortable-hoc": "^1.7.1",
"react": "^16.8.4",
"react_ujs": "^2.5.0",
"select2": "^4.0.6-rc.1",
"turbolinks": "^5.2.0"
},
"devDependencies": {
"babel-eslint": "^10.0.1",
"eclint": "^2.8.0",
"eslint": "^5.9.0",
"eslint-config-prettier": "^3.3.0",
"eslint-plugin-prettier": "^3.0.0",
"eclint": "^2.8.1",
"eslint": "^5.16.0",
"eslint-config-prettier": "^4.1.0",
"eslint-plugin-prettier": "^3.0.1",
"eslint-plugin-react": "^7.12.4",
"eslint-plugin-react-hooks": "^1.5.1",
"prettier": "^1.15.3",
"webpack-dev-server": "^3.1.9"
"eslint-plugin-react-hooks": "^1.6.0",
"prettier": "^1.17.0",
"webpack-dev-server": "^3.3.1"
},
"scripts": {
"lint:ec": "eclint check $({ git ls-files ; find vendor -type f ; echo 'db/schema.rb' ; } | sort | uniq -u)",

View file

@ -45,7 +45,7 @@ describe Champs::CarteController, type: :controller do
expect(assigns(:error)).to eq(nil)
expect(champ.reload.value).to eq(nil)
expect(champ.reload.geo_areas).to eq([])
expect(response.body).to include("DS.drawMapData(\".carte-1\", {\"position\":{\"lon\":\"2.428462\",\"lat\":\"46.538192\",\"zoom\":\"13\"},\"selection\":null,\"quartiersPrioritaires\":[],\"cadastres\":[],\"parcellesAgricoles\":[]});")
expect(response.body).to include("DS.fire('carte:update', {\"selector\":\".carte-1\",\"data\":{\"position\":{\"lon\":\"2.428462\",\"lat\":\"46.538192\",\"zoom\":\"13\"},\"selection\":null,\"quartiersPrioritaires\":[],\"cadastres\":[],\"parcellesAgricoles\":[]}});")
}
end

4405
yarn.lock

File diff suppressed because it is too large Load diff