Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 1a1d8f64

Přidáno uživatelem Martin Sebela před více než 3 roky(ů)

Re #8163 - refactoring

Zobrazit rozdíly:

website/public/js/zcu-heatmap.js
34 34
// }
35 35
//
36 36
var info = []
37
let currentInfo = 0
37
let currentPageInPopup = 0
38 38

  
39 39
// dictionary for names of datasets
40 40
const datasetDictNameDisplayName = {}
......
65 65
  },
66 66
  _popup: null
67 67
}
68

  
68 69
const setGlobalPopupContent = (content) => {
69 70
  globalPopup._popup.setContent(content)
70 71
  globalPopup._popup.openOn(mymap)
71 72
}
73

  
72 74
const disablePopupControls = () => {
73
  $('#previous-info-btn').prop('disabled', true)
74
  $('#next-info-btn').prop('disabled', true)
75
  $('#btn-previous-page').prop('disabled', true)
76
  $('#btn-next-page').prop('disabled', true)
75 77
  $('.popup-controls').hide()
76 78
}
77 79

  
......
87 89
    }
88 90
  }, delay)
89 91
}
92

  
90 93
const loadingY = (delay = defaultLoaderDelay) => {
91 94
  loading++
92 95
  // check after nms if there is something that is loading
93 96
  loadingCallbackNested(() => loadingCallbackNested((isLoading) => loadingTimeline(isLoading), delay))
94 97
}
98

  
95 99
const loadingN = (delay = defaultLoaderDelay) => {
96 100
  loading--
97 101
  loadingCallbackNested(() => loadingCallbackNested((isLoading) => loadingTimeline(isLoading)), delay)
......
106 110
}
107 111

  
108 112
const changeCurrentDate = (date = null) => {
109
  if (date) {
110
    currentDate = new Date(date)
111
  } else {
112
    currentDate = new Date($('#date').val())
113
  }
113
  const dateInput = $('#date')
114
  currentDate = new Date(date ? date : dateInput.val())
114 115

  
115
  $('#date').val(currentDateToString())
116
  dateInput.val(currentDateToString())
116 117
  $('#player-date span').html(`${currentDate.getDate()}. ${currentDate.getMonth() + 1}. ${currentDate.getFullYear()}`)
117 118

  
118 119
  data = []
119 120
}
121

  
120 122
const currentDayToString = () => {
121 123
  const day = currentDate.getDate()
122 124
  return day > 9 ? `${day}` : `0${day}`
123 125
}
126

  
124 127
const currentMonthToString = () => {
125 128
  const month = currentDate.getMonth() + 1
126 129
  return month > 9 ? `${month}` : `0${month}`
127 130
}
131

  
128 132
const currentDateToString = () => `${currentDate.getFullYear()}-${currentMonthToString()}-${currentDayToString()}`
133

  
129 134
const addDayToCurrentDate = (day) => {
130 135
  currentDate.setDate(currentDate.getDate() + day)
131 136
  changeCurrentDate(currentDate)
132 137
}
138

  
133 139
const toggleDayLock = () => {
134 140
  lockedDay = !lockedDay
135 141
  $('#player-date').toggleClass('lock')
......
142 148
    headers: headers
143 149
  })
144 150
  const beforeJson = await fetch(myRequest)
151

  
145 152
  return beforeJson.json()
146 153
}
147 154

  
......
152 159
    headers: headers
153 160
  })
154 161
  const beforeJson = await fetch(myRequest)
162

  
155 163
  return beforeJson.json()
