cootook / project

Learn by doing project for everybody
MIT License
0 stars 0 forks source link

[TICKET] - get rid of moment.js in calendar.js #19

Open cootook opened 8 months ago

cootook commented 8 months ago

Summary:

To show interactive calendar we use module calendar.js . In calendar.js we use open source library moment.js for working with dates. These js modules are imported via template calendar.html. image

The goal is to get rid of moment.js and use JS, WEB API and small functions in calendar.js

Impact/Urgency:

low priority

Full Description:

Module calendar.js was taken from sliderrevolution.com and adapted for the app by @cootook . This module is using open source library calendar.js In fact the object moment and its methods are used a few times and can be replaced by Vanilla JS and WEB API. There is a library to help to replace module's methods. Also this article can be useful.

We have two parts where moment.js used:

  1. var today = moment();
    
    Calendar.prototype.getDayClass = function(day) {
      classes = ['day'];
      if(day.month() !== this.current.month()) {
        classes.push('other');
      } else if (today.isSame(day, 'day')) {
        classes.push('today');
      }
      return classes.join(' ');
    }
  2. Template calendar.html is included in other templates (index.html, windows.html). Via <script>var action_path = "/windows/"; var slots = {{slots}} </script> two variables are declared before including calendar.html. Variable of Jinja template slot is passed from route handler return render_template("windows.html", slots=slots) slots is a list of time slots that should be shown in calendar. That list is gotten from database with query: "SELECT slot_id, year, month, day, hour, minute, is_open FROM calendar WHERE year>=?", (today.year,) In calendar.js all dates before today filtered out.

  !function() {
    filtered_slots = []    
    slots.forEach((slot) => {
      if (slot[1] < moment().year()) {

        return
      } else if (slot[1] == moment().year() && slot[2] < moment().month()+1) {        
        return
      } else if (slot[1] == moment().year() && slot[2] == moment().month()+1 && slot[3] < moment().date()) {
        return
      } else {
        filtered_slots.push(slot)
        return
      }
    })
    var data = filtered_slots.map((slot) => {
      slot_status = slot[6] == 1 ? 'Avaliable time' : 'Closed time'
      slot_color  = slot[6] == 1 ? 'green' : 'yellow'
      slot[5] = (slot[5] < 10) ? ('0' + slot[5]) : slot[5]
      var the_date = moment().minute(slot[5]).hour(slot[4]).date(slot[3]).month(slot[2] - 1).year(slot[1])
      return { eventName: the_date.format("llll"), calendar: slot_status, color: slot_color, date: the_date}
    });

Test Cases:

routes:

JavaScript Date objects

moment.js