Skip to content

Commit

Permalink
chore: move alert to dedicated module
Browse files Browse the repository at this point in the history
  • Loading branch information
yohanboniface committed May 22, 2024
1 parent 03f6080 commit a6975cf
Show file tree
Hide file tree
Showing 12 changed files with 135 additions and 110 deletions.
2 changes: 2 additions & 0 deletions umap/static/umap/js/modules/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Browser from './browser.js'
import Facets from './facets.js'
import Caption from './caption.js'
import { Panel, EditPanel, FullPanel } from './panel.js'
import Alert from './ui/alert.js'
import * as Utils from './utils.js'
import { SCHEMA } from './schema.js'
import { Request, ServerRequest, RequestError, HTTPError, NOKError } from './request.js'
Expand All @@ -21,6 +22,7 @@ window.U = {
Browser,
Facets,
Panel,
Alert,
EditPanel,
FullPanel,
Utils,
Expand Down
20 changes: 12 additions & 8 deletions umap/static/umap/js/modules/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,18 @@ class BaseRequest {
// In case of error, an alert is sent, but non 20X status are not handled
// The consumer must check the response status by hand
export class Request extends BaseRequest {
constructor(ui) {
constructor(alert) {
super()
this.ui = ui
this.alert = alert
}

fire(name, params) {
document.body.dispatchEvent(new CustomEvent(name, params))
}

async _fetch(method, uri, headers, data) {
const id = Math.random()
this.ui.fire('dataloading', { id: id })
this.fire('dataloading', { id: id })
try {
const response = await BaseRequest.prototype._fetch.call(
this,
Expand All @@ -68,7 +72,7 @@ export class Request extends BaseRequest {
if (error instanceof NOKError) return this._onNOK(error)
return this._onError(error)
} finally {
this.ui.fire('dataload', { id: id })
this.fire('dataload', { id: id })
}
}

Expand All @@ -81,7 +85,7 @@ export class Request extends BaseRequest {
}

_onError(error) {
this.ui.alert({ content: L._('Problem in the response'), level: 'error' })
this.alert.open({ content: L._('Problem in the response'), level: 'error' })
}

_onNOK(error) {
Expand Down Expand Up @@ -127,9 +131,9 @@ export class ServerRequest extends Request {
try {
const data = await response.json()
if (data.info) {
this.ui.alert({ content: data.info, level: 'info' })
this.alert.open({ content: data.info, level: 'info' })
} else if (data.error) {
this.ui.alert({ content: data.error, level: 'error' })
this.alert.open({ content: data.error, level: 'error' })
return this._onError(new Error(data.error))
}
return [data, response, null]
Expand All @@ -144,7 +148,7 @@ export class ServerRequest extends Request {

_onNOK(error) {
if (error.status === 403) {
this.ui.alert({
this.alert.open({
content: error.message || L._('Action not allowed :('),
level: 'error',
})
Expand Down
88 changes: 88 additions & 0 deletions umap/static/umap/js/modules/ui/alert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { DomUtil, DomEvent } from '../../../vendors/leaflet/leaflet-src.esm.js'
import { translate } from '../i18n.js'

const ALERTS = []
let ALERT_ID = null

export default class Alert {
constructor(map) {
this.parent = map._controlContainer
this.map = map
this.container = DomUtil.create('div', 'with-transition', this.parent)
this.container.id = 'umap-alert-container'
DomEvent.disableClickPropagation(this.container)
DomEvent.on(this.container, 'contextmenu', DomEvent.stopPropagation) // Do not activate our custom context menu.
DomEvent.on(this.container, 'wheel', DomEvent.stopPropagation)
DomEvent.on(this.container, 'MozMousePixelScroll', DomEvent.stopPropagation)
}

open(params) {
if (DomUtil.hasClass(this.parent, 'umap-alert')) ALERTS.push(params)
else this._open(params)
}

_open(params) {
if (!params) {
if (ALERTS.length) params = ALERTS.pop()
else return
}
let timeoutID
const level_class = params.level && params.level == 'info' ? 'info' : 'error'
this.container.innerHTML = ''
DomUtil.addClass(this.parent, 'umap-alert')
DomUtil.addClass(this.container, level_class)
const close = () => {
if (timeoutID && timeoutID !== ALERT_ID) {
return
} // Another alert has been forced
this.container.innerHTML = ''
DomUtil.removeClass(this.parent, 'umap-alert')
DomUtil.removeClass(this.container, level_class)
if (timeoutID) window.clearTimeout(timeoutID)
this._open()
}
const closeButton = DomUtil.createButton(
'umap-close-link',
this.container,
'',
close,
this
)
DomUtil.create('i', 'umap-close-icon', closeButton)
const label = DomUtil.create('span', '', closeButton)
label.title = label.textContent = translate('Close')
DomUtil.element({
tagName: 'div',
innerHTML: params.content,
parent: this.container,
})
this.addActions(params.actions)
if (params.duration !== Infinity) {
ALERT_ID = timeoutID = window.setTimeout(close, params.duration || 3000)
}
}

addActions(actions) {
actions = actions || []
let action, el, input
const form = DomUtil.create('div', 'umap-alert-actions', this.container)
for (let action of actions) {
if (action.input) {
input = DomUtil.element({
tagName: 'input',
parent: form,
className: 'umap-alert-input',
placeholder: action.input,
})
}
el = DomUtil.createButton(
'umap-action',
form,
action.label,
action.callback,
action.callbackContext || this.map
)
DomEvent.on(el, 'click', close, this)
}
}
}
3 changes: 1 addition & 2 deletions umap/static/umap/js/umap.controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -1048,7 +1048,6 @@ U.Locate = L.Control.Locate.extend({
if (!this._container || !this._container.parentNode) return
return L.Control.Locate.prototype.remove.call(this)
},

})

U.Search = L.PhotonSearch.extend({
Expand Down Expand Up @@ -1087,7 +1086,7 @@ U.Search = L.PhotonSearch.extend({
if (latlng.isValid()) {
this.reverse.doReverse(latlng)
} else {
this.map.ui.alert({ content: 'Invalid latitude or longitude', mode: 'error' })
this.map.alert.open({ content: 'Invalid latitude or longitude', mode: 'error' })
}
return
}
Expand Down
4 changes: 2 additions & 2 deletions umap/static/umap/js/umap.features.js
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@ U.Marker = L.Marker.extend({
const builder = new U.FormBuilder(this, coordinatesOptions, {
callback: function () {
if (!this._latlng.isValid()) {
this.map.ui.alert({
this.map.alert.open({
content: L._('Invalid latitude or longitude'),
level: 'error',
})
Expand Down Expand Up @@ -928,7 +928,7 @@ U.PathMixin = {
items.push({
text: L._('Display measure'),
callback: function () {
this.map.ui.alert({ content: this.getMeasure(), level: 'info' })
this.map.alert.open({ content: this.getMeasure(), level: 'info' })
},
context: this,
})
Expand Down
4 changes: 2 additions & 2 deletions umap/static/umap/js/umap.importer.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,15 @@ U.Importer = L.Class.extend({
}
} else {
if (!type)
return this.map.ui.alert({
return this.map.alert.open({
content: L._('Please choose a format'),
level: 'error',
})
if (this.rawInput.value && type === 'umap') {
try {
this.map.importRaw(this.rawInput.value, type)
} catch (e) {
this.ui.alert({ content: L._('Invalid umap data'), level: 'error' })
this.alert.open({ content: L._('Invalid umap data'), level: 'error' })
console.error(e)
}
} else {
Expand Down
33 changes: 18 additions & 15 deletions umap/static/umap/js/umap.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,16 @@ U.Map = L.Map.extend({
this.urls = new U.URLs(this.options.urls)

this.panel = new U.Panel(this)
this.alert = new U.Alert(this)
if (this.hasEditMode()) {
this.editPanel = new U.EditPanel(this)
this.fullPanel = new U.FullPanel(this)
}
this.ui = new U.UI(this._container)
this.ui.on('dataloading', (e) => this.fire('dataloading', e))
this.ui.on('dataload', (e) => this.fire('dataload', e))
this.server = new U.ServerRequest(this.ui)
this.request = new U.Request(this.ui)
L.DomEvent.on(document.body, 'dataloading', (e) => this.fire('dataloading', e))
L.DomEvent.on(document.body, 'dataload', (e) => this.fire('dataload', e))
this.server = new U.ServerRequest(this.alert)
this.request = new U.Request(this.alert)

this.initLoader()
this.name = this.options.name
Expand Down Expand Up @@ -359,7 +360,7 @@ U.Map = L.Map.extend({
icon: 'umap-fake-class',
iconLoading: 'umap-fake-class',
flyTo: this.options.easing,
onLocationError: (err) => this.ui.alert({ content: err.message }),
onLocationError: (err) => this.alert.open({ content: err.message }),
})
this._controls.fullscreen = new L.Control.Fullscreen({
title: { false: L._('View Fullscreen'), true: L._('Exit Fullscreen') },
Expand Down Expand Up @@ -392,7 +393,9 @@ U.Map = L.Map.extend({
},

renderControls: function () {
const hasSlideshow = Boolean(this.options.slideshow && this.options.slideshow.active)
const hasSlideshow = Boolean(
this.options.slideshow && this.options.slideshow.active
)
const barEnabled = this.options.captionBar || hasSlideshow
document.body.classList.toggle('umap-caption-bar-enabled', barEnabled)
document.body.classList.toggle('umap-slideshow-enabled', hasSlideshow)
Expand Down Expand Up @@ -641,7 +644,7 @@ U.Map = L.Map.extend({
} catch (e) {
console.error(e)
this.removeLayer(tilelayer)
this.ui.alert({
this.alert.open({
content: `${L._('Error in the tilelayer URL')}: ${tilelayer._url}`,
level: 'error',
})
Expand Down Expand Up @@ -676,7 +679,7 @@ U.Map = L.Map.extend({
} catch (e) {
this.removeLayer(overlay)
console.error(e)
this.ui.alert({
this.alert.open({
content: `${L._('Error in the overlay URL')}: ${overlay._url}`,
level: 'error',
})
Expand Down Expand Up @@ -799,7 +802,7 @@ U.Map = L.Map.extend({
if (this.options.umap_id) {
// We do not want an extra message during the map creation
// to avoid the double notification/alert.
this.ui.alert({
this.alert.open({
content: L._('The zoom and center have been modified.'),
level: 'info',
})
Expand Down Expand Up @@ -842,7 +845,7 @@ U.Map = L.Map.extend({
processFileToImport: function (file, layer, type) {
type = type || U.Utils.detectFileType(file)
if (!type) {
this.ui.alert({
this.alert.open({
content: L._('Unable to detect format of file {filename}', {
filename: file.name,
}),
Expand Down Expand Up @@ -899,7 +902,7 @@ U.Map = L.Map.extend({
self.importRaw(rawData)
} catch (e) {
console.error('Error importing data', e)
self.ui.alert({
self.alert.open({
content: L._('Invalid umap data in {filename}', { filename: file.name }),
level: 'error',
})
Expand Down Expand Up @@ -1030,7 +1033,7 @@ U.Map = L.Map.extend({
label: L._('Copy link'),
callback: () => {
L.Util.copyToClipboard(data.permissions.anonymous_edit_url)
this.ui.alert({
this.alert.open({
content: L._('Secret edit link copied to clipboard!'),
level: 'info',
})
Expand Down Expand Up @@ -1058,7 +1061,7 @@ U.Map = L.Map.extend({
history.pushState({}, this.options.name, data.url)
else window.location = data.url
alert.content = data.info || alert.content
this.once('saved', () => this.ui.alert(alert))
this.once('saved', () => this.alert.open(alert))
this.permissions.save()
}
},
Expand Down Expand Up @@ -1091,7 +1094,7 @@ U.Map = L.Map.extend({

star: async function () {
if (!this.options.umap_id)
return this.ui.alert({
return this.alert.open({
content: L._('Please save the map first'),
level: 'error',
})
Expand All @@ -1102,7 +1105,7 @@ U.Map = L.Map.extend({
let msg = data.starred
? L._('Map has been starred')
: L._('Map has been unstarred')
this.ui.alert({ content: msg, level: 'info' })
this.alert.open({ content: msg, level: 'info' })
this.renderControls()
}
},
Expand Down
12 changes: 6 additions & 6 deletions umap/static/umap/js/umap.layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -865,8 +865,8 @@ U.DataLayer = L.Evented.extend({
isRemoteLayer: function () {
return Boolean(
this.options.remoteData &&
this.options.remoteData.url &&
this.options.remoteData.format
this.options.remoteData.url &&
this.options.remoteData.format
)
},

Expand Down Expand Up @@ -965,7 +965,7 @@ U.DataLayer = L.Evented.extend({
message: err[0].message,
})
}
this.map.ui.alert({ content: message, level: 'error', duration: 10000 })
this.map.alert.open({ content: message, level: 'error', duration: 10000 })
console.error(err)
}
if (result && result.features.length) {
Expand All @@ -992,7 +992,7 @@ U.DataLayer = L.Evented.extend({
const gj = JSON.parse(c)
callback(gj)
} catch (err) {
this.map.ui.alert({ content: `Invalid JSON file: ${err}` })
this.map.alert.open({ content: `Invalid JSON file: ${err}` })
return
}
}
Expand Down Expand Up @@ -1050,7 +1050,7 @@ U.DataLayer = L.Evented.extend({
return this.geojsonToFeatures(geometry.geometries)

default:
this.map.ui.alert({
this.map.alert.open({
content: L._('Skipping unknown geometry.type: {type}', {
type: geometry.type || 'undefined',
}),
Expand Down Expand Up @@ -1641,7 +1641,7 @@ U.DataLayer = L.Evented.extend({
label: L._('Cancel'),
},
]
this.map.ui.alert({
this.map.alert.open({
content: msg,
level: 'error',
duration: 100000,
Expand Down
Loading

0 comments on commit a6975cf

Please sign in to comment.