Skip to content

Commit

Permalink
[refactor] Use JS modules for client URL routing
Browse files Browse the repository at this point in the history
  • Loading branch information
almet committed Dec 13, 2023
1 parent d15c436 commit 6bcde85
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 94 deletions.
3 changes: 3 additions & 0 deletions umap/static/umap/js/bindModules.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import URLs from "./modules/urls.mjs"

window.URLs = URLs;
44 changes: 44 additions & 0 deletions umap/static/umap/js/modules/urls.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
export default class URLs {
constructor(serverUrls) {
this.urls = serverUrls;
}

/**
* Returns the URL to the requested resource.
*
* @param {String} urlName The URL name, as specified by the server.
* @param {String|Object} params If a string, the map id, otherwise the parameters passed to the URL template.
* @returns {String} The URL that has been built.
*/
get(urlName, params) {
if (typeof params != 'object')
params = { map_id: params };

if (typeof this[urlName] === "function")
return this[urlName](params);

if (this.urls.hasOwnProperty(urlName)) {
console.log("urls", this.urls, urlName, params);
return L.Util.template(this.urls[urlName], params);
} else {
throw `Unable to find a URL for route ${urlName}`;
}
}

// Update if map_id is passed, create otherwise.
map_save({ map_id }) {
if (map_id)
return this.get("map_update", map_id);
return this.get("map_create");
}

// Update the layer if pk is passed, create otherwise.
datalayer_save({ map_id, pk }) {
if (pk)
return this.get(
"datalayer_update",
{ map_id: map_id, pk: pk }
);
return this.get("datalayer_create", map_id);
}
}
76 changes: 28 additions & 48 deletions umap/static/umap/js/umap.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,20 @@ L.U.Map.include({
const zoomControl =
typeof geojson.properties.zoomControl !== 'undefined'
? geojson.properties.zoomControl
: true
: true;
geojson.properties.zoomControl = false
const fullscreenControl =
typeof geojson.properties.fullscreenControl !== 'undefined'
? geojson.properties.fullscreenControl
: true
: true;
geojson.properties.fullscreenControl = false
L.Util.setBooleanFromQueryString(geojson.properties, 'scrollWheelZoom')

L.Map.prototype.initialize.call(this, el, geojson.properties)

// After calling parent initialize, as we are doing initCenter our-selves
if (geojson.geometry) this.options.center = this.latLng(geojson.geometry)
this.urls = new window.URLs(this.options.urls);

this.ui = new L.U.UI(this._container)
this.xhr = new L.U.Xhr(this.ui)
Expand Down Expand Up @@ -272,10 +273,10 @@ L.U.Map.include({
url.searchParams.delete('edit')
history.pushState({}, '', url)
}
if (L.Util.queryString('download'))
window.location = L.Util.template(this.options.urls.map_download, {
map_id: this.options.umap_id,
})
if (L.Util.queryString('download')) {
let download_url = this.urls.get('map_download', this.options.umap_id);
window.location = download_url;
}
})

window.onbeforeunload = () => this.isDirty || null
Expand Down Expand Up @@ -352,7 +353,7 @@ L.U.Map.include({
document.body,
'umap-caption-bar-enabled',
this.options.captionBar ||
(this.options.slideshow && this.options.slideshow.active)
(this.options.slideshow && this.options.slideshow.active)
)
L.DomUtil.classIf(
document.body,
Expand Down Expand Up @@ -582,7 +583,7 @@ L.U.Map.include({
if (
this.options.tilelayer &&
this.options.tilelayer.url_template ===
this.options.tilelayers[i].url_template
this.options.tilelayers[i].url_template
) {
// Keep control over the displayed attribution for non custom tilelayers
this.options.tilelayer.attribution = this.options.tilelayers[i].attribution
Expand Down Expand Up @@ -1093,7 +1094,7 @@ L.U.Map.include({
formData.append('name', this.options.name)
formData.append('center', JSON.stringify(this.geometry()))
formData.append('settings', JSON.stringify(geojson))
this.post(this.getSaveUrl(), {
this.post(this.urls.get('map_save', this.options.umap_id), {
data: formData,
context: this,
callback: function (data) {
Expand Down Expand Up @@ -1169,42 +1170,25 @@ L.U.Map.include({
},

sendEditLink: function () {
const url = L.Util.template(this.options.urls.map_send_edit_link, {
map_id: this.options.umap_id,
}),
input = this.ui._alert.querySelector('input'),
email = input.value
const input = this.ui._alert.querySelector('input')
const email = input.value

const formData = new FormData()
formData.append('email', email)

const url = this.urls.get('map_send_edit_link', this.options.umap_id)
this.post(url, {
data: formData,
})
},

getEditUrl: function () {
return L.Util.template(this.options.urls.map_update, {
map_id: this.options.umap_id,
})
},

getCreateUrl: function () {
return L.Util.template(this.options.urls.map_create)
},

getSaveUrl: function () {
return (this.options.umap_id && this.getEditUrl()) || this.getCreateUrl()
},

star: function () {
if (!this.options.umap_id)
return this.ui.alert({
content: L._('Please save the map first'),
level: 'error',
})
let url = L.Util.template(this.options.urls.map_star, {
map_id: this.options.umap_id,
})
let url = this.urls.get('map_star', this.options.umap_id);
this.post(url, {
context: this,
callback: function (data) {
Expand Down Expand Up @@ -1749,10 +1733,10 @@ L.U.Map.include({

initCaptionBar: function () {
const container = L.DomUtil.create(
'div',
'umap-caption-bar',
this._controlContainer
),
'div',
'umap-caption-bar',
this._controlContainer
),
name = L.DomUtil.create('h3', '', container)
L.DomEvent.disableClickPropagation(container)
this.permissions.addOwnerLink('span', container)
Expand Down Expand Up @@ -1812,9 +1796,7 @@ L.U.Map.include({

del: function () {
if (confirm(L._('Are you sure you want to delete this map?'))) {
const url = L.Util.template(this.options.urls.map_delete, {
map_id: this.options.umap_id,
})
const url = this.urls.get('map_delete', this.options.umap_id);
this.post(url)
}
},
Expand All @@ -1823,10 +1805,8 @@ L.U.Map.include({
if (
confirm(L._('Are you sure you want to clone this map and all its datalayers?'))
) {
const url = L.Util.template(this.options.urls.map_clone, {
map_id: this.options.umap_id,
})
this.post(url)
const url = this.urls.get('map_clone', this.options.umap_id);
this.post(url);
}
},

Expand Down Expand Up @@ -1960,17 +1940,17 @@ L.U.Map.include({
},

openExternalRouting: function (e) {
const url = this.options.urls.routing
if (url) {
const params = {
let url = this.urls.get(
'routing',
{
lat: e.latlng.lat,
lng: e.latlng.lng,
locale: L.locale,
zoom: this.getZoom(),
}
window.open(L.Util.template(url, params))
}
return
);
if (url)
window.open(url)
},

getMap: function () {
Expand Down
28 changes: 6 additions & 22 deletions umap/static/umap/js/umap.layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ L.U.Layer = {
return []
},

postUpdate: function () {},
postUpdate: function () { },

hasDataVisible: function () {
return !!Object.keys(this._layers).length
Expand Down Expand Up @@ -436,8 +436,8 @@ L.U.Layer.Heat = L.HeatLayer.extend({
this._latlngs[i].alt !== undefined
? this._latlngs[i].alt
: this._latlngs[i][2] !== undefined
? +this._latlngs[i][2]
: 1
? +this._latlngs[i][2]
: 1

grid[y] = grid[y] || []
cell = grid[y][x]
Expand Down Expand Up @@ -1045,23 +1045,6 @@ L.U.DataLayer = L.Evented.extend({
})
},

getEditUrl: function () {
return L.Util.template(this.map.options.urls.datalayer_update, {
map_id: this.map.options.umap_id,
pk: this.umap_id,
})
},

getCreateUrl: function () {
return L.Util.template(this.map.options.urls.datalayer_create, {
map_id: this.map.options.umap_id,
})
},

getSaveUrl: function () {
return (this.umap_id && this.getEditUrl()) || this.getCreateUrl()
},

getColor: function () {
return this.options.color || this.map.getOption('color')
},
Expand Down Expand Up @@ -1531,8 +1514,9 @@ L.U.DataLayer = L.Evented.extend({
formData.append('settings', JSON.stringify(this.options))
// Filename support is shaky, don't do it for now.
const blob = new Blob([JSON.stringify(geojson)], { type: 'application/json' })
formData.append('geojson', blob)
this.map.post(this.getSaveUrl(), {
formData.append('geojson', blob);
let saveUrl = this.map.urls.get("datalayer_save", { map_id: this.map.options.umap_id, pk: this.umap_id })
this.map.post(saveUrl, {
data: formData,
callback: function (data, response) {
// Response contains geojson only if save has conflicted and conflicts have
Expand Down
2 changes: 1 addition & 1 deletion umap/static/umap/test/Util.js
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ describe('L.Util', function () {
assert.equal(L.Util.normalize('aéroport'), 'aeroport')
// American é
assert.equal(L.Util.normalize('aéroport'), 'aeroport')
})
});
})

describe("#sortFeatures()", function () {
Expand Down
40 changes: 22 additions & 18 deletions umap/static/umap/test/index.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<!DOCTYPE html>
<html>
<head>
<title>Umap front Tests</title>
Expand Down Expand Up @@ -27,6 +28,7 @@
<script src="../vendors/tokml/tokml.js"></script>
<script src="../vendors/simple-statistics/simple-statistics.min.js"></script>
<script src="../vendors/colorbrewer/colorbrewer.js"></script>
<script type="module" src="../js/bindModules.mjs"></script>
<script src="../js/umap.core.js"></script>
<script src="../js/umap.autocomplete.js"></script>
<script src="../js/umap.popup.js"></script>
Expand All @@ -47,8 +49,10 @@
<link rel="stylesheet" href="../vendors/minimap/Control.MiniMap.css" />
<link rel="stylesheet" href="../vendors/editinosm/Leaflet.EditInOSM.css" />
<link rel="stylesheet" href="../vendors/markercluster/MarkerCluster.css" />
<link rel="stylesheet" href="../vendors/markercluster/MarkerCluster.Default.css" />
<link rel="stylesheet" href="../vendors/contextmenu/leaflet.contextmenu.css" />
<link rel="stylesheet"
href="../vendors/markercluster/MarkerCluster.Default.css" />
<link rel="stylesheet"
href="../vendors/contextmenu/leaflet.contextmenu.css" />
<link rel="stylesheet" href="../vendors/toolbar/leaflet.toolbar.css" />
<link rel="stylesheet" href="../vendors/measurable/Leaflet.Measurable.css" />
<link rel="stylesheet" href="../../umap/font.css" />
Expand All @@ -57,7 +61,6 @@
<link rel="stylesheet" href="../../umap/nav.css" />
<link rel="stylesheet" href="../../umap/map.css" />
<link rel="stylesheet" href="../../umap/theme.css" />

<script src="../../../../node_modules/sinon/pkg/sinon.js"></script>
<script src="../../../../node_modules/mocha/mocha.js"></script>
<script src="../../../../node_modules/chai/chai.js"></script>
Expand Down Expand Up @@ -86,21 +89,22 @@
<script src="./Permissions.js"></script>
<script src="./Choropleth.js"></script>
<style type="text/css">
#mocha {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 10000;
background-color: white;
box-shadow: 0px 0px 8px 0px black;
overflow-y: auto;
display: none;
}
#mocha-stats {
position: absolute;
}
#mocha {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 10000;
background-color: white;
box-shadow: 0px 0px 8px 0px black;
overflow-y: auto;
display: none;
}

#mocha-stats {
position: absolute;
}
</style>
</head>
<body>
Expand Down
2 changes: 1 addition & 1 deletion umap/templates/umap/content.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
{% endblock content %}
{% block bottom_js %}
{{ block.super }}
<script type="text/javascript">
<script defer type="text/javascript">
!(function () {
const ui = new L.U.UI(document.querySelector('header'))
const xhr = new L.U.Xhr(ui)
Expand Down
1 change: 1 addition & 0 deletions umap/templates/umap/js.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,5 @@
<script src="{{ STATIC_URL }}umap/js/umap.browser.js"></script>
<script src="{{ STATIC_URL }}umap/js/umap.js"></script>
<script src="{{ STATIC_URL }}umap/js/umap.ui.js"></script>
<script type="module" src="{{ STATIC_URL }}umap/js/bindModules.mjs"></script>
{% endcompress %}
6 changes: 4 additions & 2 deletions umap/templates/umap/map_fragment.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{% load umap_tags %}
<div id="{{ unique_id }}" class="map_fragment"></div>
<!-- djlint:off -->
<script type="text/javascript">
new L.U.Map("{{ unique_id }}", {{ map_settings|notag|safe }})
<script defer type="text/javascript">
window.addEventListener('load', (event) => {
new L.U.Map("{{ unique_id }}", {{ map_settings|notag|safe }})
});
</script>
<!-- djlint:on -->
Loading

0 comments on commit 6bcde85

Please sign in to comment.