You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

586 lines
17 KiB

6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
3 years ago
3 years ago
3 years ago
3 years ago
6 years ago
  1. /* global openstreetbrowserPrefix */
  2. /* eslint camelcase: 0 */
  3. var OpenStreetBrowserLoader = require('./OpenStreetBrowserLoader')
  4. var OverpassLayer = require('overpass-layer')
  5. var OverpassLayerList = require('overpass-layer').List
  6. var queryString = require('query-string')
  7. var CategoryBase = require('./CategoryBase')
  8. var state = require('./state')
  9. var tabs = require('modulekit-tabs')
  10. var markers = require('./markers')
  11. var maki = require('./maki')
  12. var qs = require('sheet-router/qs')
  13. const ObjectDisplay = require('./ObjectDisplay')
  14. const showMore = require('./showMore')
  15. const listTemplate = '<a href="{{ object.appUrl|default("#") }}">' +
  16. '<div class="marker">' +
  17. '{% if object.templateMarkerSymbol|default(object.markerSymbol)|trim == "line" %}' +
  18. '<div class="symbol">{{ markerLine(object) }}</div>' +
  19. '{% elseif object.templateMarkerSymbol|default(object.markerSymbol)|trim == "polygon" %}' +
  20. '<div class="symbol">{{ markerPolygon(object) }}</div>' +
  21. '{% elseif object.templateMarkerSymbol or object.markerSymbol %}' +
  22. '<div class="symbol">{{ object.templateMarkerSymbol|default(object.markerSymbol) }}</div>' +
  23. '{% elseif object.marker and object.marker.iconUrl %}' +
  24. '<img class="symbol" src="{{ object.marker.iconUrl|e }}">' +
  25. '{% endif %}' +
  26. '{% if object.templateMarkerSign or object.markerSign %}' +
  27. '<div class="sign">{{ object.templateMarkerSign|default(object.markerSign) }}</div>' +
  28. '{% endif %}' +
  29. '</div>' +
  30. '<div class="content">' +
  31. '{% if object.templateDetails or object.details %}<div class="details">{{ object.templateDetails|default(object.details) }}</div>{% endif %}' +
  32. '{% if object.templateDescription or object.description %}<div class="description">{{ object.templateDescription|default(object.description) }}</div>{% endif %}' +
  33. '{% if object.templateTitle or object.title %}<div class="title">{{ object.templateTitle|default(object.title) }}</div>{% endif %}' +
  34. '</div>' +
  35. '</a>'
  36. var defaultValues = {
  37. feature: {
  38. title: "{{ localizedTag(tags, 'name') |default(localizedTag(tags, 'operator')) | default(localizedTag(tags, 'ref')) }}",
  39. markerSign: '',
  40. 'style:selected': {
  41. color: '#3f3f3f',
  42. width: 3,
  43. opacity: 1,
  44. radius: 12,
  45. pane: 'selected'
  46. },
  47. markerSymbol: '{{ markerPointer({})|raw }}',
  48. listMarkerSymbol: '{{ markerCircle({})|raw }}',
  49. preferredZoom: 16
  50. },
  51. layouts: {
  52. list: listTemplate.replace(/template/g, 'list'),
  53. popup:
  54. '<h1>{{ object.popupTitle|default(object.title) }}</h1>' +
  55. '{% if object.popupDescription or object.description %}<div class="description">{{ object.popupDescription|default(object.description) }}</div>{% endif %}' +
  56. '{% if object.popupBody or object.body %}<div class="body">{{ object.popupBody|default(object.body) }}</div>{% endif %}'
  57. },
  58. queryOptions: {
  59. }
  60. }
  61. CategoryOverpass.prototype = Object.create(CategoryBase.prototype)
  62. CategoryOverpass.prototype.constructor = CategoryOverpass
  63. function CategoryOverpass (options, data, repository) {
  64. var p
  65. CategoryBase.call(this, options, data, repository)
  66. data.id = this.id
  67. // set undefined data properties from defaultValues
  68. for (var k1 in defaultValues) {
  69. if (!(k1 in data)) {
  70. data[k1] = JSON.parse(JSON.stringify(defaultValues[k1]))
  71. } else if (typeof defaultValues[k1] === 'object') {
  72. for (var k2 in defaultValues[k1]) {
  73. if (!(k2 in data[k1])) {
  74. data[k1][k2] = JSON.parse(JSON.stringify(defaultValues[k1][k2]))
  75. } else if (typeof defaultValues[k1][k2] === 'object') {
  76. for (var k3 in defaultValues[k1][k2]) {
  77. if (!(k3 in data[k1][k2])) {
  78. data[k1][k2][k3] = JSON.parse(JSON.stringify(defaultValues[k1][k2][k3]))
  79. }
  80. }
  81. }
  82. }
  83. }
  84. }
  85. // get minZoom
  86. if ('minZoom' in data) {
  87. // has minZoom
  88. } else if (typeof data.query === 'object') {
  89. data.minZoom = Object.keys(data.query)[0]
  90. } else {
  91. data.minZoom = 14
  92. }
  93. data.feature.appUrl = '#' + this.id + '/{{ id }}'
  94. data.styleNoBindPopup = [ 'selected' ]
  95. data.stylesNoAutoShow = [ 'selected' ]
  96. data.updateAssets = this.updateAssets.bind(this)
  97. data.layouts.popup = () => null
  98. this.layer = new OverpassLayer(data)
  99. this.layer.onLoadStart = function (ev) {
  100. this.dom.classList.add('loading')
  101. if (this.parentCategory) {
  102. this.parentCategory.notifyChildLoadStart(this)
  103. }
  104. }.bind(this)
  105. this.layer.onLoadEnd = function (ev) {
  106. this.dom.classList.remove('loading')
  107. if (this.parentCategory) {
  108. this.parentCategory.notifyChildLoadEnd(this)
  109. }
  110. if (ev.error) {
  111. alert('Error loading data from Overpass API: ' + ev.error)
  112. }
  113. }.bind(this)
  114. this.layer.on('update', function (object, ob) {
  115. if (!ob.popup || !ob.popup._contentNode || map._popup !== ob.popup) {
  116. return
  117. }
  118. this.emit('update', object, ob)
  119. }.bind(this))
  120. this.layer.on('add', (ob, data) => this.emit('add', ob, data))
  121. this.layer.on('remove', (ob, data) => this.emit('remove', ob, data))
  122. this.layer.on('zoomChange', (ob, data) => this.emit('remove', ob, data))
  123. this.layer.on('twigData',
  124. (ob, data, result) => {
  125. result.user = global.options
  126. global.currentCategory = this
  127. }
  128. )
  129. call_hooks('category-overpass-init', this)
  130. var p = document.createElement('div')
  131. p.className = 'loadingIndicator'
  132. p.innerHTML = '<i class="fa fa-spinner fa-pulse fa-fw"></i><span class="sr-only">' + lang('loading') + '</span>'
  133. this.dom.appendChild(p)
  134. this.domStatus = document.createElement('div')
  135. this.domStatus.className = 'status'
  136. if (this.data.lists) {
  137. this.dom.insertBefore(this.domStatus, this.domHeader.nextSibling)
  138. } else {
  139. p = document.createElement('div')
  140. p.className = 'loadingIndicator2'
  141. p.innerHTML = '<div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div>'
  142. this.dom.appendChild(p)
  143. this.dom.appendChild(this.domStatus)
  144. }
  145. register_hook('state-get', function (state) {
  146. if (this.isOpen) {
  147. if (state.categories) {
  148. state.categories += ','
  149. } else {
  150. state.categories = ''
  151. }
  152. let id = this.id
  153. let param = {}
  154. this.emit('stateGet', param)
  155. for (var k in param) {
  156. if (!param[k]) {
  157. delete param[k]
  158. }
  159. }
  160. if (param && Object.keys(param).length) {
  161. id += '[' + queryString.stringify(param) + ']'
  162. }
  163. state.categories += id
  164. }
  165. }.bind(this))
  166. register_hook('state-apply', function (state) {
  167. if (!('categories' in state)) {
  168. return
  169. }
  170. let list = state.categories.split(',')
  171. let found = list.filter(id => {
  172. let m = id.match(/^([0-9A-Z_-]+)(\[(.*)\])/i)
  173. if (m) {
  174. id = m[1]
  175. }
  176. return id === this.id
  177. }).length
  178. if (!found) {
  179. this.close()
  180. }
  181. // opening categories is handled by src/categories.js
  182. }.bind(this))
  183. }
  184. CategoryOverpass.prototype.setParam = function (param) {
  185. this.emit('setParam', param)
  186. this._applyParam(param)
  187. }
  188. CategoryOverpass.prototype._applyParam = function (param) {
  189. this.emit('applyParam', param)
  190. }
  191. CategoryOverpass.prototype.updateAssets = function (div) {
  192. var imgs = div.getElementsByTagName('img')
  193. for (var i = 0; i < imgs.length; i++) {
  194. let img = imgs[i]
  195. // TODO: 'src' is deprecated, use only data-src
  196. var src = img.getAttribute('src') || img.getAttribute('data-src')
  197. if (src === null) {
  198. } else if (src.match(/^(maki|temaki):.*/)) {
  199. /* HACK for temaki icons: as some icons are larger than the default 15px, force size to 15px. */
  200. if (src.match(/^temaki:/) && !img.hasAttribute('width') && !img.hasAttribute('height')) {
  201. img.setAttribute('width', '15')
  202. img.setAttribute('height', '15')
  203. }
  204. let m = src.match(/^(maki|temaki):([a-z0-9-_]*)(?:\?(.*))?$/)
  205. if (m) {
  206. maki(m[1], m[2], m[3] ? qs(m[3]) : {}, function (err, result) {
  207. if (err === null) {
  208. img.setAttribute('src', result)
  209. }
  210. })
  211. }
  212. } else if (src.match(/^(marker):.*/)) {
  213. let m = src.match(/^(marker):([a-z0-9-_]*)(?:\?(.*))?$/)
  214. if (m) {
  215. let span = document.createElement('span')
  216. img.parentNode.insertBefore(span, img)
  217. img.parentNode.removeChild(img)
  218. i--
  219. let param = m[3] ? qs(m[3]) : {}
  220. if (param.styles) {
  221. let newParam = { styles: param.styles }
  222. for (let k in param) {
  223. let m = k.match(/^(style|style:.*)?:([^:]*)$/)
  224. if (m) {
  225. if (!(m[1] in newParam)) {
  226. newParam[m[1]] = {}
  227. }
  228. newParam[m[1]][m[2]] = param[k]
  229. }
  230. }
  231. param = newParam
  232. }
  233. span.innerHTML = markers[m[2]](param)
  234. }
  235. } else if (!src.match(/^(https?:|data:|\.|\/)/)) {
  236. img.setAttribute('src', (typeof openstreetbrowserPrefix === 'undefined' ? './' : openstreetbrowserPrefix) +
  237. 'asset.php?repo=' + this.options.repositoryId + '&file=' + encodeURIComponent(img.getAttribute('data-src') || img.getAttribute('src')))
  238. }
  239. }
  240. }
  241. CategoryOverpass.prototype.load = function (callback) {
  242. OpenStreetBrowserLoader.getTemplate('popupBody', this.options, function (err, template) {
  243. if (err) {
  244. console.log("can't load popupBody.html")
  245. } else {
  246. this.popupBodyTemplate = template
  247. }
  248. callback(null)
  249. }.bind(this))
  250. }
  251. CategoryOverpass.prototype.setParentDom = function (parentDom) {
  252. CategoryBase.prototype.setParentDom.call(this, parentDom)
  253. }
  254. CategoryOverpass.prototype.setMap = function (map) {
  255. CategoryBase.prototype.setMap.call(this, map)
  256. this.map.on('zoomend', function () {
  257. this.updateStatus()
  258. this.updateInfo()
  259. }.bind(this))
  260. this.updateStatus()
  261. this.updateInfo()
  262. }
  263. CategoryOverpass.prototype.updateStatus = function () {
  264. this.domStatus.innerHTML = ''
  265. if (typeof this.data.query === 'object') {
  266. var highestZoom = Object.keys(this.data.query).reverse()[0]
  267. if (this.map.getZoom() < highestZoom) {
  268. this.domStatus.innerHTML = lang('zoom_in_more')
  269. }
  270. }
  271. if ('minZoom' in this.data && this.map.getZoom() < this.data.minZoom) {
  272. this.domStatus.innerHTML = lang('zoom_in_appear')
  273. }
  274. }
  275. CategoryOverpass.prototype.open = function () {
  276. if (this.isOpen) {
  277. return
  278. }
  279. CategoryBase.prototype.open.call(this)
  280. this.layer.addTo(this.map)
  281. if (!this.lists) {
  282. this.lists = []
  283. this.listsDom = []
  284. if (this.data.lists) {
  285. let wrapper = document.createElement('div')
  286. wrapper.className = 'categoryWrapper'
  287. this.domContent.appendChild(wrapper)
  288. for (let k in this.data.lists) {
  289. let listData = this.data.lists[k]
  290. this.layer.setLayout(listData.prefix, listTemplate.replace(/template/g, listData.prefix))
  291. let list = new OverpassLayerList(this.layer, listData)
  292. this.lists.push(list)
  293. let dom = document.createElement('div')
  294. dom.className = 'category category-list'
  295. this.listsDom.push(dom)
  296. wrapper.appendChild(dom)
  297. let domHeader = document.createElement('header')
  298. dom.appendChild(domHeader)
  299. let p = document.createElement('div')
  300. p.className = 'loadingIndicator'
  301. p.innerHTML = '<i class="fa fa-spinner fa-pulse fa-fw"></i><span class="sr-only">' + lang('loading') + '</span>'
  302. dom.appendChild(p)
  303. let name
  304. if (typeof listData.name === 'undefined') {
  305. name = k
  306. } else if (typeof listData.name === 'object') {
  307. name = lang(listData.name)
  308. } else {
  309. name = listData.name
  310. }
  311. let a = document.createElement('a')
  312. a.appendChild(document.createTextNode(name))
  313. a.href = '#'
  314. domHeader.appendChild(a)
  315. a.onclick = () => {
  316. dom.classList.toggle('open')
  317. return false
  318. }
  319. let domContent = document.createElement('div')
  320. domContent.className = 'content'
  321. dom.appendChild(domContent)
  322. list.addTo(domContent)
  323. showMore(this, domContent)
  324. p = document.createElement('div')
  325. p.className = 'loadingIndicator2'
  326. p.innerHTML = '<div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div>'
  327. dom.appendChild(p)
  328. }
  329. } else {
  330. let list = new OverpassLayerList(this.layer, {})
  331. this.lists.push(list)
  332. list.addTo(this.domContent)
  333. this.listsDom.push(this.domContent)
  334. showMore(this, this.domContent)
  335. }
  336. }
  337. this.listsDom.forEach(dom => dom.classList.add('open'))
  338. this.isOpen = true
  339. state.update()
  340. if ('info' in this.data) {
  341. if (!this.tabInfo) {
  342. this.tabInfo = new tabs.Tab({
  343. id: 'info'
  344. })
  345. this.tools.add(this.tabInfo)
  346. this.tabInfo.header.innerHTML = '<i class="fa fa-info-circle" aria-hidden="true"></i>'
  347. this.tabInfo.header.title = lang('category-info-tooltip')
  348. this.domInfo = this.tabInfo.content
  349. this.domInfo.classList.add('info')
  350. }
  351. if (!this.templateInfo) {
  352. this.templateInfo = OverpassLayer.twig.twig({ data: this.data.info, autoescape: true, rethrow: true })
  353. }
  354. this.updateInfo()
  355. }
  356. this.emit('open')
  357. }
  358. CategoryOverpass.prototype.updateInfo = function () {
  359. if (!this.tabInfo) {
  360. return
  361. }
  362. global.currentCategory = this
  363. var data = {
  364. layer_id: this.id,
  365. 'const': this.data.const
  366. }
  367. if (this.map) {
  368. data.map = {
  369. zoom: this.map.getZoom(),
  370. metersPerPixel: this.map.getMetersPerPixel()
  371. }
  372. }
  373. this.domInfo.innerHTML = this.templateInfo.render(data)
  374. this.updateAssets(this.domInfo)
  375. global.currentCategory = null
  376. }
  377. CategoryOverpass.prototype.recalc = function () {
  378. this.layer.recalc()
  379. }
  380. CategoryOverpass.prototype.close = function () {
  381. if (!this.isOpen) {
  382. return
  383. }
  384. CategoryBase.prototype.close.call(this)
  385. this.layer.remove()
  386. this.lists.forEach(list => list.remove())
  387. state.update()
  388. }
  389. CategoryOverpass.prototype.get = function (id, callback) {
  390. this.layer.get(id, callback)
  391. }
  392. CategoryOverpass.prototype.show = function (id, options, callback) {
  393. if (this.currentDetails) {
  394. this.currentDetails.hide()
  395. }
  396. let layerOptions = {
  397. styles: [ 'selected' ],
  398. flags: [ 'selected' ]
  399. }
  400. let idParts = id.split(/:/)
  401. switch (idParts.length) {
  402. case 2:
  403. id = idParts[1]
  404. layerOptions.sublayer_id = idParts[0]
  405. break
  406. case 1:
  407. break
  408. default:
  409. return callback(new Error('too many id parts! ' + id))
  410. }
  411. this.currentDetails = this.layer.show(id, layerOptions,
  412. function (err, ob, data) {
  413. if (!err) {
  414. if (!options.hasLocation) {
  415. var preferredZoom = data.data.preferredZoom || 16
  416. var maxZoom = this.map.getZoom()
  417. maxZoom = maxZoom > preferredZoom ? maxZoom : preferredZoom
  418. this.map.flyToBounds(data.object.bounds.toLeaflet({ shiftWorld: this.layer.getShiftWorld() }), {
  419. maxZoom: maxZoom
  420. })
  421. }
  422. }
  423. callback(err, data)
  424. }.bind(this)
  425. )
  426. }
  427. CategoryOverpass.prototype.notifyPopupOpen = function (object, popup) {
  428. if (this.currentSelected) {
  429. this.currentSelected.hide()
  430. }
  431. let layerOptions = {
  432. styles: [ 'selected' ],
  433. flags: [ 'selected' ],
  434. sublayer_id: object.sublayer_id
  435. }
  436. if (popup._contentNode) {
  437. popup._contentNode.style = ''
  438. }
  439. this.currentSelected = this.layer.show(object.id, layerOptions, function () {})
  440. this.currentPopupDisplay = new ObjectDisplay({
  441. feature: object,
  442. category: this,
  443. dom: popup._contentNode,
  444. displayId: 'popup'
  445. }, () => {})
  446. // Move close button into the content, to make its position depending whether a scrollbar is visible or not
  447. popup._closeButton.setAttribute('data-order', -1001)
  448. popup._contentNode.insertBefore(popup._closeButton, popup._contentNode.firstChild)
  449. }
  450. CategoryOverpass.prototype.notifyPopupClose = function (object, popup) {
  451. if (this.currentSelected) {
  452. this.currentSelected.hide()
  453. this.currentSelected = null
  454. }
  455. if (this.currentDetails) {
  456. this.currentDetails.hide()
  457. this.currentDetails = null
  458. }
  459. if (this.currentPopupDisplay) {
  460. this.currentPopupDisplay.close()
  461. delete this.currentPopupDisplay
  462. }
  463. }
  464. CategoryOverpass.prototype.renderTemplate = function (object, templateId, callback) {
  465. OpenStreetBrowserLoader.getTemplate(templateId, this.options, function (err, template) {
  466. if (err) {
  467. err = "can't load " + templateId + ': ' + err
  468. return callback(err, null)
  469. }
  470. var result = template.render(object.twigData)
  471. callback(null, result)
  472. })
  473. }
  474. CategoryOverpass.prototype.allMapFeatures = function (callback) {
  475. if (!this.isOpen) {
  476. return callback(null, [])
  477. }
  478. callback(null, Object.values(this.layer.mainlayer.visibleFeatures))
  479. }
  480. CategoryOverpass.defaultValues = defaultValues
  481. OpenStreetBrowserLoader.registerType('overpass', CategoryOverpass)
  482. module.exports = CategoryOverpass