Merge pull request #1940 from umap-project/apply-biome-safe

chore: apply Biome safe changes
This commit is contained in:
David Larlet 2024-06-25 16:04:25 -04:00 committed by GitHub
commit 88d1151972
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 264 additions and 364 deletions

View file

@ -140,7 +140,7 @@ class uMapAlertConflict extends uMapAlert {
// biome-ignore lint/style/useNumberNamespace: Number.Infinity returns undefined by default // biome-ignore lint/style/useNumberNamespace: Number.Infinity returns undefined by default
const { const {
level = 'info', level = 'info',
duration = Infinity, duration = Number.POSITIVE_INFINITY,
message = '', message = '',
forceCallback = undefined, forceCallback = undefined,
} = event.detail } = event.detail

View file

@ -1,8 +1,8 @@
import { import {
DomUtil,
DomEvent, DomEvent,
setOptions, DomUtil,
Util, Util,
setOptions,
} from '../../vendors/leaflet/leaflet-src.esm.js' } from '../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from './i18n.js' import { translate } from './i18n.js'
import { Request, ServerRequest } from './request.js' import { Request, ServerRequest } from './request.js'

View file

@ -1,4 +1,4 @@
import { DomUtil, DomEvent, stamp } from '../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil, stamp } from '../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from './i18n.js' import { translate } from './i18n.js'
export default class Browser { export default class Browser {
@ -90,7 +90,7 @@ export default class Browser {
container.innerHTML = '' container.innerHTML = ''
datalayer.eachFeature((feature) => this.addFeature(feature, container)) datalayer.eachFeature((feature) => this.addFeature(feature, container))
let total = datalayer.count(), const total = datalayer.count(),
current = container.querySelectorAll('li').length, current = container.querySelectorAll('li').length,
count = total == current ? total : `${current}/${total}` count = total == current ? total : `${current}/${total}`
const counter = DomUtil.create('span', 'datalayer-counter', headline) const counter = DomUtil.create('span', 'datalayer-counter', headline)

View file

@ -18,7 +18,7 @@ export default class Caption {
open() { open() {
const container = DomUtil.create('div', 'umap-caption') const container = DomUtil.create('div', 'umap-caption')
const hgroup = DomUtil.element({tagName: 'hgroup', parent: container}) const hgroup = DomUtil.element({ tagName: 'hgroup', parent: container })
DomUtil.createTitle(hgroup, this.map.options.name, 'icon-caption icon-block') DomUtil.createTitle(hgroup, this.map.options.name, 'icon-caption icon-block')
this.map.permissions.addOwnerLink('h4', hgroup) this.map.permissions.addOwnerLink('h4', hgroup)
if (this.map.options.description) { if (this.map.options.description) {

View file

@ -1,5 +1,5 @@
import { default as DOMPurifyInitializer } from '../../vendors/dompurify/purify.es.js'
import { JSDOM } from 'jsdom' import { JSDOM } from 'jsdom'
import { default as DOMPurifyInitializer } from '../../vendors/dompurify/purify.es.js'
console.log(DOMPurifyInitializer) console.log(DOMPurifyInitializer)

View file

@ -1,4 +1,4 @@
import { DomUtil, DomEvent, stamp } from '../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil, stamp } from '../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from './i18n.js' import { translate } from './i18n.js'
import * as Utils from './utils.js' import * as Utils from './utils.js'
@ -57,7 +57,7 @@ export default class Facets {
} }
isActive() { isActive() {
for (let { type, min, max, choices } of Object.values(this.selected)) { for (const { type, min, max, choices } of Object.values(this.selected)) {
if (min !== undefined || max != undefined || choices?.length) { if (min !== undefined || max != undefined || choices?.length) {
return true return true
} }
@ -71,7 +71,7 @@ export default class Facets {
const facetProperties = this.compute(names, defined) const facetProperties = this.compute(names, defined)
const fields = names.map((name) => { const fields = names.map((name) => {
let criteria = facetProperties[name] const criteria = facetProperties[name]
let handler = 'FacetSearchChoices' let handler = 'FacetSearchChoices'
switch (criteria['type']) { switch (criteria['type']) {
case 'number': case 'number':
@ -84,7 +84,7 @@ export default class Facets {
handler = 'FacetSearchDateTime' handler = 'FacetSearchDateTime'
break break
} }
let label = defined[name]['label'] const label = defined[name]['label']
return [ return [
`selected.${name}`, `selected.${name}`,
{ {
@ -112,7 +112,7 @@ export default class Facets {
getParser(type) { getParser(type) {
switch (type) { switch (type) {
case 'number': case 'number':
return parseFloat return Number.parseFloat
case 'datetime': case 'datetime':
return (v) => new Date(v) return (v) => new Date(v)
case 'date': case 'date':

View file

@ -1,24 +1,24 @@
import URLs from './urls.js'
import Browser from './browser.js'
import Facets from './facets.js'
import Caption from './caption.js'
import { Panel, EditPanel, FullPanel } from './ui/panel.js'
import Dialog from './ui/dialog.js'
import Tooltip from './ui/tooltip.js'
import Rules from './rules.js'
import * as Utils from './utils.js'
import { SCHEMA } from './schema.js'
import { Request, ServerRequest, RequestError, HTTPError, NOKError } from './request.js'
import { AjaxAutocomplete, AjaxAutocompleteMultiple } from './autocomplete.js'
import Orderable from './orderable.js'
import Importer from './importer.js'
import Help from './help.js'
import { SyncEngine } from './sync/engine.js'
import { import {
uMapAlert as Alert, uMapAlert as Alert,
uMapAlertCreation as AlertCreation,
uMapAlertConflict as AlertConflict, uMapAlertConflict as AlertConflict,
uMapAlertCreation as AlertCreation,
} from '../components/alerts/alert.js' } from '../components/alerts/alert.js'
import { AjaxAutocomplete, AjaxAutocompleteMultiple } from './autocomplete.js'
import Browser from './browser.js'
import Caption from './caption.js'
import Facets from './facets.js'
import Help from './help.js'
import Importer from './importer.js'
import Orderable from './orderable.js'
import { HTTPError, NOKError, Request, RequestError, ServerRequest } from './request.js'
import Rules from './rules.js'
import { SCHEMA } from './schema.js'
import { SyncEngine } from './sync/engine.js'
import Dialog from './ui/dialog.js'
import { EditPanel, FullPanel, Panel } from './ui/panel.js'
import Tooltip from './ui/tooltip.js'
import URLs from './urls.js'
import * as Utils from './utils.js'
// Import modules and export them to the global scope. // Import modules and export them to the global scope.
// For the not yet module-compatible JS out there. // For the not yet module-compatible JS out there.

View file

@ -1,4 +1,4 @@
import { DomUtil, DomEvent } from '../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil } from '../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from './i18n.js' import { translate } from './i18n.js'
const SHORTCUTS = { const SHORTCUTS = {

View file

@ -1,8 +1,8 @@
import { DomUtil, DomEvent } from '../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil } from '../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from './i18n.js'
import { uMapAlert as Alert } from '../components/alerts/alert.js' import { uMapAlert as Alert } from '../components/alerts/alert.js'
import Dialog from './ui/dialog.js' import { translate } from './i18n.js'
import { SCHEMA } from './schema.js' import { SCHEMA } from './schema.js'
import Dialog from './ui/dialog.js'
import * as Utils from './utils.js' import * as Utils from './utils.js'
const TEMPLATE = ` const TEMPLATE = `

View file

@ -1,8 +1,8 @@
import { DomUtil, DomEvent } from '../../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil } from '../../../vendors/leaflet/leaflet-src.esm.js'
import { uMapAlert as Alert } from '../../components/alerts/alert.js'
import { BaseAjax, SingleMixin } from '../autocomplete.js' import { BaseAjax, SingleMixin } from '../autocomplete.js'
import { translate } from '../i18n.js' import { translate } from '../i18n.js'
import * as Utils from '../utils.js' import * as Utils from '../utils.js'
import { uMapAlert as Alert } from '../../components/alerts/alert.js'
const BOUNDARY_TYPES = { const BOUNDARY_TYPES = {
admin_6: 'département', admin_6: 'département',
@ -54,7 +54,7 @@ export class Importer {
const select = container.querySelector('select') const select = container.querySelector('select')
if (response && response.ok) { if (response && response.ok) {
const { themes } = await response.json() const { themes } = await response.json()
themes.sort((a, b) => Utils.naturalSort(a['name:fr'], b ['name:fr'])) themes.sort((a, b) => Utils.naturalSort(a['name:fr'], b['name:fr']))
for (const theme of themes) { for (const theme of themes) {
DomUtil.element({ DomUtil.element({
tagName: 'option', tagName: 'option',

View file

@ -1,7 +1,7 @@
import { DomUtil } from '../../../vendors/leaflet/leaflet-src.esm.js' import { DomUtil } from '../../../vendors/leaflet/leaflet-src.esm.js'
import { uMapAlert as Alert } from '../../components/alerts/alert.js'
import { BaseAjax, SingleMixin } from '../autocomplete.js' import { BaseAjax, SingleMixin } from '../autocomplete.js'
import { translate } from '../i18n.js' import { translate } from '../i18n.js'
import { uMapAlert as Alert } from '../../components/alerts/alert.js'
const TEMPLATE = ` const TEMPLATE = `
<h3>Overpass</h3> <h3>Overpass</h3>
@ -68,7 +68,7 @@ export class Importer {
if (!tags.startsWith('[')) tags = `[${tags}]` if (!tags.startsWith('[')) tags = `[${tags}]`
let area = '{south},{west},{north},{east}' let area = '{south},{west},{north},{east}'
if (boundary) area = `area:${boundary}` if (boundary) area = `area:${boundary}`
let query = `[out:json];nwr${tags}(${area});out ${outMode};` const query = `[out:json];nwr${tags}(${area});out ${outMode};`
importer.url = `${this.baseUrl}?data=${query}` importer.url = `${this.baseUrl}?data=${query}`
if (boundary) importer.layerName = boundaryName if (boundary) importer.layerName = boundaryName
importer.format = 'osm' importer.format = 'osm'

View file

@ -1,5 +1,5 @@
import { translate } from './i18n.js'
import { uMapAlert as Alert } from '../components/alerts/alert.js' import { uMapAlert as Alert } from '../components/alerts/alert.js'
import { translate } from './i18n.js'
export class RequestError extends Error {} export class RequestError extends Error {}

View file

@ -1,9 +1,8 @@
import { DomUtil, DomEvent, stamp } from '../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil, stamp } from '../../vendors/leaflet/leaflet-src.esm.js'
import * as Utils from './utils.js'
import { translate } from './i18n.js' import { translate } from './i18n.js'
import * as Utils from './utils.js'
class Rule { class Rule {
get condition() { get condition() {
return this._condition return this._condition
} }
@ -13,7 +12,6 @@ class Rule {
this.parse() this.parse()
} }
get isDirty() { get isDirty() {
return this._isDirty return this._isDirty
} }
@ -76,7 +74,7 @@ class Rule {
if (vars.length != 2) return if (vars.length != 2) return
this.key = vars[0] this.key = vars[0]
this.expected = vars[1] this.expected = vars[1]
if (!isNaN(this.expected)) this.cast = parseFloat if (!isNaN(this.expected)) this.cast = Number.parseFloat
else if (['true', 'false'].includes(this.expected)) this.cast = (v) => !!v else if (['true', 'false'].includes(this.expected)) this.cast = (v) => !!v
this.expected = this.cast(this.expected) this.expected = this.cast(this.expected)
} }

View file

@ -1,5 +1,5 @@
import { DataLayerUpdater, FeatureUpdater, MapUpdater } from './updaters.js'
import { WebSocketTransport } from './websocket.js' import { WebSocketTransport } from './websocket.js'
import { MapUpdater, DataLayerUpdater, FeatureUpdater } from './updaters.js'
export class SyncEngine { export class SyncEngine {
constructor(map) { constructor(map) {
@ -37,7 +37,7 @@ export class SyncEngine {
// This method is called by the transport layer on new messages // This method is called by the transport layer on new messages
receive({ kind, ...payload }) { receive({ kind, ...payload }) {
if (kind == 'operation') { if (kind == 'operation') {
let updater = this._getUpdater(payload.subject, payload.metadata) const updater = this._getUpdater(payload.subject, payload.metadata)
updater.applyMessage(payload) updater.applyMessage(payload)
} else { } else {
throw new Error(`Unknown dispatch kind: ${kind}`) throw new Error(`Unknown dispatch kind: ${kind}`)

View file

@ -35,7 +35,7 @@ class BaseUpdater {
} }
applyMessage(payload) { applyMessage(payload) {
let { verb } = payload const { verb } = payload
return this[verb](payload) return this[verb](payload)
} }
} }
@ -69,7 +69,7 @@ export class FeatureUpdater extends BaseUpdater {
// Create or update an object at a specific position // Create or update an object at a specific position
upsert({ metadata, value }) { upsert({ metadata, value }) {
let { id, layerId } = metadata const { id, layerId } = metadata
const datalayer = this.getDataLayerFromID(layerId) const datalayer = this.getDataLayerFromID(layerId)
let feature = this.getFeatureFromMetadata(metadata, value) let feature = this.getFeatureFromMetadata(metadata, value)
@ -84,7 +84,7 @@ export class FeatureUpdater extends BaseUpdater {
// Update a property of an object // Update a property of an object
update({ key, metadata, value }) { update({ key, metadata, value }) {
let feature = this.getFeatureFromMetadata(metadata) const feature = this.getFeatureFromMetadata(metadata)
if (feature === undefined) { if (feature === undefined) {
console.error(`Unable to find feature with id = ${metadata.id}.`) console.error(`Unable to find feature with id = ${metadata.id}.`)
} }
@ -103,7 +103,7 @@ export class FeatureUpdater extends BaseUpdater {
delete({ metadata }) { delete({ metadata }) {
// XXX Distinguish between properties getting deleted // XXX Distinguish between properties getting deleted
// and the wole feature getting deleted // and the wole feature getting deleted
let feature = this.getFeatureFromMetadata(metadata) const feature = this.getFeatureFromMetadata(metadata)
if (feature) feature.del(false) if (feature) feature.del(false)
} }
} }

View file

@ -15,7 +15,7 @@ export class WebSocketTransport {
send(kind, payload) { send(kind, payload) {
const message = { ...payload } const message = { ...payload }
message.kind = kind message.kind = kind
let encoded = JSON.stringify(message) const encoded = JSON.stringify(message)
this.websocket.send(encoded) this.websocket.send(encoded)
} }

View file

@ -1,4 +1,4 @@
import { DomUtil, DomEvent } from '../../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil } from '../../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from '../i18n.js' import { translate } from '../i18n.js'
export default class Dialog { export default class Dialog {

View file

@ -1,4 +1,4 @@
import { DomUtil, DomEvent } from '../../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil } from '../../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from '../i18n.js' import { translate } from '../i18n.js'
export class Panel { export class Panel {

View file

@ -1,4 +1,4 @@
import { DomUtil, DomEvent } from '../../../vendors/leaflet/leaflet-src.esm.js' import { DomEvent, DomUtil } from '../../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from '../i18n.js' import { translate } from '../i18n.js'
export default class Tooltip { export default class Tooltip {
@ -34,7 +34,7 @@ export default class Tooltip {
if (opts.anchor) { if (opts.anchor) {
L.DomEvent.once(opts.anchor, 'mouseout', closeIt) L.DomEvent.once(opts.anchor, 'mouseout', closeIt)
} }
if (opts.duration !== Infinity) { if (opts.duration !== Number.POSITIVE_INFINITY) {
window.setTimeout(closeIt, opts.duration || 3000) window.setTimeout(closeIt, opts.duration || 3000)
} }
} }

View file

@ -36,7 +36,7 @@ export function checkId(string) {
*/ */
export function getImpactsFromSchema(fields, schema) { export function getImpactsFromSchema(fields, schema) {
schema = schema || U.SCHEMA schema = schema || U.SCHEMA
let impacted = fields const impacted = fields
.map((field) => { .map((field) => {
// remove the option prefix for fields // remove the option prefix for fields
// And only keep the first part in case of a subfield // And only keep the first part in case of a subfield
@ -120,7 +120,7 @@ export function toHTML(r, options) {
r = r.replace(/^\*\* (.*)/gm, '<ul><ul><li>$1</li></ul></ul>') r = r.replace(/^\*\* (.*)/gm, '<ul><ul><li>$1</li></ul></ul>')
r = r.replace(/^\* (.*)/gm, '<ul><li>$1</li></ul>') r = r.replace(/^\* (.*)/gm, '<ul><li>$1</li></ul>')
for (let ii = 0; ii < 3; ii++) { for (let ii = 0; ii < 3; ii++) {
r = r.replace(new RegExp(`</ul>(\r\n|\r|\n)<ul>`, 'g'), '') r = r.replace(/<\/ul>(\r\n|\r|\n)<ul>/g, '')
} }
// headings and hr // headings and hr
@ -352,7 +352,7 @@ export function normalize(s) {
var templateRe = /\{ *([\w_ -]+) *\}/g var templateRe = /\{ *([\w_ -]+) *\}/g
export function template(str, data) { export function template(str, data) {
return str.replace(templateRe, function (str, key) { return str.replace(templateRe, (str, key) => {
var value = data[key] var value = data[key]
if (value === undefined) { if (value === undefined) {

View file

@ -162,7 +162,7 @@ U.BaseFeatureAction = L.ToolbarAction.extend({
this.postInit() this.postInit()
}, },
postInit: function () {}, postInit: () => {},
hideToolbar: function () { hideToolbar: function () {
this.map.removeLayer(this.toolbar) this.map.removeLayer(this.toolbar)
@ -356,7 +356,7 @@ U.DropControl = L.Class.extend({
this.dropzone.classList.add('umap-dragover') this.dropzone.classList.add('umap-dragover')
}, },
dragover: function (e) { dragover: (e) => {
L.DomEvent.stop(e) L.DomEvent.stop(e)
}, },
@ -393,7 +393,7 @@ U.EditControl = L.Control.extend({
L.DomEvent.on( L.DomEvent.on(
enableEditing, enableEditing,
'mouseover', 'mouseover',
function () { () => {
map.tooltip.open({ map.tooltip.open({
content: map.help.displayLabel('TOGGLE_EDIT'), content: map.help.displayLabel('TOGGLE_EDIT'),
anchor: enableEditing, anchor: enableEditing,
@ -503,7 +503,7 @@ L.Control.Button = L.Control.extend({
return container return container
}, },
afterAdd: function (container) {}, afterAdd: (container) => {},
}) })
U.DataLayersControl = L.Control.Button.extend({ U.DataLayersControl = L.Control.Button.extend({
@ -1205,9 +1205,7 @@ L.Control.MiniMap.include({
this._miniMap.addLayer(this._layer) this._miniMap.addLayer(this._layer)
}, },
_cloneLayer: function (layer) { _cloneLayer: (layer) => new L.TileLayer(layer._url, L.Util.extend({}, layer.options)),
return new L.TileLayer(layer._url, L.Util.extend({}, layer.options))
},
}) })
L.Control.Loading.include({ L.Control.Loading.include({
@ -1364,7 +1362,7 @@ U.Editable = L.Editable.extend({
this.map.ui.closeTooltip() this.map.ui.closeTooltip()
}, },
onVertexRawClick: function (e) { onVertexRawClick: (e) => {
e.layer.onVertexRawClick(e) e.layer.onVertexRawClick(e)
L.DomEvent.stop(e) L.DomEvent.stop(e)
e.cancel() e.cancel()

View file

@ -1,4 +1,4 @@
L.Util.copyToClipboard = function (textToCopy) { L.Util.copyToClipboard = (textToCopy) => {
// https://stackoverflow.com/a/65996386 // https://stackoverflow.com/a/65996386
// Navigator clipboard api needs a secure context (https) // Navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) { if (navigator.clipboard && window.isSecureContext) {
@ -25,7 +25,7 @@ L.Util.copyToClipboard = function (textToCopy) {
} }
} }
L.Util.queryString = function (name, fallback) { L.Util.queryString = (name, fallback) => {
const decode = (s) => decodeURIComponent(s.replace(/\+/g, ' ')) const decode = (s) => decodeURIComponent(s.replace(/\+/g, ' '))
const qs = window.location.search.slice(1).split('&'), const qs = window.location.search.slice(1).split('&'),
qa = {} qa = {}
@ -37,27 +37,27 @@ L.Util.queryString = function (name, fallback) {
return qa[name] || fallback return qa[name] || fallback
} }
L.Util.booleanFromQueryString = function (name) { L.Util.booleanFromQueryString = (name) => {
const value = L.Util.queryString(name) const value = L.Util.queryString(name)
return value === '1' || value === 'true' return value === '1' || value === 'true'
} }
L.Util.setFromQueryString = function (options, name) { L.Util.setFromQueryString = (options, name) => {
const value = L.Util.queryString(name) const value = L.Util.queryString(name)
if (typeof value !== 'undefined') options[name] = value if (typeof value !== 'undefined') options[name] = value
} }
L.Util.setBooleanFromQueryString = function (options, name) { L.Util.setBooleanFromQueryString = (options, name) => {
const value = L.Util.queryString(name) const value = L.Util.queryString(name)
if (typeof value !== 'undefined') options[name] = value == '1' || value == 'true' if (typeof value !== 'undefined') options[name] = value == '1' || value == 'true'
} }
L.Util.setNumberFromQueryString = function (options, name) { L.Util.setNumberFromQueryString = (options, name) => {
const value = +L.Util.queryString(name) const value = +L.Util.queryString(name)
if (!isNaN(value)) options[name] = value if (!isNaN(value)) options[name] = value
} }
L.Util.setNullableBooleanFromQueryString = function (options, name) { L.Util.setNullableBooleanFromQueryString = (options, name) => {
let value = L.Util.queryString(name) let value = L.Util.queryString(name)
if (typeof value !== 'undefined') { if (typeof value !== 'undefined') {
if (value === 'null') value = null if (value === 'null') value = null
@ -222,7 +222,11 @@ L.DomUtil.contrastedColor = (el, bgcolor) => {
let rgb = window.getComputedStyle(el).getPropertyValue('background-color') let rgb = window.getComputedStyle(el).getPropertyValue('background-color')
rgb = L.DomUtil.RGBRegex.exec(rgb) rgb = L.DomUtil.RGBRegex.exec(rgb)
if (!rgb || rgb.length !== 4) return out if (!rgb || rgb.length !== 4) return out
rgb = [parseInt(rgb[1], 10), parseInt(rgb[2], 10), parseInt(rgb[3], 10)] rgb = [
Number.parseInt(rgb[1], 10),
Number.parseInt(rgb[2], 10),
Number.parseInt(rgb[3], 10),
]
out = L.DomUtil.contrastWCAG21(rgb) out = L.DomUtil.contrastWCAG21(rgb)
if (bgcolor) _CACHE_CONSTRAST[bgcolor] = out if (bgcolor) _CACHE_CONSTRAST[bgcolor] = out
return out return out

View file

@ -7,15 +7,12 @@ U.DataLayerPermissions = L.Class.extend({
this.options = L.Util.setOptions(this, datalayer.options.permissions) this.options = L.Util.setOptions(this, datalayer.options.permissions)
this.datalayer = datalayer this.datalayer = datalayer
let isDirty = false let isDirty = false
const self = this
try { try {
Object.defineProperty(this, 'isDirty', { Object.defineProperty(this, 'isDirty', {
get: function () { get: () => isDirty,
return isDirty set: (status) => {
},
set: function (status) {
isDirty = status isDirty = status
if (status) self.datalayer.isDirty = status if (status) this.datalayer.isDirty = status
}, },
}) })
} catch (e) { } catch (e) {

View file

@ -58,19 +58,16 @@ U.FeatureMixin = {
} }
} }
let isDirty = false let isDirty = false
const self = this
try { try {
Object.defineProperty(this, 'isDirty', { Object.defineProperty(this, 'isDirty', {
get: function () { get: () => isDirty,
return isDirty set: (status) => {
},
set: function (status) {
if (!isDirty && status) { if (!isDirty && status) {
self.fire('isdirty') this.fire('isdirty')
} }
isDirty = status isDirty = status
if (self.datalayer) { if (this.datalayer) {
self.datalayer.isDirty = status this.datalayer.isDirty = status
} }
}, },
}) })
@ -82,7 +79,7 @@ U.FeatureMixin = {
this.parentClass.prototype.initialize.call(this, latlng, options) this.parentClass.prototype.initialize.call(this, latlng, options)
}, },
preInit: function () {}, preInit: () => {},
isReadOnly: function () { isReadOnly: function () {
return this.datalayer && this.datalayer.isDataReadOnly() return this.datalayer && this.datalayer.isDataReadOnly()
@ -228,19 +225,17 @@ U.FeatureMixin = {
popupFieldset.appendChild(builder.build()) popupFieldset.appendChild(builder.build())
}, },
getInteractionOptions: function () { getInteractionOptions: () => [
return [ 'properties._umap_options.popupShape',
'properties._umap_options.popupShape', 'properties._umap_options.popupTemplate',
'properties._umap_options.popupTemplate', 'properties._umap_options.showLabel',
'properties._umap_options.showLabel', 'properties._umap_options.labelDirection',
'properties._umap_options.labelDirection', 'properties._umap_options.labelInteractive',
'properties._umap_options.labelInteractive', 'properties._umap_options.outlink',
'properties._umap_options.outlink', 'properties._umap_options.outlinkTarget',
'properties._umap_options.outlinkTarget', ],
]
},
endEdit: function () {}, endEdit: () => {},
getDisplayName: function (fallback) { getDisplayName: function (fallback) {
if (fallback === undefined) fallback = this.datalayer.options.name if (fallback === undefined) fallback = this.datalayer.options.name
@ -298,7 +293,7 @@ U.FeatureMixin = {
} }
}, },
cleanProperty: function ([key, value]) { cleanProperty: ([key, value]) => {
// dot in key will break the dot based property access // dot in key will break the dot based property access
// while editing the feature // while editing the feature
key = key.replace('.', '_') key = key.replace('.', '_')
@ -434,13 +429,9 @@ U.FeatureMixin = {
L.DomEvent.stop(e) L.DomEvent.stop(e)
}, },
getPopupToolbarAnchor: function () { getPopupToolbarAnchor: () => [0, 0],
return [0, 0]
},
getInplaceToolbarActions: function (e) { getInplaceToolbarActions: (e) => [U.ToggleEditAction, U.DeleteFeatureAction],
return [U.ToggleEditAction, U.DeleteFeatureAction]
},
_showContextMenu: function (e) { _showContextMenu: function (e) {
L.DomEvent.stop(e) L.DomEvent.stop(e)
@ -463,7 +454,7 @@ U.FeatureMixin = {
if (permalink) if (permalink)
items.push({ items.push({
text: L._('Permalink'), text: L._('Permalink'),
callback: function () { callback: () => {
window.open(permalink) window.open(permalink)
}, },
}) })
@ -554,9 +545,9 @@ U.FeatureMixin = {
matchFacets: function () { matchFacets: function () {
const selected = this.map.facets.selected const selected = this.map.facets.selected
for (let [name, { type, min, max, choices }] of Object.entries(selected)) { for (const [name, { type, min, max, choices }] of Object.entries(selected)) {
let value = this.properties[name] let value = this.properties[name]
let parser = this.map.facets.getParser(type) const parser = this.map.facets.getParser(type)
value = parser(value) value = parser(value)
switch (type) { switch (type) {
case 'date': case 'date':
@ -581,13 +572,9 @@ U.FeatureMixin = {
}).addTo(this.map, this, e.latlng, e.vertex) }).addTo(this.map, this, e.latlng, e.vertex)
}, },
getVertexActions: function () { getVertexActions: () => [U.DeleteVertexAction],
return [U.DeleteVertexAction]
},
isMulti: function () { isMulti: () => false,
return false
},
clone: function () { clone: function () {
const geoJSON = this.toGeoJSON() const geoJSON = this.toGeoJSON()
@ -746,22 +733,16 @@ U.Marker = L.Marker.extend({
return this._latlng return this._latlng
}, },
getClassName: function () { getClassName: () => 'marker',
return 'marker'
},
getShapeOptions: function () { getShapeOptions: () => [
return [ 'properties._umap_options.color',
'properties._umap_options.color', 'properties._umap_options.iconClass',
'properties._umap_options.iconClass', 'properties._umap_options.iconUrl',
'properties._umap_options.iconUrl', 'properties._umap_options.iconOpacity',
'properties._umap_options.iconOpacity', ],
]
},
getAdvancedOptions: function () { getAdvancedOptions: () => ['properties._umap_options.zoomTo'],
return ['properties._umap_options.zoomTo']
},
appendEditFieldsets: function (container) { appendEditFieldsets: function (container) {
U.FeatureMixin.appendEditFieldsets.call(this, container) U.FeatureMixin.appendEditFieldsets.call(this, container)
@ -847,21 +828,17 @@ U.PathMixin = {
'interactive', 'interactive',
], ],
getShapeOptions: function () { getShapeOptions: () => [
return [ 'properties._umap_options.color',
'properties._umap_options.color', 'properties._umap_options.opacity',
'properties._umap_options.opacity', 'properties._umap_options.weight',
'properties._umap_options.weight', ],
]
},
getAdvancedOptions: function () { getAdvancedOptions: () => [
return [ 'properties._umap_options.smoothFactor',
'properties._umap_options.smoothFactor', 'properties._umap_options.dashArray',
'properties._umap_options.dashArray', 'properties._umap_options.zoomTo',
'properties._umap_options.zoomTo', ],
]
},
setStyle: function (options) { setStyle: function (options) {
options = options || {} options = options || {}
@ -1070,13 +1047,9 @@ U.Polyline = L.Polyline.extend({
mainColor: 'color', mainColor: 'color',
}, },
isSameClass: function (other) { isSameClass: (other) => other instanceof U.Polyline,
return other instanceof U.Polyline
},
getClassName: function () { getClassName: () => 'polyline',
return 'polyline'
},
getMeasure: function (shape) { getMeasure: function (shape) {
const length = L.GeoUtil.lineLength(this.map, shape || this._defaultShape()) const length = L.GeoUtil.lineLength(this.map, shape || this._defaultShape())
@ -1214,15 +1187,11 @@ U.Polygon = L.Polygon.extend({
mainColor: 'fillColor', mainColor: 'fillColor',
}, },
isSameClass: function (other) { isSameClass: (other) => other instanceof U.Polygon,
return other instanceof U.Polygon
},
getClassName: function () { getClassName: () => 'polygon',
return 'polygon'
},
getShapeOptions: function () { getShapeOptions: () => {
const options = U.PathMixin.getShapeOptions() const options = U.PathMixin.getShapeOptions()
options.push( options.push(
'properties._umap_options.stroke', 'properties._umap_options.stroke',
@ -1233,7 +1202,7 @@ U.Polygon = L.Polygon.extend({
return options return options
}, },
getInteractionOptions: function () { getInteractionOptions: () => {
const options = U.FeatureMixin.getInteractionOptions() const options = U.FeatureMixin.getInteractionOptions()
options.push('properties._umap_options.interactive') options.push('properties._umap_options.interactive')
return options return options

View file

@ -296,10 +296,9 @@ L.FormBuilder.ColorPicker = L.FormBuilder.Input.extend({
}, },
onBlur: function () { onBlur: function () {
const self = this, const closePicker = () => {
closePicker = () => { this.container.style.display = 'none'
self.container.style.display = 'none' }
}
// We must leave time for the click to be listened. // We must leave time for the click to be listened.
window.setTimeout(closePicker, 100) window.setTimeout(closePicker, 100)
}, },
@ -341,7 +340,7 @@ L.FormBuilder.TextColorPicker = L.FormBuilder.ColorPicker.extend({
}) })
L.FormBuilder.LayerTypeChooser = L.FormBuilder.Select.extend({ L.FormBuilder.LayerTypeChooser = L.FormBuilder.Select.extend({
getOptions: function () { getOptions: () => {
const layer_classes = [ const layer_classes = [
U.Layer.Default, U.Layer.Default,
U.Layer.Cluster, U.Layer.Cluster,
@ -353,7 +352,7 @@ L.FormBuilder.LayerTypeChooser = L.FormBuilder.Select.extend({
}) })
L.FormBuilder.SlideshowDelay = L.FormBuilder.IntSelect.extend({ L.FormBuilder.SlideshowDelay = L.FormBuilder.IntSelect.extend({
getOptions: function () { getOptions: () => {
const options = [] const options = []
for (let i = 1; i < 30; i++) { for (let i = 1; i < 30; i++) {
options.push([i * 1000, L._('{delay} seconds', { delay: i })]) options.push([i * 1000, L._('{delay} seconds', { delay: i })])
@ -459,9 +458,7 @@ L.FormBuilder.BlurInput.include({
}) })
L.FormBuilder.IconUrl = L.FormBuilder.BlurInput.extend({ L.FormBuilder.IconUrl = L.FormBuilder.BlurInput.extend({
type: function () { type: () => 'hidden',
return 'hidden'
},
build: function () { build: function () {
L.FormBuilder.BlurInput.prototype.build.call(this) L.FormBuilder.BlurInput.prototype.build.call(this)
@ -547,10 +544,10 @@ L.FormBuilder.IconUrl = L.FormBuilder.BlurInput.extend({
openTab: function (name) { openTab: function (name) {
const els = this.tabs.querySelectorAll('button') const els = this.tabs.querySelectorAll('button')
for (let el of els) { for (const el of els) {
L.DomUtil.removeClass(el, 'on') L.DomUtil.removeClass(el, 'on')
} }
let el = this.tabs.querySelector(`.tab-${name}`) const el = this.tabs.querySelector(`.tab-${name}`)
L.DomUtil.addClass(el, 'on') L.DomUtil.addClass(el, 'on')
this.body.innerHTML = '' this.body.innerHTML = ''
}, },
@ -612,7 +609,7 @@ L.FormBuilder.IconUrl = L.FormBuilder.BlurInput.extend({
if (name) L.DomUtil.add('h6', '', parent, name) if (name) L.DomUtil.add('h6', '', parent, name)
const grid = L.DomUtil.create('div', 'umap-pictogram-grid', parent) const grid = L.DomUtil.create('div', 'umap-pictogram-grid', parent)
let status = false let status = false
for (let item of items) { for (const item of items) {
status = this.addIconPreview(item, grid) || status status = this.addIconPreview(item, grid) || status
} }
if (status) this.grid.appendChild(parent) if (status) this.grid.appendChild(parent)
@ -630,7 +627,7 @@ L.FormBuilder.IconUrl = L.FormBuilder.BlurInput.extend({
const sorted = Object.entries(categories).toSorted(([a], [b]) => const sorted = Object.entries(categories).toSorted(([a], [b]) =>
U.Utils.naturalSort(a, b, L.lang) U.Utils.naturalSort(a, b, L.lang)
) )
for (let [name, items] of sorted) { for (const [name, items] of sorted) {
this.addCategory(items, name) this.addCategory(items, name)
} }
}, },
@ -701,7 +698,7 @@ L.FormBuilder.IconUrl = L.FormBuilder.BlurInput.extend({
return input return input
}, },
unselectAll: function (container) { unselectAll: (container) => {
const els = container.querySelectorAll('div.selected') const els = container.querySelectorAll('div.selected')
for (const el in els) { for (const el in els) {
if (els.hasOwnProperty(el)) L.DomUtil.removeClass(els[el], 'selected') if (els.hasOwnProperty(el)) L.DomUtil.removeClass(els[el], 'selected')
@ -710,9 +707,7 @@ L.FormBuilder.IconUrl = L.FormBuilder.BlurInput.extend({
}) })
L.FormBuilder.Url = L.FormBuilder.Input.extend({ L.FormBuilder.Url = L.FormBuilder.Input.extend({
type: function () { type: () => 'url',
return 'url'
},
}) })
L.FormBuilder.Switch = L.FormBuilder.CheckBox.extend({ L.FormBuilder.Switch = L.FormBuilder.CheckBox.extend({
@ -780,17 +775,11 @@ L.FormBuilder.FacetSearchChoices = L.FormBuilder.FacetSearchBase.extend({
}) })
L.FormBuilder.MinMaxBase = L.FormBuilder.FacetSearchBase.extend({ L.FormBuilder.MinMaxBase = L.FormBuilder.FacetSearchBase.extend({
getInputType: function (type) { getInputType: (type) => type,
return type
},
getLabels: function () { getLabels: () => [L._('Min'), L._('Max')],
return [L._('Min'), L._('Max')]
},
prepareForHTML: function (value) { prepareForHTML: (value) => value.valueOf(),
return value.valueOf()
},
build: function () { build: function () {
this.container = L.DomUtil.create('fieldset', 'umap-facet', this.parentNode) this.container = L.DomUtil.create('fieldset', 'umap-facet', this.parentNode)
@ -880,19 +869,13 @@ L.FormBuilder.MinMaxBase = L.FormBuilder.FacetSearchBase.extend({
}) })
L.FormBuilder.FacetSearchNumber = L.FormBuilder.MinMaxBase.extend({ L.FormBuilder.FacetSearchNumber = L.FormBuilder.MinMaxBase.extend({
prepareForJS: function (value) { prepareForJS: (value) => new Number(value),
return new Number(value)
},
}) })
L.FormBuilder.FacetSearchDate = L.FormBuilder.MinMaxBase.extend({ L.FormBuilder.FacetSearchDate = L.FormBuilder.MinMaxBase.extend({
prepareForJS: function (value) { prepareForJS: (value) => new Date(value),
return new Date(value)
},
toLocaleDateTime: function (dt) { toLocaleDateTime: (dt) => new Date(dt.valueOf() - dt.getTimezoneOffset() * 60000),
return new Date(dt.valueOf() - dt.getTimezoneOffset() * 60000)
},
prepareForHTML: function (value) { prepareForHTML: function (value) {
// Value must be in local time // Value must be in local time
@ -900,15 +883,11 @@ L.FormBuilder.FacetSearchDate = L.FormBuilder.MinMaxBase.extend({
return this.toLocaleDateTime(value).toISOString().substr(0, 10) return this.toLocaleDateTime(value).toISOString().substr(0, 10)
}, },
getLabels: function () { getLabels: () => [L._('From'), L._('Until')],
return [L._('From'), L._('Until')]
},
}) })
L.FormBuilder.FacetSearchDateTime = L.FormBuilder.FacetSearchDate.extend({ L.FormBuilder.FacetSearchDateTime = L.FormBuilder.FacetSearchDate.extend({
getInputType: function (type) { getInputType: (type) => 'datetime-local',
return 'datetime-local'
},
prepareForHTML: function (value) { prepareForHTML: function (value) {
// Value must be in local time // Value must be in local time
@ -1020,9 +999,7 @@ L.FormBuilder.DataLayersControl = L.FormBuilder.TernaryChoices.extend({
}) })
L.FormBuilder.Range = L.FormBuilder.FloatInput.extend({ L.FormBuilder.Range = L.FormBuilder.FloatInput.extend({
type: function () { type: () => 'range',
return 'range'
},
value: function () { value: function () {
return L.DomUtil.hasClass(this.wrapper, 'undefined') return L.DomUtil.hasClass(this.wrapper, 'undefined')
@ -1124,7 +1101,7 @@ U.FormBuilder = L.FormBuilder.extend({
}, },
computeDefaultOptions: function () { computeDefaultOptions: function () {
for (let [key, schema] of Object.entries(U.SCHEMA)) { for (const [key, schema] of Object.entries(U.SCHEMA)) {
if (schema.type === Boolean) { if (schema.type === Boolean) {
if (schema.nullable) schema.handler = 'NullableChoices' if (schema.nullable) schema.handler = 'NullableChoices'
else schema.handler = 'Switch' else schema.handler = 'Switch'

View file

@ -17,7 +17,7 @@ U.Icon = L.DivIcon.extend({
} }
}, },
_setRecent: function (url) { _setRecent: (url) => {
if (U.Utils.hasVar(url)) return if (U.Utils.hasVar(url)) return
if (url === U.SCHEMA.iconUrl.default) return if (url === U.SCHEMA.iconUrl.default) return
if (U.Icon.RECENT.indexOf(url) === -1) { if (U.Icon.RECENT.indexOf(url) === -1) {
@ -49,14 +49,10 @@ U.Icon = L.DivIcon.extend({
return this.map.getDefaultOption('iconOpacity') return this.map.getDefaultOption('iconOpacity')
}, },
formatUrl: function (url, feature) { formatUrl: (url, feature) =>
return U.Utils.greedyTemplate( U.Utils.greedyTemplate(url || '', feature ? feature.extendedProperties() : {}),
url || '',
feature ? feature.extendedProperties() : {}
)
},
onAdd: function () {}, onAdd: () => {},
}) })
U.Icon.Default = U.Icon.extend({ U.Icon.Default = U.Icon.extend({
@ -208,11 +204,10 @@ U.Icon.Cluster = L.DivIcon.extend({
}, },
}) })
U.Icon.isImg = function (src) { U.Icon.isImg = (src) =>
return U.Utils.isPath(src) || U.Utils.isRemoteUrl(src) || U.Utils.isDataImage(src) U.Utils.isPath(src) || U.Utils.isRemoteUrl(src) || U.Utils.isDataImage(src)
}
U.Icon.makeIconElement = function (src, parent) { U.Icon.makeIconElement = (src, parent) => {
let icon let icon
if (U.Icon.isImg(src)) { if (U.Icon.isImg(src)) {
icon = L.DomUtil.create('img') icon = L.DomUtil.create('img')
@ -225,7 +220,7 @@ U.Icon.makeIconElement = function (src, parent) {
return icon return icon
} }
U.Icon.setIconContrast = function (icon, parent, src, bgcolor) { U.Icon.setIconContrast = (icon, parent, src, bgcolor) => {
/* /*
* icon: the element we'll adapt the style, it can be an image or text * icon: the element we'll adapt the style, it can be an image or text
* parent: the element we'll consider to decide whether to adapt the style, * parent: the element we'll consider to decide whether to adapt the style,

View file

@ -83,18 +83,15 @@ U.Map = L.Map.extend({
} }
let editedFeature = null let editedFeature = null
const self = this
try { try {
Object.defineProperty(this, 'editedFeature', { Object.defineProperty(this, 'editedFeature', {
get: function () { get: () => editedFeature,
return editedFeature set: (feature) => {
},
set: function (feature) {
if (editedFeature && editedFeature !== feature) { if (editedFeature && editedFeature !== feature) {
editedFeature.endEdit() editedFeature.endEdit()
} }
editedFeature = feature editedFeature = feature
self.fire('seteditedfeature') this.fire('seteditedfeature')
}, },
}) })
} catch (e) { } catch (e) {
@ -156,9 +153,7 @@ U.Map = L.Map.extend({
let isDirty = false // self status let isDirty = false // self status
try { try {
Object.defineProperty(this, 'isDirty', { Object.defineProperty(this, 'isDirty', {
get: function () { get: () => isDirty,
return isDirty
},
set: function (status) { set: function (status) {
isDirty = status isDirty = status
this.checkDirty() this.checkDirty()
@ -235,9 +230,9 @@ U.Map = L.Map.extend({
}, },
render: function (fields) { render: function (fields) {
let impacts = U.Utils.getImpactsFromSchema(fields) const impacts = U.Utils.getImpactsFromSchema(fields)
for (let impact of impacts) { for (const impact of impacts) {
switch (impact) { switch (impact) {
case 'ui': case 'ui':
this.initCaptionBar() this.initCaptionBar()
@ -274,7 +269,7 @@ U.Map = L.Map.extend({
}) })
}, },
setOptionsFromQueryString: function (options) { setOptionsFromQueryString: (options) => {
// This is not an editable option // This is not an editable option
L.Util.setFromQueryString(options, 'editMode') L.Util.setFromQueryString(options, 'editMode')
// FIXME retrocompat // FIXME retrocompat
@ -341,7 +336,7 @@ U.Map = L.Map.extend({
// Merge the given schema with the default one // Merge the given schema with the default one
// Missing keys inside the schema are merged with the default ones. // Missing keys inside the schema are merged with the default ones.
overrideSchema: function (schema) { overrideSchema: (schema) => {
for (const [key, extra] of Object.entries(schema)) { for (const [key, extra] of Object.entries(schema)) {
U.SCHEMA[key] = L.extend({}, U.SCHEMA[key], extra) U.SCHEMA[key] = L.extend({}, U.SCHEMA[key], extra)
} }
@ -624,7 +619,7 @@ U.Map = L.Map.extend({
initTileLayers: function () { initTileLayers: function () {
this.tilelayers = [] this.tilelayers = []
for (const props of this.options.tilelayers) { for (const props of this.options.tilelayers) {
let layer = this.createTileLayer(props) const layer = this.createTileLayer(props)
this.tilelayers.push(layer) this.tilelayers.push(layer)
if ( if (
this.options.tilelayer && this.options.tilelayer &&
@ -647,9 +642,7 @@ U.Map = L.Map.extend({
if (this._controls) this._controls.tilelayers.setLayers() if (this._controls) this._controls.tilelayers.setLayers()
}, },
createTileLayer: function (tilelayer) { createTileLayer: (tilelayer) => new L.TileLayer(tilelayer.url_template, tilelayer),
return new L.TileLayer(tilelayer.url_template, tilelayer)
},
selectTileLayer: function (tilelayer) { selectTileLayer: function (tilelayer) {
if (tilelayer === this.selected_tilelayer) { if (tilelayer === this.selected_tilelayer) {
@ -756,7 +749,7 @@ U.Map = L.Map.extend({
} }
}, },
latLng: function (a, b, c) { latLng: (a, b, c) => {
// manage geojson case and call original method // manage geojson case and call original method
if (!(a instanceof L.LatLng) && a.coordinates) { if (!(a instanceof L.LatLng) && a.coordinates) {
// Guess it's a geojson // Guess it's a geojson
@ -766,10 +759,10 @@ U.Map = L.Map.extend({
}, },
handleLimitBounds: function () { handleLimitBounds: function () {
const south = parseFloat(this.options.limitBounds.south), const south = Number.parseFloat(this.options.limitBounds.south),
west = parseFloat(this.options.limitBounds.west), west = Number.parseFloat(this.options.limitBounds.west),
north = parseFloat(this.options.limitBounds.north), north = Number.parseFloat(this.options.limitBounds.north),
east = parseFloat(this.options.limitBounds.east) east = Number.parseFloat(this.options.limitBounds.east)
if (!isNaN(south) && !isNaN(west) && !isNaN(north) && !isNaN(east)) { if (!isNaN(south) && !isNaN(west) && !isNaN(north) && !isNaN(east)) {
const bounds = L.latLngBounds([ const bounds = L.latLngBounds([
[south, west], [south, west],
@ -815,9 +808,7 @@ U.Map = L.Map.extend({
datalayer.edit() datalayer.edit()
}, },
getDefaultOption: function (option) { getDefaultOption: (option) => U.SCHEMA[option] && U.SCHEMA[option].default,
return U.SCHEMA[option] && U.SCHEMA[option].default
},
getOption: function (option, feature) { getOption: function (option, feature) {
if (feature) { if (feature) {
@ -841,11 +832,10 @@ U.Map = L.Map.extend({
}, },
updateTileLayers: function () { updateTileLayers: function () {
const self = this, const callback = (tilelayer) => {
callback = (tilelayer) => { this.options.tilelayer = tilelayer.toJSON()
self.options.tilelayer = tilelayer.toJSON() this.isDirty = true
self.isDirty = true }
}
if (this._controls.tilelayersChooser) if (this._controls.tilelayersChooser)
this._controls.tilelayersChooser.openSwitcher({ this._controls.tilelayersChooser.openSwitcher({
callback: callback, callback: callback,
@ -911,14 +901,13 @@ U.Map = L.Map.extend({
} }
if (importedData.geometry) this.options.center = this.latLng(importedData.geometry) if (importedData.geometry) this.options.center = this.latLng(importedData.geometry)
const self = this
importedData.layers.forEach((geojson) => { importedData.layers.forEach((geojson) => {
if (!geojson._umap_options && geojson._storage) { if (!geojson._umap_options && geojson._storage) {
geojson._umap_options = geojson._storage geojson._umap_options = geojson._storage
delete geojson._storage delete geojson._storage
} }
delete geojson._umap_options?.id // Never trust an id at this stage delete geojson._umap_options?.id // Never trust an id at this stage
const dataLayer = self.createDataLayer(geojson._umap_options) const dataLayer = this.createDataLayer(geojson._umap_options)
dataLayer.fromUmapGeoJSON(geojson) dataLayer.fromUmapGeoJSON(geojson)
}) })
@ -936,11 +925,10 @@ U.Map = L.Map.extend({
importFromFile: function (file) { importFromFile: function (file) {
const reader = new FileReader() const reader = new FileReader()
reader.readAsText(file) reader.readAsText(file)
const self = this
reader.onload = (e) => { reader.onload = (e) => {
const rawData = e.target.result const rawData = e.target.result
try { try {
self.importRaw(rawData) this.importRaw(rawData)
} catch (e) { } catch (e) {
console.error('Error importing data', e) console.error('Error importing data', e)
U.Alert.error(L._('Invalid umap data in {filename}', { filename: file.name })) U.Alert.error(L._('Invalid umap data in {filename}', { filename: file.name }))

View file

@ -15,11 +15,9 @@ U.Layer = {
return this._layers return this._layers
}, },
getEditableOptions: function () { getEditableOptions: () => [],
return []
},
onEdit: function () {}, onEdit: () => {},
hasDataVisible: function () { hasDataVisible: function () {
return !!Object.keys(this._layers).length return !!Object.keys(this._layers).length
@ -67,9 +65,7 @@ U.Layer.Cluster = L.MarkerClusterGroup.extend({
polygonOptions: { polygonOptions: {
color: this.datalayer.getColor(), color: this.datalayer.getColor(),
}, },
iconCreateFunction: function (cluster) { iconCreateFunction: (cluster) => new U.Icon.Cluster(datalayer, cluster),
return new U.Icon.Cluster(datalayer, cluster)
},
} }
if (this.datalayer.options.cluster && this.datalayer.options.cluster.radius) { if (this.datalayer.options.cluster && this.datalayer.options.cluster.radius) {
options.maxClusterRadius = this.datalayer.options.cluster.radius options.maxClusterRadius = this.datalayer.options.cluster.radius
@ -99,26 +95,24 @@ U.Layer.Cluster = L.MarkerClusterGroup.extend({
return L.MarkerClusterGroup.prototype.removeLayer.call(this, layer) return L.MarkerClusterGroup.prototype.removeLayer.call(this, layer)
}, },
getEditableOptions: function () { getEditableOptions: () => [
return [ [
[ 'options.cluster.radius',
'options.cluster.radius', {
{ handler: 'BlurIntInput',
handler: 'BlurIntInput', placeholder: L._('Clustering radius'),
placeholder: L._('Clustering radius'), helpText: L._('Override clustering radius (default 80)'),
helpText: L._('Override clustering radius (default 80)'), },
}, ],
], [
[ 'options.cluster.textColor',
'options.cluster.textColor', {
{ handler: 'TextColorPicker',
handler: 'TextColorPicker', placeholder: L._('Auto'),
placeholder: L._('Auto'), helpText: L._('Text color for the cluster label'),
helpText: L._('Text color for the cluster label'), },
}, ],
], ],
]
},
onEdit: function (field, builder) { onEdit: function (field, builder) {
if (field === 'options.cluster.radius') { if (field === 'options.cluster.radius') {
@ -182,7 +176,7 @@ U.Layer.Choropleth = L.FeatureGroup.extend({
getValues: function () { getValues: function () {
const values = [] const values = []
this.datalayer.eachLayer((layer) => { this.datalayer.eachLayer((layer) => {
let value = this._getValue(layer) const value = this._getValue(layer)
if (!isNaN(value)) values.push(value) if (!isNaN(value)) values.push(value)
}) })
return values return values
@ -370,7 +364,7 @@ U.Layer.Heat = L.HeatLayer.extend({
this.datalayer.options.heat && this.datalayer.options.heat &&
this.datalayer.options.heat.intensityProperty this.datalayer.options.heat.intensityProperty
) { ) {
alt = parseFloat( alt = Number.parseFloat(
layer.properties[this.datalayer.options.heat.intensityProperty || 0] layer.properties[this.datalayer.options.heat.intensityProperty || 0]
) )
latlng = new L.LatLng(latlng.lat, latlng.lng, alt) latlng = new L.LatLng(latlng.lat, latlng.lng, alt)
@ -383,37 +377,33 @@ U.Layer.Heat = L.HeatLayer.extend({
this.setLatLngs([]) this.setLatLngs([])
}, },
getFeatures: function () { getFeatures: () => ({}),
return {}
},
getBounds: function () { getBounds: function () {
return L.latLngBounds(this._latlngs) return L.latLngBounds(this._latlngs)
}, },
getEditableOptions: function () { getEditableOptions: () => [
return [ [
[ 'options.heat.radius',
'options.heat.radius', {
{ handler: 'Range',
handler: 'Range', min: 10,
min: 10, max: 100,
max: 100, step: 5,
step: 5, label: L._('Heatmap radius'),
label: L._('Heatmap radius'), helpText: L._('Override heatmap radius (default 25)'),
helpText: L._('Override heatmap radius (default 25)'), },
}, ],
], [
[ 'options.heat.intensityProperty',
'options.heat.intensityProperty', {
{ handler: 'BlurInput',
handler: 'BlurInput', placeholder: L._('Heatmap intensity property'),
placeholder: L._('Heatmap intensity property'), helpText: L._('Optional intensity property for heatmap'),
helpText: L._('Optional intensity property for heatmap'), },
}, ],
], ],
]
},
onEdit: function (field, builder) { onEdit: function (field, builder) {
if (field === 'options.heat.intensityProperty') { if (field === 'options.heat.intensityProperty') {
@ -538,23 +528,20 @@ U.DataLayer = L.Evented.extend({
let isDirty = false let isDirty = false
let isDeleted = false let isDeleted = false
const self = this
try { try {
Object.defineProperty(this, 'isDirty', { Object.defineProperty(this, 'isDirty', {
get: function () { get: () => isDirty,
return isDirty set: (status) => {
}, if (!isDirty && status) this.fire('dirty')
set: function (status) {
if (!isDirty && status) self.fire('dirty')
isDirty = status isDirty = status
if (status) { if (status) {
self.map.addDirtyDatalayer(self) this.map.addDirtyDatalayer(this)
// A layer can be made dirty by indirect action (like dragging layers) // A layer can be made dirty by indirect action (like dragging layers)
// we need to have it loaded before saving it. // we need to have it loaded before saving it.
if (!self.isLoaded()) self.fetchData() if (!this.isLoaded()) this.fetchData()
} else { } else {
self.map.removeDirtyDatalayer(self) this.map.removeDirtyDatalayer(this)
self.isDeleted = false this.isDeleted = false
} }
}, },
}) })
@ -563,13 +550,11 @@ U.DataLayer = L.Evented.extend({
} }
try { try {
Object.defineProperty(this, 'isDeleted', { Object.defineProperty(this, 'isDeleted', {
get: function () { get: () => isDeleted,
return isDeleted set: (status) => {
}, if (!isDeleted && status) this.fire('deleted')
set: function (status) {
if (!isDeleted && status) self.fire('deleted')
isDeleted = status isDeleted = status
if (status) self.isDirty = status if (status) this.isDirty = status
}, },
}) })
} catch (e) { } catch (e) {
@ -618,9 +603,9 @@ U.DataLayer = L.Evented.extend({
}, },
render: function (fields, builder) { render: function (fields, builder) {
let impacts = U.Utils.getImpactsFromSchema(fields) const impacts = U.Utils.getImpactsFromSchema(fields)
for (let impact of impacts) { for (const impact of impacts) {
switch (impact) { switch (impact) {
case 'ui': case 'ui':
this.map.onDataLayersChanged() this.map.onDataLayersChanged()
@ -787,8 +772,8 @@ U.DataLayer = L.Evented.extend({
}, },
showAtZoom: function () { showAtZoom: function () {
const from = parseInt(this.options.fromZoom, 10), const from = Number.parseInt(this.options.fromZoom, 10),
to = parseInt(this.options.toZoom, 10), to = Number.parseInt(this.options.toZoom, 10),
zoom = this.map.getZoom() zoom = this.map.getZoom()
return !((!isNaN(from) && zoom < from) || (!isNaN(to) && zoom > to)) return !((!isNaN(from) && zoom < from) || (!isNaN(to) && zoom > to))
}, },
@ -953,7 +938,7 @@ U.DataLayer = L.Evented.extend({
this.rawToGeoJSON(c, type, (geojson) => this.addData(geojson)) this.rawToGeoJSON(c, type, (geojson) => this.addData(geojson))
}, },
rawToGeoJSON: function (c, type, callback) { rawToGeoJSON: (c, type, callback) => {
const toDom = (x) => { const toDom = (x) => {
const doc = new DOMParser().parseFromString(x, 'text/xml') const doc = new DOMParser().parseFromString(x, 'text/xml')
const errorNode = doc.querySelector('parsererror') const errorNode = doc.querySelector('parsererror')
@ -1045,7 +1030,7 @@ U.DataLayer = L.Evented.extend({
const geometry = geojson.type === 'Feature' ? geojson.geometry : geojson const geometry = geojson.type === 'Feature' ? geojson.geometry : geojson
let feature = this.geoJSONToLeaflet({ geometry, geojson }) const feature = this.geoJSONToLeaflet({ geometry, geojson })
if (feature) { if (feature) {
this.addLayer(feature) this.addLayer(feature)
feature.onCommit() feature.onCommit()
@ -1318,7 +1303,7 @@ U.DataLayer = L.Evented.extend({
layerProperties.appendChild(builder.build()) layerProperties.appendChild(builder.build())
} }
let shapeOptions = [ const shapeOptions = [
'options.color', 'options.color',
'options.iconClass', 'options.iconClass',
'options.iconUrl', 'options.iconUrl',
@ -1337,7 +1322,7 @@ U.DataLayer = L.Evented.extend({
const shapeProperties = L.DomUtil.createFieldset(container, L._('Shape properties')) const shapeProperties = L.DomUtil.createFieldset(container, L._('Shape properties'))
shapeProperties.appendChild(builder.build()) shapeProperties.appendChild(builder.build())
let optionsFields = [ const optionsFields = [
'options.smoothFactor', 'options.smoothFactor',
'options.dashArray', 'options.dashArray',
'options.zoomTo', 'options.zoomTo',
@ -1499,8 +1484,8 @@ U.DataLayer = L.Evented.extend({
buildVersionsFieldset: async function (container) { buildVersionsFieldset: async function (container) {
const appendVersion = (data) => { const appendVersion = (data) => {
const date = new Date(parseInt(data.at, 10)) const date = new Date(Number.parseInt(data.at, 10))
const content = `${date.toLocaleString(L.lang)} (${parseInt(data.size) / 1000}Kb)` const content = `${date.toLocaleString(L.lang)} (${Number.parseInt(data.size) / 1000}Kb)`
const el = L.DomUtil.create('div', 'umap-datalayer-version', versionsContainer) const el = L.DomUtil.create('div', 'umap-datalayer-version', versionsContainer)
const button = L.DomUtil.createButton( const button = L.DomUtil.createButton(
'', '',

View file

@ -12,16 +12,13 @@ U.MapPermissions = L.Class.extend({
this.setOptions(map.options.permissions) this.setOptions(map.options.permissions)
this.map = map this.map = map
let isDirty = false let isDirty = false
const self = this
try { try {
Object.defineProperty(this, 'isDirty', { Object.defineProperty(this, 'isDirty', {
get: function () { get: () => isDirty,
return isDirty set: (status) => {
},
set: function (status) {
isDirty = status isDirty = status
if (status) { if (status) {
self.map.isDirty = status this.map.isDirty = status
} }
}, },
}) })

View file

@ -84,11 +84,11 @@ U.Popup.Panel = U.Popup.extend({
} }
}, },
update: function () {}, update: () => {},
_updateLayout: function () {}, _updateLayout: () => {},
_updatePosition: function () {}, _updatePosition: () => {},
_adjustPan: function () {}, _adjustPan: () => {},
_animateZoom: function () {}, _animateZoom: () => {},
}) })
U.Popup.SimplePanel = U.Popup.Panel // Retrocompat. U.Popup.SimplePanel = U.Popup.Panel // Retrocompat.
@ -102,7 +102,7 @@ U.PopupTemplate.Default = L.Class.extend({
this.container = container this.container = container
}, },
renderTitle: function () {}, renderTitle: () => {},
renderBody: function () { renderBody: function () {
const template = this.feature.getOption('popupContentTemplate') const template = this.feature.getOption('popupContentTemplate')
@ -181,7 +181,7 @@ U.PopupTemplate.BaseWithTitle = U.PopupTemplate.Default.extend({
}) })
U.PopupTemplate.Table = U.PopupTemplate.BaseWithTitle.extend({ U.PopupTemplate.Table = U.PopupTemplate.BaseWithTitle.extend({
formatRow: function (key, value) { formatRow: (key, value) => {
if (value.indexOf('http') === 0) { if (value.indexOf('http') === 0) {
value = `<a href="${value}" target="_blank">${value}</a>` value = `<a href="${value}" target="_blank">${value}</a>`
} }
@ -268,7 +268,7 @@ U.PopupTemplate.OSM = U.PopupTemplate.Default.extend({
const color = this.feature.getDynamicOption('color') const color = this.feature.getDynamicOption('color')
title.style.backgroundColor = color title.style.backgroundColor = color
const iconUrl = this.feature.getDynamicOption('iconUrl') const iconUrl = this.feature.getDynamicOption('iconUrl')
let icon = U.Icon.makeIconElement(iconUrl, title) const icon = U.Icon.makeIconElement(iconUrl, title)
L.DomUtil.addClass(icon, 'icon') L.DomUtil.addClass(icon, 'icon')
U.Icon.setIconContrast(icon, title, iconUrl, color) U.Icon.setIconContrast(icon, title, iconUrl, color)
if (L.DomUtil.contrastedColor(title, color)) title.style.color = 'white' if (L.DomUtil.contrastedColor(title, color)) title.style.color = 'white'

View file

@ -1,28 +1,22 @@
U.Share = L.Class.extend({ U.Share = L.Class.extend({
EXPORT_TYPES: { EXPORT_TYPES: {
geojson: { geojson: {
formatter: function (map) { formatter: (map) => JSON.stringify(map.toGeoJSON(), null, 2),
return JSON.stringify(map.toGeoJSON(), null, 2)
},
ext: '.geojson', ext: '.geojson',
filetype: 'application/json', filetype: 'application/json',
}, },
gpx: { gpx: {
formatter: function (map) { formatter: (map) => togpx(map.toGeoJSON()),
return togpx(map.toGeoJSON())
},
ext: '.gpx', ext: '.gpx',
filetype: 'application/gpx+xml', filetype: 'application/gpx+xml',
}, },
kml: { kml: {
formatter: function (map) { formatter: (map) => tokml(map.toGeoJSON()),
return tokml(map.toGeoJSON())
},
ext: '.kml', ext: '.kml',
filetype: 'application/vnd.google-earth.kml+xml', filetype: 'application/vnd.google-earth.kml+xml',
}, },
csv: { csv: {
formatter: function (map) { formatter: (map) => {
const table = [] const table = []
map.eachFeature((feature) => { map.eachFeature((feature) => {
const row = feature.toGeoJSON()['properties'], const row = feature.toGeoJSON()['properties'],

View file

@ -15,8 +15,6 @@ U.Slideshow = L.Class.extend({
// current feature // current feature
let current = null let current = null
const self = this
try { try {
Object.defineProperty(this, 'current', { Object.defineProperty(this, 'current', {
get: function () { get: function () {
@ -26,7 +24,7 @@ U.Slideshow = L.Class.extend({
} }
return current return current
}, },
set: function (feature) { set: (feature) => {
current = feature current = feature
}, },
}) })
@ -35,9 +33,9 @@ U.Slideshow = L.Class.extend({
} }
try { try {
Object.defineProperty(this, 'next', { Object.defineProperty(this, 'next', {
get: function () { get: () => {
if (!current) { if (!current) {
return self.current return this.current
} }
return current.getNext() return current.getNext()
}, },
@ -69,7 +67,7 @@ U.Slideshow = L.Class.extend({
}, },
timeSpinner: function () { timeSpinner: function () {
const time = parseInt(this.options.delay, 10) const time = Number.parseInt(this.options.delay, 10)
if (!time) return if (!time) return
const css = `rotation ${time / 1000}s infinite linear`, const css = `rotation ${time / 1000}s infinite linear`,
spinners = document.querySelectorAll('.umap-slideshow-toolbox .play .spinner') spinners = document.querySelectorAll('.umap-slideshow-toolbox .play .spinner')
@ -81,7 +79,7 @@ U.Slideshow = L.Class.extend({
} }
}, },
resetSpinners: function () { resetSpinners: () => {
// Make that animnation is coordinated with user actions // Make that animnation is coordinated with user actions
const spinners = document.querySelectorAll('.umap-slideshow-toolbox .play .spinner') const spinners = document.querySelectorAll('.umap-slideshow-toolbox .play .spinner')

View file

@ -81,7 +81,7 @@ U.TableEditor = L.Class.extend({
this.properties = this.datalayer._propertiesIndex this.properties = this.datalayer._propertiesIndex
}, },
validateName: function (name) { validateName: (name) => {
if (name.indexOf('.') !== -1) { if (name.indexOf('.') !== -1) {
U.Alert.error(L._('Invalide property name: {name}', { name: name })) U.Alert.error(L._('Invalide property name: {name}', { name: name }))
return false return false