156 164
}
157 165

  
158
const genPopUpControlButtons = (currentPage, numPages, onNextClick, onPreviousClick) => ({
159
  previousButton: '<button id="previous-info-btn" class="circle-button" onclick="previousInfo()"></button>',
160
  nextButton: '<button id="next-info-btn" class="circle-button next" onclick="nextInfo()"></button>',
161
  posInfo: `<div id="pages">${currentPage} z ${numPages}</div>`
166
const getPaginationButtonsInPopup = (currentPage, countPages) => ({
167
  previousButton: '<button id="btn-previous-page" class="circle-button" onclick="setPreviousPageInPopup()"></button>',
168
  pagesList: `<div id="pages">${currentPage} z ${countPages}</div>`,
169
  nextButton: '<button id="btn-next-page" class="circle-button next" onclick="setNextPageInPopup()"></button>'
162 170
})
163 171

  
164 172
const genPopUpControls = (controls) => {
165 173
  return `<div class="popup-controls">${controls ? controls.reduce((sum, item) => sum + item, '') : ''}</div>`
166 174
}
167 175

  
168
const genMultipleDatasetsPopUp = (sum, currentPos, maxPos, datasetName) => {
169
  const popupHeader = `<strong id="dataset-info">${datasetName}</strong>`
176
const genMultipleDatasetsPopUp = (sum, currentPage, countPages, datasetName) => {
177
  const popupHeader = `<strong id="dataset-name">${datasetName}</strong>`
170 178
  const popupData = `<div id="number-info"><span id="current-number">${sum}</span></div>`
171
  const { previousButton, nextButton, posInfo } = genPopUpControlButtons(currentPos, maxPos)
179
  const { previousButton, nextButton, pagesList } = getPaginationButtonsInPopup(currentPage, countPages)
172 180

  
173 181
  return `
174 182
  ${popupHeader}
175 183
  ${popupData}
176
  ${genPopUpControls([previousButton, posInfo, nextButton])}
184
  ${genPopUpControls([previousButton, pagesList, nextButton])}
177 185
  `
178 186
}
179 187

  
......
182 190
  className: className
183 191
}).setLatLng([lat / num, lng / num])
184 192

  
185
const genPopUp = (datasetName, place, currentCount, sum, currentPos, maxPos) => {
193
const getPopupContent = (datasetName, placeName, currentCount, sum, currentPage, countPages) => {
186 194
  const popupHeader = `
187 195
    <strong>${datasetName}</strong>
188
    <div id="place-info">${place}</div>`
196
    <div id="place-name">${placeName}</div>`
189 197
  const popupData = `
190 198
    <div id="number-info">
191 199
      <span id="current-number">${currentCount}</span>
192
      <span id="part-info">${(sum && (sum !== Number(currentCount))) ? '/' + sum : ''}</span>
200
      <span id="part-info">${(sum && sum !== Number(currentCount)) ? '/' + sum : ''}</span>
193 201
    </div>`
194
  const { previousButton, nextButton, posInfo } = genPopUpControlButtons(currentPos, maxPos)
202
  const { previousButton, nextButton, pagesList } = getPaginationButtonsInPopup(currentPage, countPages)
195 203

  
196 204
  return `
197 205
  ${popupHeader}
198 206
  ${popupData}
199
  ${genPopUpControls(maxPos > 1 ? [previousButton, posInfo, nextButton] : null)}
207
  ${genPopUpControls(countPages > 1 ? [previousButton, pagesList, nextButton] : null)}
200 208
  `
201 209
}
202 210

  
......
212 220
          delete data[index][datasetName]
213 221
        }
214 222
      })
223

  
215 224
      drawHeatmap(data[currentTime])
216 225
    })
217 226
  }
227

  
218 228
  updatePopup()
219
  changeUrl()
229
  changeUrlParameters()
220 230
}
221 231

  
222 232
const onArrowLeftRightKeysDownRegister = () => {
......
247 257
  $('#date').change(function () {
248 258
    changeCurrentDate($(this).val())
249 259
    loadCurrentTimeHeatmap(dataSourceRoute, positionsSourceRoute, 0)
250
    changeUrl()
260
    changeUrlParameters()
251 261
  })
252 262

  
253 263
  $('#dropdown-time input[type="radio"]').each(function () {
......
283 293
  mymap.on('click', function (e) { showInfo(e) })
284 294
}
285 295

  
286
const getInfoLength = () => {
296
const getCountPagesInPopup = () => {
287 297
  const infoKeys = Object.keys(info)
288 298
  if (infoKeys.length === 1) {
289 299
    // return number of records in one dataset (one dataset in area)
......
304 314

  
305 315
function showInfo (e) {
306 316
  info = []
307
  currentInfo = 0
308
  const currentPos = 1
317
  currentPageInPopup = 0
309 318

  
310 319
  // https://wiki.openstreetmap.org/wiki/Zoom_levels
311 320
  // Todo change to variable - it is used in heatmap init
......
336 345
      }
337 346
    })
338 347
  })
348

  
339 349
  // Process info for more then one dataset
340 350
  info = info.reduce((acc, item) => {
341 351
    if (!acc[item.datasetName]) {
......
353 363
  // There is one dataset
354 364

  
355 365
  const numDatasets = Object.keys(datasetsInRadius).length
366

  
356 367
  if (!numDatasets) {
357 368
    if (mymap._popup) {
358 369
      $('#part-info').text('')
......
362 373

  
363 374
    return
364 375
  }
376

  
365 377
  if (numDatasets === 1) {
366 378
    const infoDict = getElFromObjectInfo(0)
367 379
    const info_ = infoDict.items
368
    const { place, number } = info_[currentInfo]
380
    const { place, number } = info_[currentPageInPopup]
369 381

  
370 382
    if (!globalPopup._popup || !areSameCoord(globalPopup.coord, eventCoord)) {
371 383
      globalPopup._popup = prepareLayerPopUp(lat, lng, i, `popup-${infoDict.datasetName}`)
372 384
      globalPopup.coord = eventCoord
373 385
    }
374 386

  
375
    setGlobalPopupContent(genPopUp(datasetDictNameDisplayName[infoDict.datasetName], place, number, total, currentPos, info_.length))
387
    setGlobalPopupContent(getPopupContent(datasetDictNameDisplayName[infoDict.datasetName], place, number, total, 1, info_.length))
376 388

  
377 389
    if (info_.length === 1) {
378 390
      disablePopupControls()
379 391
    }
380 392
  } else {
381
    const { datasetName, number } = getElFromObjectInfo(currentInfo)
393
    const { datasetName, number } = getElFromObjectInfo(currentPageInPopup)
382 394

  
383 395
    if (!globalPopup._popup || !areSameCoord(globalPopup.coord, eventCoord)) {
384 396
      globalPopup._popup = prepareLayerPopUp(lat, lng, i, `popup-${datasetName}`)
385 397
      globalPopup.coord = eventCoord
386 398
    }
387 399

  
388
    setGlobalPopupContent(genMultipleDatasetsPopUp(number, currentPos, getInfoLength(), datasetDictNameDisplayName[datasetName]))
400
    setGlobalPopupContent(genMultipleDatasetsPopUp(number, 1, getCountPagesInPopup(), datasetDictNameDisplayName[datasetName]))
389 401
  }
390 402
}
391 403

  
392 404
// eslint-disable-next-line no-unused-vars
393
function previousInfo () {
394
  const infoLength = getInfoLength()
395
  const previousCurrentInfo = currentInfo
405
function setPreviousPageInPopup () {
406
  const countPagesInPopup = getCountPagesInPopup()
407
  const newPage = currentPageInPopup
396 408

  
397
  currentInfo = (currentInfo + infoLength - 1) % infoLength
398
  displayInfoText(previousCurrentInfo)
409
  currentPageInPopup = (currentPageInPopup + countPagesInPopup - 1) % countPagesInPopup
410
  setPageContentInPopup(newPage)
399 411
}
400 412

  
401 413
// eslint-disable-next-line no-unused-vars
402
function nextInfo () {
403
  const infoLength = getInfoLength()
404
  const previousCurrentInfo = currentInfo
414
function setNextPageInPopup () {
415
  const countPagesInPopup = getCountPagesInPopup()
416
  const newPage = currentPageInPopup
405 417

  
406
  currentInfo = (currentInfo + 1) % infoLength
407
  displayInfoText(previousCurrentInfo)
418
  currentPageInPopup = (currentPageInPopup + 1) % countPagesInPopup
419
  setPageContentInPopup(newPage)
408 420
}
409 421

  
410
function displayInfoText (previousInfoNum) {
411
  const previousInfo = hasInfoMultipleDatasets() ? getElFromObjectInfo(previousInfoNum) : getElFromObjectInfo(0).items[previousInfoNum]
412
  const info_ = hasInfoMultipleDatasets() ? getElFromObjectInfo(currentInfo) : getElFromObjectInfo(0).items[currentInfo]
413
  const infoLength = getInfoLength()
414
  const datasetInfo = $('#dataset-info')
422
function setPageContentInPopup (page) {
423
  const previousPageData = hasInfoMultipleDatasets() ? getElFromObjectInfo(page) : getElFromObjectInfo(0).items[page]
424
  const currentPageData = hasInfoMultipleDatasets() ? getElFromObjectInfo(currentPageInPopup) : getElFromObjectInfo(0).items[currentPageInPopup]
425
  const datasetName = $('#dataset-name')
415 426

  
416
  if (datasetInfo) {
417
    $(datasetInfo).html(datasetDictNameDisplayName[info_.datasetName])
427
  if (datasetName) {
428
    datasetName.html(datasetDictNameDisplayName[currentPageData.datasetName])
418 429
  }
419 430

  
420
  $('#place-info').html(info_.place ? info_.place : info_.datasetName)
421
  $('#current-number').html(info_.number)
422
  $('#pages').html(currentInfo + 1 + ' z ' + infoLength)
431
  $('#place-name').html(currentPageData.place ? currentPageData.place : currentPageData.datasetName)
432
  $('#current-number').html(currentPageData.number)
433
  $('#pages').html(currentPageInPopup + 1 + ' z ' + getCountPagesInPopup())
423 434

  
424
  $('.leaflet-popup').removeClass(`popup-${previousInfo.datasetName}`)
425
  $('.leaflet-popup').addClass(`popup-${info_.datasetName}`)
435
  $('.leaflet-popup').removeClass(`popup-${previousPageData.datasetName}`).addClass(`popup-${currentPageData.datasetName}`)
426 436
}
427 437

  
428 438
// eslint-disable-next-line no-unused-vars
......
430 440
  localStorage.setItem('lat', latitude)
431 441
  localStorage.setItem('lng', longitude)
432 442
  localStorage.setItem('zoom', zoom)
443

  
433 444
  mymap.setView([latitude, longitude], zoom)
434 445
}
435 446

  
......
438 449
 */
439 450
// eslint-disable-next-line no-unused-vars
440 451
function changeAnimationState () {
452
  const btnAnimate = $('#animate-btn')
453

  
441 454
  isAnimationRunning = !isAnimationRunning
442 455

  
443 456
  if (isAnimationRunning) {
444
    $('#animate-btn').removeClass('play').addClass('pause')
457
    btnAnimate.removeClass('play').addClass('pause')
445 458
    timer = setInterval(function () { next() }, 800)
446 459
  } else {
447 460
    clearTimeout(timer)
448
    $('#animate-btn').removeClass('pause').addClass('play')
461
    btnAnimate.removeClass('pause').addClass('play')
449 462
  }
450 463
}
451 464

  
......
457 470

  
458 471
  currentTime = (currentTime + 23) % 24
459 472
  changeHour(currentTime)
460
  // mymap.closePopup()
461
  if (!lockedDay && (currentTime === 23)) {
473
  
474
  if (!lockedDay && currentTime === 23) {
462 475
    addDayToCurrentDate(-1)
463 476
    await loadCurrentTimeHeatmap(dataSourceRoute, positionsSourceRoute)
464 477
  } else {
465 478
    drawHeatmap(data[currentTime])
466 479
  }
480

  
467 481
  updatePopup()
468 482
}
469 483

  
......
474 488

  
475 489
  currentTime = (currentTime + 1) % 24
476 490
  changeHour(currentTime)
477
  if (!lockedDay && (currentTime === 0)) {
491

  
492
  if (!lockedDay && currentTime === 0) {
478 493
    addDayToCurrentDate(1)
479 494
    await loadCurrentTimeHeatmap(dataSourceRoute, positionsSourceRoute)
480 495
  } else {
481 496
    drawHeatmap(data[currentTime])
482 497
  }
498

  
483 499
  updatePopup()
484 500
}
485 501

  
486 502
/**
487 503
 * Change browser url based on animation step.
488 504
 */
489
function changeUrl () {
505
const changeUrlParameters = () => {
490 506
  window.history.pushState(
491 507
    '',
492 508
    document.title,
......
494 510
  )
495 511
}
496 512

  
497
function updateHeaderControls () {
513
const updateHeaderControls = () => {
498 514
  $(`#time_${currentTime}`).prop('checked', true)
499 515
  $('#dropdownMenuButtonTime').html((currentTime < 10 ? '0' : '') + `${currentTime}:00`)
500 516
}
501 517

  
502
function setTimeline () {
518
const setTimeline = () => {
503 519
  $('#player-time > span').text(currentTime + ':00')
504 520
  $('#player-time').attr('class', 'time hour-' + currentTime)
505 521
}
......
511 527
    loadingNTimeline()
512 528
  }
513 529
}
530

  
514 531
const loadingYTimeline = () => {
515 532
  $('#player-time > .spinner-border').removeClass('d-none')
516 533
  $('#player-time > span').text('')
517 534
}
535

  
518 536
const loadingNTimeline = () => {
519 537
  $('#player-time > .spinner-border').addClass('d-none')
520 538
  setTimeline()
521 539
}
540

  
522 541
const onChangeHour = (hour) => {
523 542
  changeHour(hour)
524 543
  drawHeatmap(data[currentTime])
......
529 548
  changeCurrentTime(hour)
530 549
  updateHeaderControls()
531 550
  setTimeline()
532
  changeUrl()
551
  changeUrlParameters()
533 552
  updatePopup()
534 553
}
535 554

  
536 555
const updatePopup = () => {
537 556
  const { _popup } = mymap
557

  
538 558
  if (_popup) {
539 559
    showInfo({
540 560
      latlng: _popup.getLatLng()
541
    }
542
    )
561
    })
543 562
  }
544 563
}
564

  
545 565
/**
546 566
 * Load and display heatmap layer for current data
547 567
 * @param {string} opendataRoute route to dataset source
......
560 580
    if (!(datasetName in dataSourceMarks)) {
561 581
      dataSourceMarks[datasetName] = await fetchDataSourceMarks(positionsRoute, datasetName)
562 582
    }
583

  
563 584
    const datasetData = await fetchByNameDate(dataSourceRoute, datasetName, currentDateToString(), currentTime)
564 585
    data[currentTime][datasetName] = datasetData
565 586
  }
......
568 589
  })
569 590

  
570 591
  loadingY(loaderDelay)
592

  
571 593
  await Promise.all(allPromises).then(
572 594
    () => {
573 595
      loadingN(0)
......
591 613
      const { x, y, name } = data[key_][key]
592 614
      const pop =
593 615
          prepareLayerPopUp(x, y, 1, `popup-${key_}`)
594
            .setContent(genPopUp(datasetDictNameDisplayName[key_], name, 0, 0, 1, 1))
616
            .setContent(getPopupContent(datasetDictNameDisplayName[key_], name, 0, 0, 1, 1))
595 617
      const newCircle =
596 618
        L.circle([x, y], { radius: 2, fillOpacity: 0.8, color: '#004fb3', fillColor: '#004fb3', bubblingMouseEvents: true })
597 619
          .bindPopup(pop)
......
607 629

  
608 630
async function preload (time, change, date) {
609 631
  loadingY()
632

  
610 633
  for (let nTime = time + change; nTime >= 0 && nTime <= 23; nTime = nTime + change) {
611 634
    if (!data[nTime]) {
612 635
      data[nTime] = {}
......
618 641
      }
619 642
    })
620 643
  }
644

  
621 645
  loadingN()
622 646
}
623 647

  
......
746 770
}
747 771

  
748 772
function initLocationsMenu () {
749
  var locationsWrapper = '.locations'
750
  var locationsDisplayClass = 'show'
773
  const elmLocationsList = $('.locations')
774
  const locationsDisplayClass = 'show'
751 775

  
752 776
  if ($(window).width() <= 480) {
753
    $(locationsWrapper).removeClass(locationsDisplayClass)
777
    elmLocationsList.removeClass(locationsDisplayClass)
754 778
  } else {
755
    $(locationsWrapper).addClass(locationsDisplayClass)
779
    elmLocationsList.addClass(locationsDisplayClass)
756 780
  }
757 781
}
758 782

  
......
770 794

  
771 795
const loadCheckboxDatasetNameData = () => {
772 796
  datasetSelected = []
797

  
773 798
  $('#dropdown-dataset .dropdown-item').each(function () {
774 799
    const input = $(this).find('input')
775 800
    const inputVal = input[0].value
......
782 807
  })
783 808
}
784 809

  
785
function dragTimeline () {
810
const dragTimeline = () => {
786 811
  const hourElemWidthPx = 26
787 812

  
788 813
  const elem = $('#player-time')
......
791 816
  if (offset >= 0 && offset <= elem.parent().width()) {
792 817
    const hour = Math.round(offset / hourElemWidthPx)
793 818

  
794
    if (hour != currentTime) {
819
    if (hour !== currentTime) {
795 820
      elem.attr('class', 'time hour-' + hour)
796 821
      $('#player-time span').html(hour + ':00')
797 822

  

Také k dispozici: Unified diff