more refactoring

more refactoring

--- app/coffee/drm-calendar/drm-calendar.coffee
+++ app/coffee/drm-calendar/drm-calendar.coffee
@@ -588,6 +588,29 @@
                 i = i + 1
             weekInfo

+        getWeekNumber: (currentMonth, currentDate, currentYear) =>
+            self = @
+            weekNum = 1
+            weekNums = []
+            weekInfo = self.getDatesInWeek currentMonth, currentDate, currentYear
+
+            $.each self.months, (key, value) ->
+                numberDays = self.getDaysInMonth key, currentYear
+                firstDay = self.getDayOfWeek key, 1, currentYear
+                dayShift = if firstDay is self.daysPerWeek then 0 else firstDay
+                numberWeeks = self.getWeeksInMonth currentMonth, currentYear
+                week = 1
+                if $.isNumeric numberWeeks
+                    until week > numberWeeks
+                        if week is 1 and firstDay isnt 0
+                            weekNum = weekNum
+                        else
+                            weekNum = weekNum + 1
+                        week = week + 1
+                        if currentMonth is key
+                            weekNums.push weekNum
+            weekNumber = weekNums[weekInfo.weekNum]
+
         createEvent: (newEvent) =>
             id = @events.length
             obj =
@@ -604,48 +627,6 @@
                 notes: if newEvent.notes? then newEvent.notes else null
             @events.push obj
             @addEventsToCalendar @events[obj.id]
-
-        addCalendarEvent: (events, dates) =>
-            calendarInner = @calendar.find "div.#{@calendarInnerClass}"
-
-            if @view is 'month'
-                calendarItem = calendarInner.find ".drm-date[data-date=#{dates}]"
-            else if !events.time?
-                calendarItem = calendarInner.find ".drm-date[data-date=#{dates}][data-hour='All Day Event']"
-            else
-                # find hour td element
-                re = new RegExp '^0?','gi'
-                re2 = new RegExp ':[0-9]{2}', 'gi'
-                hour = events.time.replace re, ''
-                hour = hour.replace re2, ''
-                calendarItem = calendarInner.find ".drm-date[data-date=#{dates}][data-hour=#{hour}]"
-
-            eventList = calendarItem.find "ul.#{@eventClass}"
-            length = eventList.length
-
-            eventContent =
-                if events.time?
-                    "#{events.time}: #{events.name}"
-                else
-                    "#{events.name}"
-
-            eventHtml = $ '',
-                href: '#'
-                'data-event': events.id
-                html: eventContent
-
-            if length is 0
-                eventList = $ '

',
-                    class: @eventClass
-
-                eventList.appendTo calendarItem
-
-            item = $ '

',
-                html: eventHtml
-
-            item.appendTo eventList
-
-            if events.type is 'holiday' then eventList.find("a:contains(#{events.name})").addClass @classes.holiday

         removeCalendarEvent: (eventId, index) =>
             events = @calendar.find "ul.#{@eventClass} a[data-event=#{eventId}]"
@@ -821,6 +802,48 @@
                 eventDates.push parseInt(events.eventDate, 10)
                 eventDates

+            _addCalendarEvent = (events, dates) ->
+                # create event html
+
+                if self.view is 'month'
+                    calendarItem = calendarInner.find ".drm-date[data-date=#{dates}]"
+                else if !events.time?
+                    calendarItem = calendarInner.find ".drm-date[data-date=#{dates}][data-hour='All Day Event']"
+                else
+                    # find hour td element
+                    re = new RegExp '^0?','gi'
+                    re2 = new RegExp ':[0-9]{2}', 'gi'
+                    hour = events.time.replace re, ''
+                    hour = hour.replace re2, ''
+                    calendarItem = calendarInner.find ".drm-date[data-date=#{dates}][data-hour=#{hour}]"
+
+                eventList = calendarItem.find "ul.#{self.eventClass}"
+                length = eventList.length
+
+                eventContent =
+                    if events.time?
+                        "#{events.time}: #{events.name}"
+                    else
+                        "#{events.name}"
+
+                eventHtml = $ '',
+                    href: '#'
+                    'data-event': events.id
+                    html: eventContent
+
+                if length is 0
+                    eventList = $ '

',
+                        class: self.eventClass
+
+                    eventList.appendTo calendarItem
+
+                item = $ '

',
+                    html: eventHtml
+
+                item.appendTo eventList
+
+                if events.type is 'holiday' then eventList.find("a:contains(#{events.name})").addClass self.classes.holiday
+
             if events.recurrance is 'yearly' and currentMonth is month
                 _addYearlyEvents events, eventDates
             else if events.recurrance is 'monthly'
@@ -836,98 +859,7 @@
             if eventDates.length > 0
                 $.each eventDates, (key, date) ->
                     # add css classes here
-                    self.addCalendarEvent events, date
-
-        highlightWeekends: =>
-            self = @
-            calendarInner = self.calendar.find "div.#{@calendarInnerClass}"
-            weeks = calendarInner.find '.drm-week'
-            weekends = [
-                $.inArray('Sunday', self.days)
-                $.inArray('Saturday', self.days)
-            ]
-
-            $.each weeks, ->
-                that = $ @
-                $.each weekends, (key, value) ->
-                    weekend = that.find(".#{self.classes.date}[data-day=#{value}]").not ".#{self.classes.muted}, .#{self.classes.today}, .#{self.classes.holiday}"
-                    weekend.addClass self.classes.weekend
-
-        highlightCurrentDay: =>
-            calendarInner = @calendar.find "div.#{@calendarInnerClass}"
-            month = calendarInner.data 'month'
-            year = calendarInner.data 'year'
-
-            if month is @currentMonth and year is @currentYear
-                calendarInner.find(".drm-date[data-date=#{@currentDate}]").addClass @classes.today
-
-        addWeekNumbers: =>
-            self = @
-            calendarInner = self.calendar.find "div.#{@calendarInnerClass}"
-            month = calendarInner.data 'month'
-            year = calendarInner.data 'year'
-            weekNum = 1
-            weeks = calendarInner.find '.drm-week'
-            weekNums = []
-
-            $.each self.months, (key, value) ->
-                firstDay = self.getDayOfWeek key, 1, year
-                dayShift = if firstDay is self.daysPerWeek then 0 else firstDay
-                numberWeeks = self.getWeeksInMonth month, year
-                week = 1
-                if $.isNumeric numberWeeks
-                    until week > numberWeeks
-                        if week is 1 and firstDay isnt 0
-                            weekNum = weekNum
-                        else
-                            weekNum = weekNum + 1
-                        week = week + 1
-
-                        if month is key
-                            weekNums.push weekNum
-
-            if self.view is 'month'
-                $.each weekNums, (key, value) ->
-                    week = weeks.eq key
-                    if value % 2 is 0 then week.addClass('even-week') else week.addClass('odd-week')
-                    week.attr 'data-week', value
-            else if self.view is 'week'
-                weekNum = weekNums[0] + weeks.data('month-week-num')
-                if weekNum % 2 is 0 then weeks.addClass('even-week') else weeks.addClass('odd-week')
-                weeks.attr 'data-week', weekNum
-
-        getWeekNumber: (currentMonth, currentDate, currentYear) =>
-            self = @
-            weekNum = 1
-            weekNums = []
-            weekInfo = self.getDatesInWeek currentMonth, currentDate, currentYear
-
-            $.each self.months, (key, value) ->
-                numberDays = self.getDaysInMonth key, currentYear
-                firstDay = self.getDayOfWeek key, 1, currentYear
-                dayShift = if firstDay is self.daysPerWeek then 0 else firstDay
-                numberWeeks = self.getWeeksInMonth currentMonth, currentYear
-                week = 1
-                if $.isNumeric numberWeeks
-                    until week > numberWeeks
-                        if week is 1 and firstDay isnt 0
-                            weekNum = weekNum
-                        else
-                            weekNum = weekNum + 1
-                        week = week + 1
-                        if currentMonth is key
-                            weekNums.push weekNum
-            weekNumber = weekNums[weekInfo.weekNum]
-
-        changeCalendarView: (view) =>
-            calendar = $ ".#{@calendarInnerClass}"
-
-            currentMonth = calendar.data 'month'
-            currentYear = calendar.data 'year'
-            currentDate = if currentMonth is @currentMonth then @currentDate else 1
-
-            @view = view
-            @changeCalendar currentMonth, currentDate, currentYear
+                    _addCalendarEvent events, date

         advanceDate: (direction) =>
             calendarInner = @calendar.find "div.#{@calendarInnerClass}"
@@ -1034,260 +966,271 @@

             @changeCalendar currentMonth, currentDate, currentYear

+        changeCalendarView: (view) =>
+            calendar = $ ".#{@calendarInnerClass}"
+            currentMonth = calendar.data 'month'
+            currentYear = calendar.data 'year'
+            currentDate = if currentMonth is @currentMonth then @currentDate else 1
+            # update view
+            @view = view
+            @changeCalendar currentMonth, currentDate, currentYear
+            # change calendar class
+            @calendarInnerClass = "drm-calendar-#{view}-view"
+
         changeCalendar: (month, date, year) =>
             self = @
-            calendarInner = self.calendar.find "div.#{@calendarInnerClass}"
+            calendarInner = self.calendar.find "div.#{self.calendarInnerClass}"
             calendarInner.fadeOut(300).queue (next) ->
                 $.when(calendarInner.remove()).then(self.createCalendar(month, date, year))
                 next()

-        createMonthView: (currentMonth, currentYear) =>
+        createCalendar: (currentMonth, currentDate, currentYear) =>
             self = @
-            self.calendarInnerClass = "drm-calendar-#{self.view}-view"
+            nextYear = currentYear + 1
+            lastYear = currentYear - 1
+            nextMonth = if currentMonth is 11 then 0 else currentMonth + 1
+            lastMonth = if currentMonth is 0 then 11 else currentMonth - 1
             firstDay = self.getDayOfWeek currentMonth, 1, currentYear
             dayShift = if firstDay is self.daysPerWeek then 0 else firstDay
             numberDays = self.getDaysInMonth currentMonth, currentYear
             numberWeeks = self.getWeeksInMonth currentMonth, currentYear
-            nextYear = currentYear + 1
-            lastYear = currentYear - 1
-            nextMonth = if currentMonth is 11 then 0 else currentMonth + 1
-            lastMonth = if currentMonth is 0 then 11 else currentMonth - 1
             prevMonthNumberDays = self.getDaysInMonth lastMonth, currentYear
-            calendar = null
-            heading = null
-            weekdays = null
-            weeks = null
-
-            weekdays = '

'
-            $.each self.days, (key, value) ->
-                weekdays += "#{value}	"
-            weekdays += '

'
-
-            weeks = "
"
-            i = 1
-            currentDate = 1
-            l = 1
-            prevDays = (prevMonthNumberDays - dayShift) + 1
-            nextDates = 1
-
-            while i <= numberWeeks
-                j = 1
-                weeks += "
"
-                # if we are in week 1 we need to shift to the correct day of the week
-                if i is 1 and firstDay isnt 0
-                    # add cells for the previous month until we get to the first day
-                    while l <= dayShift
-                        weeks += "#{prevDays}	"
-                        prevDays += 1
-                        l += 1
-                        j += 1
-                    # start adding cells for the current month
-                    while j <= self.daysPerWeek
-                        weeks += "#{currentDate}	"
-                        j += 1
-                        currentDate += 1
-                # if we are in the last week of the month we need to add blank cells for next month
-                else if i is numberWeeks
-                    while j <= self.daysPerWeek
-                        # finish adding cells for the current month
-                        if currentDate <= numberDays
-                            weeks += "#{currentDate}	"
-                        # start adding cells for next month
-                        else
-                            weeks += "#{nextDates}	"
-                            nextDates += 1
-                        j += 1
-                        currentDate += 1
-                else
-                    # if we are in the middle of the month add cells for the current month
-                    while j <= self.daysPerWeek
-                        weeks += "#{currentDate}	"
-                        j += 1
-                        currentDate += 1
-                weeks += '
'
-                i += 1
-            weeks += '

'
-
-            calendar = $ '

',
-                class: self.calendarInnerClass
-                html: weekdays + weeks
-                'data-month': currentMonth
-                'data-year': currentYear
-
-            heading = $ '

',
-                class: 'drm-calendar-header'
-                text: "#{@months[currentMonth]} #{currentYear}"
-
-            calendar.appendTo ".#{self.calendarClass}"
-            heading.prependTo ".#{self.calendarInnerClass}"
-
-            self.highlightCurrentDay()
-            self.highlightWeekends()
-            self.addWeekNumbers()
-
-            $.each self.events, (key, value) ->
-                self.addEventsToCalendar value
-
-            $('.drm-calendar-year-prev').text lastYear
-            $('.drm-calendar-year-next').text nextYear
-
-            $('.drm-calendar-month-prev').text self.months[lastMonth]
-            $('.drm-calendar-month-next').text self.months[nextMonth]
-
-            $('.drm-calendar-week-prev, .drm-calendar-week-next').hide()
-            $('.drm-calendar-date-prev, .drm-calendar-date-next').hide()
-
-        createWeekView: (currentMonth, currentDate, currentYear) =>
-            self = @
-            self.calendarInnerClass = "drm-calendar-#{self.view}-view"
-            firstDay = self.getDayOfWeek currentMonth, 1, currentYear
-            dayShift = if firstDay is self.daysPerWeek then 0 else firstDay
-            numberWeeks = self.getWeeksInMonth currentMonth, currentYear
-            nextYear = currentYear + 1
-            lastYear = currentYear - 1
-            nextMonth = if currentMonth is 11 then 0 else currentMonth + 1
-            lastMonth = if currentMonth is 0 then 11 else currentMonth - 1
-            prevMonthNumberDays = self.getDaysInMonth lastMonth, currentYear
-            calendar = null
-            heading = null
-            weekdays = null
             weekInfo = self.getDatesInWeek currentMonth, currentDate, currentYear
             datesInWeek = weekInfo.datesInWeek
             weekNumber = self.getWeekNumber currentMonth, currentDate, currentYear
             weekClass = if weekNumber % 2 is 0 then 'even-week' else 'odd-week'
-
-            getDates = (datesInWeek, key) ->
-                dates = {}
-                # if its the first week of the month
-                if datesInWeek.length < self.daysPerWeek and datesInWeek[0] is 1
-                    if key is firstDay
-                        dates.date = 1
-                        dates.month = currentMonth
-                    else if key > firstDay
-                        dates.date = (key - firstDay) + 1
-                        dates.month = currentMonth
+            day = self.getDayOfWeek currentMonth, currentDate, currentYear
+
+            _highlightWeekends = ->
+                calendarInner = self.calendar.find "div.#{self.calendarInnerClass}"
+                weeks = calendarInner.find '.drm-week'
+                weekends = [0, 6]
+
+                $.each weeks, ->
+                    that = $ @
+                    $.each weekends, (key, value) ->
+                        weekend = that.find(".#{self.classes.date}[data-day=#{value}]").not ".#{self.classes.muted}, .#{self.classes.today}, .#{self.classes.holiday}"
+                        weekend.addClass self.classes.weekend
+
+            _highlightCurrentDay = ->
+                calendarInner = self.calendar.find "div.#{self.calendarInnerClass}"
+                month = calendarInner.data 'month'
+                year = calendarInner.data 'year'
+
+                if month is self.currentMonth and year is self.currentYear
+                    calendarInner.find(".drm-date[data-date=#{self.currentDate}]").addClass self.classes.today
+
+            _createMonthView = (currentMonth, currentYear) ->
+                _addWeekNumbers = ->
+                    weeks = self.calendar.find("div.#{self.calendarInnerClass}").find '.drm-week'
+
+                    $.each weeks, (key, value) ->
+                        that = $ value
+                        firstDateInWeek = that.find('.drm-date').first().data 'date'
+                        weekNumber = self.getWeekNumber currentMonth, firstDateInWeek, currentYear
+                        if weekNumber % 2 is 0 then that.addClass('even-week') else that.addClass('odd-week')
+                        that.attr 'data-week', weekNumber
+
+                # create html
+                weekdays = '

'
+                $.each self.days, (key, value) ->
+                    weekdays += "#{value}	"
+                weekdays += '

'
+
+                weeks = "
"
+                i = 1
+                currentDate = 1
+                l = 1
+                prevDays = (prevMonthNumberDays - dayShift) + 1
+                nextDates = 1
+
+                while i <= numberWeeks
+                    j = 1
+                    weeks += "
"
+                    # if we are in week 1 we need to shift to the correct day of the week
+                    if i is 1 and firstDay isnt 0
+                        # add cells for the previous month until we get to the first day
+                        while l <= dayShift
+                            weeks += "#{prevDays}	"
+                            prevDays += 1
+                            l += 1
+                            j += 1
+                        # start adding cells for the current month
+                        while j <= self.daysPerWeek
+                            weeks += "#{currentDate}	"
+                            j += 1
+                            currentDate += 1
+                    # if we are in the last week of the month we need to add blank cells for next month
+                    else if i is numberWeeks
+                        while j <= self.daysPerWeek
+                            # finish adding cells for the current month
+                            if currentDate <= numberDays
+                                weeks += "#{currentDate}	"
+                            # start adding cells for next month
+                            else
+                                weeks += "#{nextDates}	"
+                                nextDates += 1
+                            j += 1
+                            currentDate += 1
                     else
-                        dates.date = prevMonthNumberDays - (firstDay - (key + 1))
-                        dates.month = lastMonth
-                else if datesInWeek.length is self.daysPerWeek
-                    dates.date = datesInWeek[key]
-                    dates.month = currentMonth
-                # if its the last week of the month
-                else if datesInWeek.length < self.daysPerWeek and datesInWeek[0] isnt 1
-                    if key < datesInWeek.length
+                        # if we are in the middle of the month add cells for the current month
+                        while j <= self.daysPerWeek
+                            weeks += "#{currentDate}	"
+                            j += 1
+                            currentDate += 1
+                    weeks += '
'
+                    i += 1
+                weeks += '

'
+
+                calendar = $ '

',
+                    class: self.calendarInnerClass
+                    html: weekdays + weeks
+                    'data-month': currentMonth
+                    'data-year': currentYear
+
+                heading = $ '

',
+                    class: 'drm-calendar-header'
+                    text: "#{self.months[currentMonth]} #{currentYear}"
+
+                calendar.appendTo ".#{self.calendarClass}"
+                heading.prependTo ".#{self.calendarInnerClass}"
+
+                _highlightCurrentDay()
+                _highlightWeekends()
+                _addWeekNumbers()
+
+                $.each self.events, (key, value) ->
+                    self.addEventsToCalendar value
+
+                $('.drm-calendar-year-prev').text lastYear
+                $('.drm-calendar-year-next').text nextYear
+
+                $('.drm-calendar-month-prev').text self.months[lastMonth]
+                $('.drm-calendar-month-next').text self.months[nextMonth]
+
+                $('.drm-calendar-week-prev, .drm-calendar-week-next').hide()
+                $('.drm-calendar-date-prev, .drm-calendar-date-next').hide()
+
+            _createWeekView = (currentMonth, currentDate, currentYear) ->
+                _getDates = (datesInWeek, key) ->
+                    dates = {}
+                    # if its the first week of the month
+                    if datesInWeek.length < self.daysPerWeek and datesInWeek[0] is 1
+                        if key is firstDay
+                            dates.date = 1
+                            dates.month = currentMonth
+                        else if key > firstDay
+                            dates.date = (key - firstDay) + 1
+                            dates.month = currentMonth
+                        else
+                            dates.date = prevMonthNumberDays - (firstDay - (key + 1))
+                            dates.month = lastMonth
+                    else if datesInWeek.length is self.daysPerWeek
                         dates.date = datesInWeek[key]
                         dates.month = currentMonth
+                    # if its the last week of the month
+                    else if datesInWeek.length < self.daysPerWeek and datesInWeek[0] isnt 1
+                        if key < datesInWeek.length
+                            dates.date = datesInWeek[key]
+                            dates.month = currentMonth
+                        else
+                            dates.date = Math.abs (datesInWeek.length - (key + 1))
+                            dates.month = nextMonth
+                    dates
+
+                weekdaysHtml = "

	"
+                $.each self.days, (key, value) ->
+                    dates = _getDates datesInWeek, key
+                    weekdaysHtml += "#{value}
#{self.months[dates.month]} #{dates.date}	"
+                weekdaysHtml += '

'
+
+                weekHtml = "
"
+                $.each self.hours, (key, value) ->
+                    hour = value.name
+                    weekHtml += "
#{hour}	"
+                    $.each self.days, (key, value) ->
+                        dates = _getDates datesInWeek, key
+                        weekHtml += "	"
+                    weekHtml += '
'
+                weekHtml += '
'
+
+                weekView = $ '

',
+                    html: weekdaysHtml + weekHtml
+
+                calendar = $ '

',
+                    class: self.calendarInnerClass
+                    html: weekView
+                    'data-month': currentMonth
+                    'data-year': currentYear
+
+                weekDates = if datesInWeek.length > 1 then "#{datesInWeek[0]} - #{datesInWeek[datesInWeek.length - 1]}" else "#{datesInWeek[0]}"
+
+                heading = $ '

',
+                    class: 'drm-calendar-header'
+                    text: "#{self.months[currentMonth]} #{weekDates}: Week #{weekNumber} of #{currentYear}"
+
+                calendar.appendTo ".#{self.calendarClass}"
+                heading.prependTo "div.#{self.calendarInnerClass}"
+
+                $("div.#{self.calendarInnerClass}").find("tbody td[data-month=#{lastMonth}]").addClass(self.classes.muted).removeClass 'drm-date'
+                $("div.#{self.calendarInnerClass}").find("tbody td[data-month=#{nextMonth}]").addClass(self.classes.muted).removeClass 'drm-date'
+                _highlightCurrentDay()
+                _highlightWeekends()
+
+                $.each self.events, (key, value) ->
+                    self.addEventsToCalendar value
+
+                $('.drm-calendar-year-prev').text lastYear
+                $('.drm-calendar-year-next').text nextYear
+
+                $('.drm-calendar-month-prev').text self.months[lastMonth]
+                $('.drm-calendar-month-next').text self.months[nextMonth]
+
+                $('.drm-calendar-week-prev, .drm-calendar-week-next').show()
+                $('.drm-calendar-date-prev, .drm-calendar-date-next').hide()
+
+            _createDateView = (currentMonth, currentDate, currentYear) ->
+                dayListHtml = "
"
+                $.each self.hours, (key, value) ->
+                    hour = value.name
+                    dayListHtml += "
#{hour}
"
+                dayListHtml += '
'
+
+                calendar = $ '

',
+                    class: self.calendarInnerClass
+                    'data-month': currentMonth
+                    'data-year': currentYear
+                    html: dayListHtml
+
+                headingText =
+                    if currentMonth is self.currentMonth and currentDate is self.currentDate and currentYear is self.currentYear
+                        "Today, #{self.days[day]}, #{self.months[currentMonth]} #{currentDate} #{currentYear}"
                     else
-                        dates.date = Math.abs (datesInWeek.length - (key + 1))
-                        dates.month = nextMonth
-                dates
-
-            weekdaysHtml = "

	"
-            $.each self.days, (key, value) ->
-                dates = getDates datesInWeek, key
-                weekdaysHtml += "#{value}
#{self.months[dates.month]} #{dates.date}	"
-            weekdaysHtml += '

'
-
-            weekHtml = "
"
-            $.each self.hours, (key, value) ->
-                hour = value.name
-                weekHtml += "
#{hour}	"
-                $.each self.days, (key, value) ->
-                    dates = getDates datesInWeek, key
-                    weekHtml += "	"
-                weekHtml += '
'
-            weekHtml += '
'
-
-            weekView = $ '

',
-                html: weekdaysHtml + weekHtml
-
-            calendar = $ '

',
-                class: self.calendarInnerClass
-                html: weekView
-                'data-month': currentMonth
-                'data-year': currentYear
-
-            weekDates = if datesInWeek.length > 1 then "#{datesInWeek[0]} - #{datesInWeek[datesInWeek.length - 1]}" else "#{datesInWeek[0]}"
-
-            heading = $ '

',
-                class: 'drm-calendar-header'
-                text: "#{@months[currentMonth]} #{weekDates}: Week #{weekNumber} of #{currentYear}"
-
-            calendar.appendTo ".#{self.calendarClass}"
-            heading.prependTo "div.#{self.calendarInnerClass}"
-
-            $("div.#{self.calendarInnerClass}").find("tbody td[data-month=#{lastMonth}]").addClass(self.classes.muted).removeClass 'drm-date'
-            $("div.#{self.calendarInnerClass}").find("tbody td[data-month=#{nextMonth}]").addClass(self.classes.muted).removeClass 'drm-date'
-            self.highlightCurrentDay()
-            self.highlightWeekends()
-
-            $.each self.events, (key, value) ->
-                self.addEventsToCalendar value
-
-            $('.drm-calendar-year-prev').text lastYear
-            $('.drm-calendar-year-next').text nextYear
-
-            $('.drm-calendar-month-prev').text self.months[lastMonth]
-            $('.drm-calendar-month-next').text self.months[nextMonth]
-
-            $('.drm-calendar-week-prev, .drm-calendar-week-next').show()
-            $('.drm-calendar-date-prev, .drm-calendar-date-next').hide()
-
-        createDateView: (currentMonth, currentDate, currentYear) =>
-            self = @
-            self.calendarInnerClass = "drm-calendar-#{self.view}-view"
-            day = self.getDayOfWeek currentMonth, currentDate, currentYear
-            weekNumber = self.getWeekNumber currentMonth, currentDate, currentYear
-            weekClass = if weekNumber % 2 is 0 then 'even-week' else 'odd-week'
-            nextYear = currentYear + 1
-            lastYear = currentYear - 1
-            nextMonth = if currentMonth is 11 then 0 else currentMonth + 1
-            lastMonth = if currentMonth is 0 then 11 else currentMonth - 1
-
-            dayListHtml = "
"
-            $.each self.hours, (key, value) ->
-                hour = value.name
-                dayListHtml += "
#{hour}
"
-            dayListHtml += '
'
-
-            calendar = $ '

',
-                class: self.calendarInnerClass
-                'data-month': currentMonth
-                'data-year': currentYear
-                html: dayListHtml
-
-            headingText =
-                if currentMonth is self.currentMonth and currentDate is self.currentDate and currentYear is self.currentYear
-                    "Today, #{self.days[day]}, #{self.months[currentMonth]} #{currentDate} #{currentYear}"
-                else
-                    "#{self.days[day]}, #{self.months[currentMonth]} #{currentDate} #{currentYear}"
-
-            heading = $ '

',
-                class: 'drm-calendar-header'
-                text: headingText
-
-            calendar.appendTo ".#{self.calendarClass}"
-            heading.prependTo ".#{self.calendarInnerClass}"
-
-            $.each self.events, (key, value) ->
-                self.addEventsToCalendar value
-
-            $('.drm-calendar-year-prev').text lastYear
-            $('.drm-calendar-year-next').text nextYear
-
-            $('.drm-calendar-month-prev').text self.months[lastMonth]
-            $('.drm-calendar-month-next').text self.months[nextMonth]
-
-            $('.drm-calendar-week-prev, .drm-calendar-week-next').show()
-            $('.drm-calendar-date-prev, .drm-calendar-date-next').show()
-
-        createCalendar: (month, date, year) =>
-            self = @
+                        "#{self.days[day]}, #{self.months[currentMonth]} #{currentDate} #{currentYear}"
+
+                heading = $ '

',
+                    class: 'drm-calendar-header'
+                    text: headingText
+
+                calendar.appendTo ".#{self.calendarClass}"
+                heading.prependTo ".#{self.calendarInnerClass}"
+
+                $.each self.events, (key, value) ->
+                    self.addEventsToCalendar value
+
+                $('.drm-calendar-year-prev').text lastYear
+                $('.drm-calendar-year-next').text nextYear
+
+                $('.drm-calendar-month-prev').text self.months[lastMonth]
+                $('.drm-calendar-month-next').text self.months[nextMonth]
+
+                $('.drm-calendar-week-prev, .drm-calendar-week-next').show()
+                $('.drm-calendar-date-prev, .drm-calendar-date-next').show()

             switch self.view
-                when 'month' then self.createMonthView month, year
-                when 'week' then self.createWeekView month, date, year
-                when 'date' then self.createDateView month, date, year
+                when 'month' then _createMonthView currentMonth, currentYear
+                when 'week' then _createWeekView currentMonth, currentDate, currentYear
+                when 'date' then _createDateView currentMonth, currentDate, currentYear

     drmCalendar = new DrmCalendar()
     drmCalendar.createEvent


Removing dummy console.log's

Removing dummy console.log's

--- app/coffee/modules/common/components.coffee
+++ app/coffee/modules/common/components.coffee
@@ -93,8 +93,6 @@

         if $attrs.greaterThan
             $scope.$watch $attrs.greaterThan, (val) ->
-                console.log "HOLA"
-                console.log val
                 $el.picker.setMinDate(moment(val))

         if $attrs.lessThan


feat(web): сheck messages to an empty string before send;

--- apps/actor-web/app/services/actorService.coffee
+++ apps/actor-web/app/services/actorService.coffee
@@ -107,7 +107,6 @@
           @$rootScope.$broadcast 'actorAuthCode'
     , (tag, message, canTryAgain, state) ->
       console.log '[AW]ActorService requestSms: error: state:', state
-
   sendCode: (code) ->
     console.log '[AW]ActorService sendCode'
     @messenger.sendCode code, (state) =>
@@ -121,12 +120,14 @@
       console.log '[AW]ActorService sendCode: error: state:', state

-
   sendMessage: (peer, message) ->
     console.log '[AW]ActorService sendMessage'
-    # console.log '[AW]ActorService sendMessage: message:', message
+    console.log '[AW]ActorService sendMessage: message:', message
+    message = message.replace /^\s+|\s+$/g, ''
+    if message.length > 0
+      console.log '[AW]ActorService sendMessage: message:', message.length
     # console.log '[AW]ActorService sendMessage: peer:', peer
-    @messenger.sendMessage peer, message
+      @messenger.sendMessage peer, message

   # Events


Pull over latest /i18n fixes from Ozaria

--- app/views/i18n/I18NEditComponentView.coffee
+++ app/views/i18n/I18NEditComponentView.coffee
@@ -18,9 +18,14 @@
         @wrapRow "#{propDoc.name} name value", ['name'], propDoc.name, i18n[lang]?.name, path
         if _.isObject propDoc.description
           for progLang, description of propDoc.description
-            @wrapRow "#{propDoc.name} description (#{progLang})", ['description', progLang], description, i18n[lang]?[progLang]?.description, path, 'markdown'
+            @wrapRow "#{propDoc.name} description (#{progLang})", ['description', progLang], description, i18n[lang]?.description?[progLang], path, 'markdown'
         else if _.isString propDoc.description
           @wrapRow "#{propDoc.name} description", ['description'], propDoc.description, i18n[lang]?.description, path, 'markdown'
+        if _.isObject propDoc.shortDescription
+          for progLang, shortDescription of propDoc.shortDescription
+            @wrapRow "#{propDoc.name} shortDescription (#{progLang})", ['shortDescription', progLang], shortDescription, i18n[lang]?.shortDescription?[progLang], path, 'markdown'
+        else if _.isString propDoc.shortDescription
+          @wrapRow "#{propDoc.name} shortDescription", ['shortDescription'], propDoc.shortDescription, i18n[lang]?.shortDescription, path, 'markdown'
         if context = propDoc.context
           for key, value of context
             @wrapRow "#{propDoc.name} context value", ['context', key], value, i18n[lang]?.context?[key], path
@@ -31,7 +36,7 @@
         d = propDoc.returns.description
         if _.isObject d
           for progLang, description of d.description
-            @wrapRow "#{propDoc.name} return val (#{progLang})", ['description', progLang], description, i18n[lang]?[progLang]?.description, path, 'markdown'
+            @wrapRow "#{propDoc.name} return val (#{progLang})", ['description', progLang], description, i18n[lang].description?[progLang], path, 'markdown'
         else if _.isString d
           @wrapRow "#{propDoc.name} return val", ['description'], d, i18n[lang]?.description, path, 'markdown'

@@ -42,7 +47,7 @@
             path = ['propertyDocumentation', propDocIndex, 'args', argIndex]
             if _.isObject argDoc.description
               for progLang, description of argDoc.description
-                @wrapRow "#{propDoc.name} arg description #{argDoc.name} (#{progLang})", ['description', progLang], description, i18n[lang]?[progLang]?.description, path, 'markdown'
+                @wrapRow "#{propDoc.name} arg description #{argDoc.name} (#{progLang})", ['description', progLang], description, i18n[lang]?.description?[progLang], path, 'markdown'
             else if _.isString argDoc.description
               @wrapRow "#{propDoc.name} arg description #{argDoc.name}", ['description'], argDoc.description, i18n[lang]?.description, path, 'markdown'


Blur previously focused entry after new search

--- assets/javascripts/views/sidebar/results.coffee
+++ assets/javascripts/views/sidebar/results.coffee
@@ -22,6 +22,7 @@
     return

   onResults: (entries, flags) =>
+    @listFocus?.blur() if flags.initialResults
     @empty() if flags.initialResults
     @append @tmpl('sidebarResult', entries)


Fixed validation.

Fixed validation.

--- app/assets/javascripts/app/models/channel.js.coffee
+++ app/assets/javascripts/app/models/channel.js.coffee
@@ -6,10 +6,10 @@

   @configure_attributes = [
     { name: 'adapter',            display: 'Type',     tag: 'select',   multiple: false, null: false, options: { IMAP: 'IMAP', POP3: 'POP3' } },
-    { name: 'options::host',      display: 'Host',     tag: 'input',    type: 'text', limit: 120, null: false, autocapitalize: false },
-    { name: 'options::user',      display: 'User',     tag: 'input',    type: 'text', limit: 120, null: false, autocapitalize: false },
-    { name: 'options::password',  display: 'Password', tag: 'input',    type: 'password', limit: 120, null: false, autocapitalize: false },
-    { name: 'options::ssl',       display: 'SSL',      tag: 'select',   multiple: false, null: false, options: { true: 'yes', false: 'no' }, translate: true, default: true},
+    { name: 'options::host',      display: 'Host',     tag: 'input',    type: 'text', limit: 120, null: true, autocapitalize: false },
+    { name: 'options::user',      display: 'User',     tag: 'input',    type: 'text', limit: 120, null: true, autocapitalize: false },
+    { name: 'options::password',  display: 'Password', tag: 'input',    type: 'password', limit: 120, null: true, autocapitalize: false },
+    { name: 'options::ssl',       display: 'SSL',      tag: 'select',   multiple: false, null: true, options: { true: 'yes', false: 'no' }, translate: true, default: true},
     { name: 'options::folder',    display: 'Folder',   tag: 'input',    type: 'text', limit: 120, null: true, autocapitalize: false },
     { name: 'group_id',           display: 'Group',    tag: 'select',   multiple: false, null: false, nulloption: true, relation: 'Group'  },
     { name: 'active',             display: 'Active',   tag: 'select',   multiple: false, null: false, options: { true: 'yes', false: 'no' }, translate: true, default: true },


minor fixes

minor fixes

--- client/landing/app/Applications/Environments.kdapplication/Controllers/FirewallActionListController.coffee
+++ client/landing/app/Applications/Environments.kdapplication/Controllers/FirewallActionListController.coffee
@@ -1,7 +0,0 @@
-class FirewallActionListController extends KDListViewController
-
-  constructor:(options={}, data)->
-    options.itemClass = FirewallActionListItemView
-    super options, data
-
-    @getListView().on "moveToIndexRequested", @bound 'moveItemToIndex'


Scale adjustments

Scale adjustments

--- app/assets/javascripts/roofpig/DomHandler.js.coffee
+++ app/assets/javascripts/roofpig/DomHandler.js.coffee
@@ -9,12 +9,12 @@
     @div.append(renderer.domElement);

     @scale = @div.width()/400
-    @hscale = Math.max(@scale, 22.0/40) # Below 22 pixels, Safari renders buttons with rounded corners. Chrome:21. Firefox:27.
+    @hscale = Math.max(@scale, 15.0/40) # Minimum height -> readable text

   has_focus: (has_it) ->
     color = if has_it then 'gray' else '#eee'
     cursor = if has_it then 'pointer' else 'default'
-    @div.css("border": "2px solid #{color}", cursor: cursor)
+    @div.css(border: "2px solid #{color}", cursor: cursor)

   alg_changed: (playing, at_start, at_end, place_text, alg_texts) ->
     if playing
@@ -52,11 +52,12 @@
     @div.append(@alg_area)

     if showalg
-      @alg_area.append(
-        @alg_text = $("<div/>").width(@div.width()).css('background-color': "#eef", 'margin-bottom': '2px'))
-      @alg_text.append(
-        @alg_past = $("<span/>").css(color: '#888'),
-        @alg_future = $("<span/>"))
+      @alg_text = $("<div/>").width(@div.width()).css('background-color': "#eef", 'margin-bottom': '2px')
+      @alg_area.append(@alg_text)
+
+      @alg_past = $("<span/>").css(color: '#888')
+      @alg_future = $("<span/>")
+      @alg_text.append(@alg_past, @alg_future)

     @reset = this._make_button("↩", "reset")
     @prev  = this._make_button("-", "prev")
@@ -87,10 +88,9 @@
     @alg_area.append(button)

     button.addClass('roofpig-button')
-    button.css('font-size': 28*@hscale, float: 'left')
-    button.height(40*@hscale).width(76*@scale)
+    button.css('font-size': 28*@hscale, float: 'left', height: 40*@hscale, width: 76*@scale)

   _make_place_area: ->
     place_div = $("<div/>", { id: 'place' }).css('text-align': 'right', float: 'right')
     @alg_area.append(place_div)
-    place_div.height(40*@scale).width(80*@scale).css("font-size", 24*@scale)
+    place_div.height(40*@hscale).width(80*@scale).css("font-size", 24*@hscale)


idioms

idioms

--- app/assets/javascripts/routes/index_route.js.coffee
+++ app/assets/javascripts/routes/index_route.js.coffee
@@ -7,8 +7,8 @@
     controller.set('model', model)
     papers = @store.filter 'litePaper', (p) ->
       roles = p.get('roles')
-      isMyPaper = roles.indexOf('My Paper') > -1
-      iAmCollaborator = roles.indexOf('Collaborator') > -1
+      isMyPaper = roles.contains('My Paper')
+      iAmCollaborator = roles.contains('Collaborator')
       isMyPaper || iAmCollaborator

     controller.set('papers', papers)


Silly line feeds

Silly line feeds

--- app/assets/javascripts/task/output_stream.js.coffee
+++ app/assets/javascripts/task/output_stream.js.coffee
@@ -8,10 +8,10 @@
     @_text ||= AnsiStream.strip(@raw)

   rawLines: ->
-    @_rawLines ||= @raw.split('\n')
+    @_rawLines ||= @raw.split(/\r?\n/)

   lines: ->
-    @_lines ||= @text().split('\n')
+    @_lines ||= @text().split(/\r?\n/)

 class Stream
   INTERVAL = 1000


MachineSettingsView: fix naming conflict with label

--- client/Main/providers/machinesettingsview.coffee
+++ client/Main/providers/machinesettingsview.coffee
@@ -166,10 +166,10 @@
           itemClass    : KDCustomHTMLView

     {advancedView, domains} = @moreForm.inputs
-    {label} = advancedView.getOptions()
-
-    label.on 'click', =>
-      label.toggleClass 'expanded'
+    advancedLabel = advancedView.getOption 'label'
+
+    advancedLabel.on 'click', =>
+      advancedLabel.toggleClass 'expanded'
       @buttonContainer.toggleClass 'hidden'

     {label} = domains.getOptions()


swap code and amount

swap code and amount

--- client/skr/screens/expense-entry/Categories.cjsx
+++ client/skr/screens/expense-entry/Categories.cjsx
@@ -5,7 +5,7 @@
     render: ->
         code = @props.categories.get(@category.category_id).code
         <span className='pair'>
-            {code} {Lanes.u.format.currency(@category.amount)}
+            {Lanes.u.format.currency(@category.amount)} {code}
         </span>


Correção validação saldo de conta.

Correção validação saldo de conta.

--- Operador-Deposito/server/lib/validations.coffee
+++ Operador-Deposito/server/lib/validations.coffee
@@ -87,7 +87,7 @@
 			throw new Meteor.Error "Conta não encontrada"

 		saldo = record.saldo
-		if valor <= valor
+		if saldo <= valor
 			throw new Meteor.Error 'Conta não possui saldo suficiente'

 		return saldo


Fixed rendering visibility check causing Issue #58

--- public/scripts/backbone-schedule/views/result-section.coffee
+++ public/scripts/backbone-schedule/views/result-section.coffee
@@ -11,7 +11,7 @@
       _.bindAll @

       Shark.schedule.bind "change", =>
-        @render();
+        @render()

       @resultsSectionTemplate = _.template(resultsSectionTemplate)

@@ -64,6 +64,7 @@
         hours: @model.get('credits')

       @$el.html @resultsSectionTemplate(params)
+      @$el.hide() if not @model.get 'visible'
       @$addButton = @$el.find('.add')
       # Color/bold the correct day letters
       _.each @model.get('timeslots'), (timeslot) =>


Removed console logging for click event

Removed console logging for click event

--- js/foundation/eventmanager/eventmanager.coffee
+++ js/foundation/eventmanager/eventmanager.coffee
@@ -954,7 +954,6 @@
   # It's different from mouseUp/mouseDown, because it's a different event,
   # and is supported by touch screen devices
   click: (e)->
-    console.log( "click" )
     @_modifiers(e)
     _leftClick = Event.isLeftClick(e)
     if _leftClick


fix test - for real this time

fix test - for real this time

--- apps/fair_info/test/templates/events.coffee
+++ apps/fair_info/test/templates/events.coffee
@@ -24,7 +24,7 @@

     it 'should render event date and time', ->
       @html.should.containEql 'Saturday, March 8'
-      @html.should.containEql '12:15-12:30PM'
+      @html.should.containEql '5:15-5:30PM'

     it 'should render event details', ->
       @html.should.containEql 'Welcome'


Ram usage bar: Minor fix about KD.utils.curryCssClass's usage

--- components/progressbar/KDProgressBarView.coffee
+++ components/progressbar/KDProgressBarView.coffee
@@ -1,6 +1,6 @@
 class KDProgressBarView extends KDCustomHTMLView
   constructor:(options = {})->
-    options.cssClass = KD.utils.curryCssClass "progressbar-container"
+    options.cssClass = KD.utils.curryCssClass "progressbar-container", options.cssClass

     super options


enhance tooltips for nested fields

enhance tooltips for nested fields

--- app/assets/javascripts/admin/tooltips.js.coffee
+++ app/assets/javascripts/admin/tooltips.js.coffee
@@ -1,5 +1,8 @@
-applyTooltips = ->
-  $(".bs-tooltip").tooltip()
+applyTooltips = ($scope) ->
+  $scope.find(".bs-tooltip").tooltip()

-$(document).on "ready page:load nested:fieldAdded",
-               applyTooltips
+$(document).on "ready page:load", ->
+  applyTooltips $("body")
+
+$(document).on "nested:fieldAdded", (e) ->
+  applyTooltips e.field


Fix Iceberg.js.coffee code because it was completely unusable

--- app/assets/javascripts/cocoon/iceberg.js.coffee
+++ app/assets/javascripts/cocoon/iceberg.js.coffee
@@ -3,33 +3,39 @@

   class Iceberg
     constructor: (@line) ->
+      # console.log 'this', this
       @display = @line.find('.item-display')

-      bindButtons(newForm)
+      @_bindButtons(@newForm())

-      @line.find('[data-edit="item-form"]').click ->
+      @line.find('*[data-edit="item-form"]').click =>
         @display.addClass('hidden')

-        clone = oldForm.clone()
-        clone.insertAfter(oldForm)
+        clone = @oldForm().clone()
+        clone.insertAfter(@oldForm())
+        clone.trigger('cocoon:after-insert')
         clone.removeClass('hidden')
-        bindButtons(newForm)
+        @_bindButtons(@newForm())

-    bindButtons: (form) ->
+    _bindButtons: (form) ->
+      # console.log '_bindButtons:this', this
+      that = this
       $(form).find('button[data-validate="item-form"]').each ->
         $(this).click (event) ->
-          validate
+          that.validate()
           event.preventDefault()

       $(form).find('button[data-cancel="item-form"]').each ->
         $(this).click (event) ->
-          cancel
+          that.cancel()
           event.preventDefault()

     validate: ->
+      # console.log 'validate:this', this
+      that = this
       @display.find('*[data-item-value]').each ->
         element = $(this)
-        target = $(newForm).find(element.data("item-value")).first()
+        target = $(that.newForm()).find(element.data("item-value")).first()
         if target.is("input")
           value = target.val()
         else
@@ -37,20 +43,23 @@
         element.html(value)

       @display.removeClass('hidden')
-      oldForm.remove()
-      newForm.addClass('hidden')
+      @oldForm().remove()
+      @newForm().addClass('hidden')

     cancel: ->
+      # console.log 'cancel:this', this
       @display.removeClass('hidden')
-      newForm.remove()
+      @newForm().remove()

     oldForm: ->
+      # console.log 'oldForm:this', this
       @line.find('.nested-item-form:hidden')

     newForm: ->
+      # console.log 'newForm:this', this
       @line.find('.nested-item-form:visible')

   $(document).ready ->
     $('table.list').on 'cocoon:after-insert', (event, inserted) ->
-      iceberg = Iceberg.new($(inserted))
+      new Iceberg($(inserted))
 ) jQuery


test_properties.coffee: remove tests for foo_units attribute

This attribute is no longer supported.

--- bokehjs/test/test_common/test_properties.coffee
+++ bokehjs/test/test_common/test_properties.coffee
@@ -122,12 +122,8 @@
     it "should be an instance of Numeric", ->
       expect(Properties.Angle.prototype).to.be.instanceof Properties.Numeric

-    it "should prefer to set units from a spec if possible", ->
-      prop = new Properties.Angle({obj: generate_obj({a: {value: 1, units: "deg"}, a_units: "rad"}), attr: 'a'})
-      expect(prop.units).to.be.equal "deg"
-
-    it "should otherwise set units from the object if possible", ->
-      prop = new Properties.Angle({obj: generate_obj({a: 1, a_units: "deg"}), attr: 'a'})
+    it "should set units from a spec", ->
+      prop = new Properties.Angle({obj: generate_obj({a: {value: 1, units: "deg"} }), attr: 'a'})
       expect(prop.units).to.be.equal "deg"

     it "should set units to 'rad' as a default", ->
@@ -142,11 +138,11 @@
     describe "transform", ->

       it "should convert degrees to radians and flip sign", ->
-        prop = new Properties.Angle({obj: generate_obj({a: 1, a_units: "deg"}), attr: 'a'})
+        prop = new Properties.Angle({obj: generate_obj({a: { value: 1, units: "deg"} }), attr: 'a'})
         expect(prop.transform [1, 2, 3]).to.be.deep.equal new Float64Array [-Math.PI/180.0, -2*Math.PI/180.0, -3*Math.PI/180.0]

       it "should pass radians with sign flipped", ->
-        prop = new Properties.Angle({obj: generate_obj({a: 1, a_units: "rad"}), attr: 'a'})
+        prop = new Properties.Angle({obj: generate_obj({a: { value: 1, units: "rad" } }), attr: 'a'})
         expect(prop.transform [1, 2, 3]).to.be.deep.equal new Float64Array [-1, -2, -3]

@@ -155,13 +151,9 @@
     it "should be an instance of Numeric", ->
       expect(Properties.Distance.prototype).to.be.instanceof Properties.Numeric

-    it "should prefer to set units from a spec if possible", ->
-      prop = new Properties.Distance({obj: generate_obj({a: {value: 1, units: "screen"}, a_units: "data"}), attr: 'a'})
+    it "should set units from a spec", ->
+      prop = new Properties.Distance({obj: generate_obj({a: {value: 1, units: "screen"} }), attr: 'a'})
       expect(prop.units).to.be.equal "screen"
-
-    it "should otherwise set units from the object if possible", ->
-      prop = new Properties.Distance({obj: generate_obj({a: 1, a_units: "data"}), attr: 'a'})
-      expect(prop.units).to.be.equal "data"

     it "should set units to 'data' as a default", ->
       prop = new Properties.Distance({obj: generate_obj({a: 1}), attr: 'a'})


Cannot use "indexOf" with a string.

Cannot use "indexOf" with a string.

--- app/assets/javascripts/lib/models/metric.coffee
+++ app/assets/javascripts/lib/models/metric.coffee
@@ -113,7 +113,7 @@
     rounded = @round_number(value, 1).toString()
     # If the number is < 1000, and has decimal places, make sure that the
     # number isn't truncated to something like 5.4, but instead returns 5.40.
-    if (abs_value < 1000 && _.indexOf(rounded, '.') != -1)
+    if abs_value < 1000 && rounded.match(/\./)
       rounded = rounded.split('.')
       if (rounded[1] && rounded[1].length == 1)
         rounded[1] += '0'


operations: NewModeratorNotify must cb()

--- src/local/operations.coffee
+++ src/local/operations.coffee
@@ -1244,6 +1244,9 @@
         , (cb2) =>
             t.getOutcast @req.node, cb2
         ], (err, [pendingUsers, bannedUsers]) =>
+            if err
+                return cb err
+
             notification = []
             notification.node = @req.node
             notification.listener = @actor
@@ -1260,6 +1263,8 @@
                     user: user
                     affiliation: 'outcast'
             @router.notify notification
+
+            cb()

 OPERATIONS =


remove debugging info

remove debugging info

--- src/components/500.coffee
+++ src/components/500.coffee
@@ -12,6 +12,3 @@
         JSON.stringify (@props.error ? {}), null, 2
       DOM.pre null,
         JSON.stringify (@props.stack ? {}), null, 2
-      if @props.sessionStuff
-        DOM.pre null,
-          JSON.stringify @props.sessionStuff, null, 2


Configure jEditable to not add "Click to edit" on blank cells.

--- app/assets/javascripts/editable.js.coffee
+++ app/assets/javascripts/editable.js.coffee
@@ -9,7 +9,7 @@
     # TODO: We should handle failures and timeouts in POSTing, and make our own "Saving..." indicator.
     $.post($span.data('url'), data)
     value
-  , tooltip: 'Click to edit'
+  , tooltip: 'Click to edit', placeholder: ''

   $('table.editable td').editable (value, settings) ->
     $td = $(this)
@@ -18,6 +18,6 @@
     # TODO: We should handle failures and timeouts in POSTing, and make our own "Saving..." indicator.
     $.post($tr.data('url'), data, null, 'json')
     value
-  , onblur: 'submit'
+  , onblur: 'submit', placeholder: ''

 window.enableEditables = enableEditables


Update notification's descriptions

Update notification's descriptions

--- lib/connection/client.coffee
+++ lib/connection/client.coffee
@@ -175,7 +175,7 @@
   connectedError: (action = 'do that') ->
     if @isActive()
       atom.notifications.addError "Can't #{action} with a Julia client running.",
-        description: "Stop the current client with Packages → Julia → Stop Julia."
+        description: "Stop the current client with `Packages -> Julia -> Stop Julia`."
       true
     else
       false
@@ -183,7 +183,7 @@
   notConnectedError: (action = 'do that') ->
     if not @isActive()
       atom.notifications.addError "Can't #{action} without a Julia client running.",
-        description: "Start Julia using **`Julia-Client: Start-Julia`** command."
+        description: "Start a client with `Packages -> Julia -> Start Julia`."
       true
     else
       false


fix new issue from previous fix

fix new issue from previous fix

--- src/main/coffee/main.coffee
+++ src/main/coffee/main.coffee
@@ -248,7 +248,7 @@
                 objSelf.scrollDisabled = false
                 $(window).scroll(objSelf._onScrollFn)
             $('html, body').animate({
-                scrollTop: newArticleOffset.top - $("#top-nav-bar").height() - $("#top-nav-bar").offset().top
+                scrollTop: newArticleOffset.top - $("#top-nav-bar").height() - 5
             }, 500, "swing", () -> setTimeout(doneFn, 0))
             e.preventDefault()

@@ -312,7 +312,7 @@
                objSelf.scrollDisabled = false
                $(window).scroll(objSelf._onScrollFn)
            $('html, body').animate({
-                scrollTop: newArticleOffset.top - $("#top-nav-bar").height() - $("#top-nav-bar").offset().top
+                scrollTop: newArticleOffset.top - $("#top-nav-bar").height() - 5
            }, 500, "swing", () -> setTimeout(doneFn, 0))

     _initializeKeyboardNavigation: ->


abstract ticker needs to handle cases where range values are bad because data is not loaded yet

--- bokehjs/src/coffee/ticking/abstract_ticker.coffee
+++ bokehjs/src/coffee/ticking/abstract_ticker.coffee
@@ -3,6 +3,32 @@
   "backbone",
   "common/has_properties",
 ], (_, Backbone, HasProperties) ->
+
+  # A hacky analogue to repr() in Python.
+  repr = (obj) ->
+    if obj == null
+      return "null"
+
+    else if obj.constructor == Array
+      elems_str = (repr(elem) for elem in obj).join(", ")
+      return "[#{elems_str}]"
+
+    else if obj.constructor == Object
+      props_str = ("#{key}: #{repr(obj[key])}" for key of obj).join(", ")
+      return "{#{props_str}}"
+
+    else if obj.constructor == String
+      return "\"#{obj}\""
+
+    else if obj.constructor == Function
+      return "<Function: #{obj.name}>"
+
+    else
+      obj_as_string = obj.toString()
+      if obj_as_string == "[object Object]"
+        return "<#{obj.constructor.name}>"
+      else
+        return obj_as_string

   # A hacky analogue to repr() in Python.
   repr = (obj) ->
@@ -66,7 +92,10 @@
       interval = @get_interval(data_low, data_high, desired_n_ticks)
       start_factor = Math.floor(data_low / interval)
       end_factor   = Math.ceil(data_high / interval)
-      factors = _.range(start_factor, end_factor + 1)
+      if _.isNaN(start_factor) or _.isNaN(end_factor)
+        factors = []
+      else
+        factors = _.range(start_factor, end_factor + 1)
       ticks = (factor * interval for factor in factors)
       return ticks


update cursor

update cursor

--- src/main/coffeescript/nz/SpriteBattleMap.coffee
+++ src/main/coffeescript/nz/SpriteBattleMap.coffee
@@ -100,19 +100,15 @@
     return res

   _createCursor: ->
-    cursor = phina.display.Shape(
-      x:           0
-      y:           0
-      width:       MAP_CHIP_W
-      height:      MAP_CHIP_H
-      strokeStyle: 'red'
-      lineWidth:   3
-      visible:     true
-    )
-    cursor._render = ->
-      @_renderBackground()
-      @canvas.strokeRect(0, 0, @width, @height)
-    return cursor
+    phina.display.RectangleShape
+      width:        MAP_CHIP_W
+      height:       MAP_CHIP_H
+      stroke:       'red'
+      strokeWidth:  3
+      visible:      true
+      cornerRadius: 5
+      fill:         null
+      backgroundColor: 'transparent'

   # MapChip用イベントハンドラ
   _dispatchMapChipEvent: (_e) ->


Added verbose to installing packages

Added verbose to installing packages

--- build/tasks/install-unpublished-packages.coffee
+++ build/tasks/install-unpublished-packages.coffee
@@ -18,6 +18,7 @@
     decompress.use(Decompress.targz({ strip: 1 }))
     decompress.run (error) ->
       if error
+        console.log 'Error while decompressing archive:', error
         throw error

       fs.unlinkSync tarballPath
@@ -33,6 +34,8 @@
         cwd: path.join(workDir, 'node_modules', name)
       cp.safeExec 'npm install', options, ->
         callback()
+  r.on 'error', (err) ->
+    console.log 'Error while fetching package:', err

   r.pipe(fs.createWriteStream(tarballPath))


Refactor js event.

Refactor js event.

--- app/assets/javascripts/undersky.js.coffee
+++ app/assets/javascripts/undersky.js.coffee
@@ -131,8 +131,8 @@
     do ->
       $d.on 'click', '.media-grid.photos a', self.toggle
       $d.on 'click', '.modal.media-panel .close', self.close
-      $d.keydown self.action
-      $w.resize self.resize
+      $d.on 'keydown', self.action
+      $w.on 'resize', self.resize

   class Likes
     self = this
@@ -201,7 +201,7 @@
       $('.likes-button a').bindAjaxHandler self.likesStatusHandler
       $('.likes-button.like a').bindAjaxHandler self.likeHandler
       $('.likes-button.unlike a').bindAjaxHandler self.unlikeHandler
-      $d.keydown self.action
+      $d.on 'keydown', self.action

   class Comments
     self = this
@@ -346,13 +346,13 @@
         panel.find('.comments-button.create-comment a').click()

       do ->
-        $d.delegate '.comments-button.create-comment a', 'click', self.show
-        $d.delegate '.modal.create-comment .username a', 'click', self.reply
-        $d.delegate '.modal.create-comment a.tag', 'click', self.tag
-        $d.delegate '.modal.create-comment [name="text"]', 'keyup change', self.validate
-        $d.delegate '.modal.create-comment [name="cancel"]', 'click', self.hide
         $('.modal.create-comment form').bindAjaxHandler self.handler
-        $d.keydown self.action
+        $d.on 'click', '.comments-button.create-comment a', self.show
+        $d.on 'click', '.modal.create-comment .username a', self.reply
+        $d.on 'click', '.modal.create-comment a.tag', self.tag
+        $d.on 'keyup change', '.modal.create-comment [name="text"]', self.validate
+        $d.on 'click', '.modal.create-comment [name="cancel"]', self.hide
+        $d.on 'keydown', self.action

   class Relationships
     self = this
@@ -401,4 +401,4 @@

     do ->
       $('.page-button.next-page a').bindAjaxHandler self.nextPageHandler
-      $w.scroll self.loadNextPage
+      $w.on 'scroll', self.loadNextPage


Update Atom configurations

Update Atom configurations

--- .atom/config.cson
+++ .atom/config.cson
@@ -82,6 +82,7 @@
   "linter-eslint": {}
   refactor: {}
   "split-diff":
+    diffWords: true
     ignoreWhitespace: true
     leftEditorColor: "red"
     rightEditorColor: "green"
@@ -105,7 +106,7 @@
   wakatime:
     apikey: "Saved in your ~/.wakatime.cfg file"
   "wakatime-hidden":
-    lastInit: 1470117818
+    lastInit: 1470709073
   welcome:
     showOnStartup: false
 ".babel.regexp.source":


Update atom config

Update atom config

--- .atom/config.cson
+++ .atom/config.cson
@@ -14,6 +14,7 @@
       "one-light-syntax"
     ]
   editor:
+    fontFamily: "Fira Code"
     fontSize: 12
     invisibles: {}
     scrollPastEnd: true


lin/win differences

lin/win differences

--- lib/editor-background.coffee
+++ lib/editor-background.coffee
@@ -601,6 +601,9 @@
             if editorSetting.fontSize?
               fontSize = editorSetting.fontSize

+          if !/[0-9]+px$/.test(fontSize)
+            fontSize+='px'
+
           css = @elements.textBackgroundCss

           css.innerText="


removed commented out code

removed commented out code

--- src/middleware/stats.coffee
+++ src/middleware/stats.coffee
@@ -18,10 +18,6 @@
     sdc.increment domain + '.channels.' + transactionStatus #Overall Transaction Status
     sdc.increment domain + '.channels.' + ctx.authorisedChannel._id # Per channel
     sdc.increment domain + '.channels.' + ctx.authorisedChannel._id + '.statuses.' + transactionStatus # Per Channel Status
-
-    #Collect stats for non-primary routes
-#    if ctx.routes?
-#      for route in ctx.routes

     if ctx.mediatorResponse?
 #      Check for custom mediator metrics
@@ -71,7 +67,6 @@

   catch error
     logger.error error, done
-    console.log error
   done()

@@ -85,9 +80,6 @@
     sdc.timing domain + '.channels.' + ctx.authorisedChannel._id, ctx.timer # Per Channel
     sdc.timing domain + '.channels.' + ctx.authorisedChannel._id + '.statuses.' + transactionStatus, ctx.timer # Per Channel Status

-    #Collect stats for non-primary routes
-#    if ctx.routes?
-#      for route in ctx.routes

     if ctx.mediatorResponse?
       if ctx.mediatorResponse.orchestrations?
@@ -139,7 +131,7 @@
         sdc.increment domain + '.channels.' + ctx.authorisedChannel._id + '.nonPrimaryRoutes.' + route.name + '.statusCodes.' + route.response.status + '.orchestrations.' + orchestrationName
         sdc.increment domain + '.channels.' + ctx.authorisedChannel._id + '.nonPrimaryRoutes.' + route.name + '.statusCodes.' + route.response.status + '.orchestrations.' + orchestrationName + '.statusCodes.' + orchestrationStatus

-        #           Log custom orchestration metrics
+        # Log custom orchestration metrics
         if orchestration.metrics?
           for metric in orchestration.metrics
             if metric.type == 'counter'


Fix linting issues at the aggregate repository

--- src/aggregate_repository/aggregate_repository.coffee
+++ src/aggregate_repository/aggregate_repository.coffee
@@ -64,16 +64,16 @@
       domainEvents.forEach (domainEvent) =>
         saveDomainEventQueue = saveDomainEventQueue.then =>
           @_store.saveDomainEvent domainEvent
-        .then =>
-          logger.debug "Saved DomainEvent", domainEvent
+        .then ->
+          logger.debug 'Saved DomainEvent', domainEvent

       saveDomainEventQueue
       .then =>
         domainEvents.forEach (domainEvent) =>
-          logger.debug "Publishing DomainEvent", domainEvent
+          logger.debug 'Publishing DomainEvent', domainEvent
           @_context.getEventBus().publishDomainEvent domainEvent
-          .catch (error) =>
+          .catch (error) ->
             logger.error error.stack || error
       .then ->
         resolve aggregate.id


Fix gesture event velocity

Fix gesture event velocity

--- framer/GestureInputRecognizer.coffee
+++ framer/GestureInputRecognizer.coffee
@@ -337,7 +337,7 @@
 			event.deltaTime = event.time - @session.lastEvent.time

 		if @session?.events
-			events = _.filter @session.events, (e) -> e.time > (event.time - GestureInputVelocityTime)
+			events = _.filter @session.events, (e) -> e.time > (event.time - (GestureInputVelocityTime * 1000))
 			event.velocity = @_getVelocity(events)

 		if event.fingers > 0


Center labels; remove log statements

Center labels; remove log statements

--- src/d3-flame-graph.coffee
+++ src/d3-flame-graph.coffee
@@ -99,9 +99,10 @@
         .append('g')
           .attr('transform', "translate(#{@margin().left}, #{@margin().top})")

-
       @maxCells = Math.floor(@height() / @cellHeight())
       @maxDepth = @data()[0].maxDepth
+
+      @fontSize = (@cellHeight() / 10) * 0.4

       @x = d3.scale.linear()
         .domain([0, d3.max(@data(), (d) -> d.x + d.dx)])
@@ -127,10 +128,10 @@

       nodes.append('text')
         .attr('class', 'label')
-        .attr('dy', '.25em')
+        .attr('dy', "#{@fontSize / 2}em")
         .attr('x', (d) => @x(d.x) + 2)
         .attr('y', (d) => @y(d.y) + @cellHeight() / 2)
-        .style('font-size', "#{(@cellHeight() / 10) * 0.4}em")
+        .style('font-size', "#{@fontSize}em")
         .text((d) => @label(d) if d.name and @x(d.dx) > 40)
       # overlaying a transparent rectangle to capture events
       # TODO: maybe there's a smarter way to do this?
@@ -173,7 +174,6 @@

     _renderBreadcrumbs: () ->
       breadcrumbData = @_ancestors.map((ancestor, idx) ->
-        console.log(ancestor)
         { name: ancestor.name, value: idx })
       breadcrumbs = @container
         .selectAll('.ancestor')
@@ -193,10 +193,10 @@

       group.append('text')
         .attr('class', 'label')
-        .attr('dy', '.25em')
+        .attr('dy', '#{@fontSize / 2}em')
         .attr('x', (d) => 2)
         .attr('y', (d, idx) => @height() - ((idx + 1) * @cellHeight()) + @cellHeight() / 2)
-        .style('font-size', "#{(@cellHeight() / 10) * 0.4}em")
+        .style('font-size', "#{@fontSize}em")
         .text((d) => "↩ #{getClassAndMethodName(d.name)}")

       breadcrumbs.exit().remove()
@@ -211,7 +211,6 @@
       @container
         .selectAll('.ancestor')
         .on 'click', (d, idx) =>
-          console.log(d)
           d3.event.stopPropagation()
           @zoom(@_ancestors[idx])
       @


Add the tooltip plugin as a parameter to the flame graph

--- src/d3-flame-graph.coffee
+++ src/d3-flame-graph.coffee
@@ -93,6 +93,7 @@
         'zoomEnabled',
         'zoomAction',
         'tooltip',
+        'tooltipPlugin',
         'color'])
       @_ancestors = []

@@ -117,6 +118,7 @@
         "rgb(#{r}, #{g}, #{b})"
       @_tooltipEnabled = true
       @_zoomEnabled = true
+      @_tooltipPlugin = d3.tip()

       # initial processing of data
       @console.time('augment')
@@ -277,7 +279,7 @@
       @

     _renderTooltip: () ->
-      @tip = d3.tip()
+      @tip = @_tooltipPlugin
         .attr('class', 'd3-tip')
         .html(@tooltip())
         .direction (d) =>


resurrection: code cleanup

resurrection: code cleanup

--- client/Social/Activity/ListItems/ActivityListItemStatusUpdate.coffee
+++ client/Social/Activity/ListItems/ActivityListItemStatusUpdate.coffee
@@ -1,7 +1,5 @@
 class StatusActivityItemView extends ActivityItemChild
-
   constructor:(options = {}, data={})->
-
     options.cssClass or= "activity-item status"
     options.tooltip  or=
       title            : "Status Update"
@@ -15,7 +13,7 @@

       options.commentSettings = fixedHeight: 300

-    super options,data
+    super options, data

     @embedOptions = $.extend {}, options,
       hasDropdown : no
@@ -29,27 +27,18 @@

     @timeAgoView = new KDTimeAgoView {}, @getData().meta.createdAt

-  attachTooltipAndEmbedInteractivity:->
-    # @$("p.status-body > span.data > a").each (i,element)->
-    #   href = $(element).attr("data-original-url") or $(element).attr("href") or ""

-    #   twOptions = (title) ->
-    #      title : title, placement : "above", offset : 3, delayIn : 300, html : yes, animate : yes, className : "link-expander"

-    #   if $(element).attr("target") is "_blank"
-    #     $(element).twipsy twOptions("External Link : "+href+"")
-    #   element

   viewAppended:->
     return if @getData().constructor is KD.remote.api.CStatusActivity
-    super()
+    super
     @setTemplate @pistachio()
     @template.update()

     # load embed on next callstack
     @utils.defer =>
-
       # If there is embed data in the model, use that!
       if @getData().link?.link_url? and @getData().link.link_url isnt ''
         @embedBox.show()
@@ -66,8 +55,6 @@
       else
         @embedBox.hide()

-      @attachTooltipAndEmbedInteractivity()
-
   render:->
     super

@@ -83,42 +70,8 @@
           @embedBox.hide()  unless @embedBox.hasValidContent

       @embedBox.setActiveLink link.link_url
-
     else
       @embedBox = new KDView
-    @attachTooltipAndEmbedInteractivity()
-
-  click:(event)->
-
-    super
-
-    # if $(event.target).is("span.type-icon")
-    #   KD.getSingleton('router').handleRoute "/Activity/#{@getData().slug}", state:@getData()
-
-  applyTextExpansions:(str = "")->
-
-    # This code will remove single links from the text if they are located
-    # at the start or end of the line. However, since we defer the embed
-    # load, there is no way to be sure if the embed is there or not when
-    # shortening the link -> so i disabled it --arvid
-
-    # link = @getData().link?.link_url
-    # if link
-
-    #   links = str.match(/([a-zA-Z]+\:\/\/)?(\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(\/\S*)?/g)
-    #   if links?
-    #     hasManyLinks = links.length > 1
-    #   else
-    #     hasManyLinks = no
-
-    #   isJustOneLink = str.trim() is link
-    #   endsWithLink = str.trim().indexOf(link, str.trim().length - link.length) isnt -1
-    #   startsWithLink = str.trim().indexOf(link) is 0
-
-    #   if @embedBox.hasValidContent and not hasManyLinks and not isJustOneLink and (endsWithLink or startsWithLink)
-    #     str = str.replace link, ""
-
-    str = @utils.applyTextExpansions str, yes

   pistachio:->
     if @twoColumns
@@ -154,22 +107,3 @@
         {{> @commentBox}}
       """

-      # """
-      # {{> @settingsButton}}
-      # {{> @avatar}}
-      #

-      #

-      #
{{@applyTextExpansions #(body)}}

-      #   {{> @embedBox}}
-      #
-      #

-      #       {{> @contentGroupLink }} by {{> @author}}
-      #       {{> @timeAgoView}}
-      #       {{> @tags}}
-      #

-      #     {{> @actionLinks}}
-      #
-      #   {{> @commentBox}}
-      #

-      # """
-


Client: Activity: Test: Updated CreatePublicChannelModal component to use ChannelParticipantsDropdown instead of CreateChannelParticipantsDropdown component

--- client/activity/lib/components/createpublicchannelmodal/index.coffee
+++ client/activity/lib/components/createpublicchannelmodal/index.coffee
@@ -1,21 +1,21 @@
-kd                                = require 'kd'
-Link                              = require 'app/components/common/link'
-React                             = require 'kd-react'
-ReactDOM                          = require 'react-dom'
-Portal                            = require('react-portal').default
-Avatar                            = require 'app/components/profile/avatar'
-AppFlux                           = require 'app/flux'
-classnames                        = require 'classnames'
-KeyboardKeys                      = require 'app/constants/keyboardKeys'
-ActivityFlux                      = require 'activity/flux'
-ActivityModal                     = require 'app/components/activitymodal'
-KDReactorMixin                    = require 'app/flux/base/reactormixin'
-isPublicChannel                   = require 'app/util/isPublicChannel'
-DropboxInputMixin                 = require 'activity/components/dropbox/dropboxinputmixin'
-CreateChannelFlux                 = require 'activity/flux/createchannel'
-ProfileLinkContainer              = require 'app/components/profile/profilelinkcontainer'
-ChannelParticipantsDropdown       = require 'activity/components/channelparticipantsdropdown'
-CreateChannelParticipantsDropdown = require 'activity/components/createchannelparticipantsdropdown'
+kd                          = require 'kd'
+Link                        = require 'app/components/common/link'
+React                       = require 'kd-react'
+ReactDOM                    = require 'react-dom'
+Portal                      = require('react-portal').default
+Avatar                      = require 'app/components/profile/avatar'
+AppFlux                     = require 'app/flux'
+classnames                  = require 'classnames'
+KeyboardKeys                = require 'app/constants/keyboardKeys'
+ActivityFlux                = require 'activity/flux'
+ActivityModal               = require 'app/components/activitymodal'
+KDReactorMixin              = require 'app/flux/base/reactormixin'
+isPublicChannel             = require 'app/util/isPublicChannel'
+DropboxInputMixin           = require 'activity/components/dropbox/dropboxinputmixin'
+CreateChannelFlux           = require 'activity/flux/createchannel'
+ProfileLinkContainer        = require 'app/components/profile/profilelinkcontainer'
+ChannelParticipantsDropdown = require 'activity/components/channelparticipantsdropdown'
+DropdownItem                = require 'activity/components/createchannelparticipantsdropdownitem'

 module.exports = class CreatePublicChannelModal extends React.Component

@@ -304,15 +304,26 @@

   renderAddNewChannelParticipantsDropdown: ->

-    <CreateChannelParticipantsDropdown
-      ref             = 'dropdown'
-      query           = { @state.query }
-      value           = { @state.value }
-      visible         = { @state.dropdownVisibility }
-      items           = { @state.dropdownUsers }
-      selectedItem    = { @state.selectedItem }
-      selectedIndex   = { @state.selectedIndex }
-      onItemConfirmed = { @bound 'onDropdownItemConfirmed' }
+    { moveToPrevIndex
+      moveToNextIndex
+      setSelectedIndex
+      setDropdownVisibility } = CreateChannelFlux.actions.user
+
+    <ChannelParticipantsDropdown.Container
+      ref                  = 'dropdown'
+      query                = { @state.query }
+      value                = { @state.value }
+      moveToPrevAction     = { moveToPrevIndex }
+      moveToNextAction     = { moveToNextIndex }
+      onItemSelectedAction = { setSelectedIndex }
+      closeAction          = { setDropdownVisibility }
+      className            = 'CreateChannel-dropbox'
+      visible              = { @state.dropdownVisibility }
+      items                = { @state.dropdownUsers }
+      selectedItem         = { @state.selectedItem }
+      selectedIndex        = { @state.selectedIndex }
+      DropdownItem         = { DropdownItem }
+      onItemConfirmed      = { @bound 'onDropdownItemConfirmed' }
     />


Testpath

Testpath

--- client/app/Applications/Home.kdapplication/Views/homeloginbar.coffee
+++ client/app/Applications/Home.kdapplication/Views/homeloginbar.coffee
@@ -96,6 +96,7 @@
       title       : "Join Group"
       icon        : {}
       cssClass    : "join green hidden button"
+      testPath    : "groups-join-button"
       attributes  :
         href      : "#"
       click       : (event)=>


support sub-views; added support for dynamic selectors

--- manager/app/assets/javascripts/stark.js.coffee
+++ manager/app/assets/javascripts/stark.js.coffee
@@ -205,8 +205,7 @@
       if ! (_.any(new_state.views, (n)-> v instanceof n) && _.any(new_state.no_redraw, (n)-> v instanceof n))
         # only dispose of view IF NOT required by new state
         console.log "disposing of", v
-        v.$el.html("")
-        v.undelegateEvents()
+        v.dispose()

   bind_app_events: ->
     _.each @app_events, (cb, key) ->
@@ -220,6 +219,8 @@
   state: null
   template: null
   app_events: null
+  selector: null
+  views: [] # sub-views

   initialize: ->
     _.bindAll @
@@ -230,7 +231,19 @@
   render: ->
     console.log "rendering view", @
     @_template = new Template(JST[ @tpl_path() ])
-    $(@el).html(@_template.render(@))
+
+    # use an optional [dynamic] selector
+    el = null
+    if @selector?
+      if _.isFunction(@selector)
+        el = @selector()
+      else
+        el = el
+    else
+      el = @el
+
+    @setElement(el)
+    @$el.html(@_template.render(@))
     @

   # proxy for Stark.state#transition
@@ -241,3 +254,10 @@
     _.each @app_events, (cb, key) ->
       @app.subscribe(key, cb)
     , @
+
+  dispose: ->
+    @$el.html("")
+    @undelegateEvents()
+    for v in @views
+      v.dispose()
+


Social: set entryPoint

Social: set entryPoint

--- workers/social/lib/social/render/loggedin/kodinghome.coffee
+++ workers/social/lib/social/render/loggedin/kodinghome.coffee
@@ -6,6 +6,7 @@
   getSidebar      = require './sidebar'
   getStatusWidget = require './statuswidget'

+  options.entryPoint = { slug : "koding", type: "group" }

   prepareHTML = (scripts)->
     """


Remove batch action initializer

Remove batch action initializer

This doesn’t add any behavior, only modifies appearance for an extreme
case. No actual functionality is broken because of this and the
presentation part is dealt in #3862 as CSS where it should be.

--- app/assets/javascripts/active_admin/initializers/batch_actions.js.coffee
+++ app/assets/javascripts/active_admin/initializers/batch_actions.js.coffee
@@ -1,11 +0,0 @@
-onDOMReady = ->
-  # In order for index scopes to overflow properly onto the next line, we have
-  # to manually set its width based on the width of the batch action button.
-  if (batch_actions_selector = $('.table_tools .batch_actions_selector')).length
-    batch_actions_selector.next().css
-      width: "calc(100% - 10px - #{batch_actions_selector.outerWidth()}px)"
-      'float': 'right'
-
-$(document).
-  ready(onDOMReady).
-  on 'page:load turbolinks:load', onDOMReady


fixes #2182 (redmine)

fixes #2182 (redmine)

--- app/assets/javascripts/modules/blaze/services/entities_service.js.coffee
+++ app/assets/javascripts/modules/blaze/services/entities_service.js.coffee
@@ -62,13 +62,17 @@
         )

       media_relation_load: (entity_id, relation_name, page) ->
+        page ||= 1
+
+        kind_id = if kd.info then kd.info.medium_kind_id else 1
+
         http(
           method: 'get'
           url: "/entities/#{entity_id}/relationships.json"
           params: {
             page: page
             relation_name: relation_name
-            to_kind_id: kd.info.medium_kind_id
+            to_kind_id: kind_id
           }
         )


home: default to metrics

home: default to metrics

--- src/pages/home/index.coffee
+++ src/pages/home/index.coffee
@@ -13,7 +13,7 @@

 module.exports = class HomePage
   constructor: ({model}) ->
-    selectedIndex = new Rx.BehaviorSubject(1)
+    selectedIndex = new Rx.BehaviorSubject(0)

     @$head = new Head()
     @$menu = new Menu()


[client-app] fix module spec

[client-app] fix module spec

This changed because we now globally require node_modules

--- packages/client-app/spec/module-cache-spec.coffee
+++ packages/client-app/spec/module-cache-spec.coffee
@@ -75,7 +75,7 @@
     ModuleCache.add NylasEnv.getLoadSettings().resourcePath, {
       _nylasModuleCache:
         dependencies: [{
-          name: 'underscore'
+          name: 'unknown-lib'
           version: require('underscore/package.json').version
           path: path.join('node_modules', 'underscore', 'underscore.js')
         }]
@@ -83,7 +83,7 @@

     indexPath = path.join(packagePath, 'index.js')
     fs.writeFileSync indexPath, """
-      exports.load = function() { require('underscore'); };
+      exports.load = function() { require('unknown-lib'); };
     """

     spyOn(process, 'cwd').andReturn('/') # Required when running this test from CLI


send referrer with register

send referrer with register

--- src/forms/register.coffee
+++ src/forms/register.coffee
@@ -32,6 +32,7 @@
       lastName:         @data.get 'user.lastName'
       password:         @data.get 'user.password'
       passwordConfirm:  @data.get 'user.passwordConfirm'
+      referrerId:       @data.get 'order.referrerId'

     @errorMessage = ''


Make it disable if described as comingsoon

--- client/app/Applications/StartTab.kdapplication/views/appthumbview.coffee
+++ client/app/Applications/StartTab.kdapplication/views/appthumbview.coffee
@@ -124,6 +124,9 @@

   constructor:(options, data)->

+    if data.type is 'comingsoon'
+      data.disabled = yes
+
     super options, data

     @img.$().attr "src", "/images/#{data.icon}"
@@ -165,7 +168,7 @@
     if type is 'koding-app'
       @showLoader()
       appManager.openApplication path, => @hideLoader()
-    else if type is 'comingsoon'
-      new KDNotificationView
-        title : 'Coming Soon!'
+    # else if type is 'comingsoon'
+    #   new KDNotificationView
+    #     title : 'Coming Soon!'
     return no


Fix bug stripping equipment from hero on second play after reloading level editor

--- app/views/play/level/PlayLevelView.coffee
+++ app/views/play/level/PlayLevelView.coffee
@@ -522,6 +522,9 @@

   onLevelReloadFromData: (e) ->
     isReload = Boolean @world
+    if isReload
+      # Make sure to share any models we loaded that the parent didn't, like hero equipment, in case the parent relodaed
+      e.supermodel.registerModel model for url, model of @supermodel.models when not e.supermodel.models[url]
     @setLevel e.level, e.supermodel
     if isReload
       @scriptManager.setScripts(e.level.get('scripts'))


Ref: remote.requireしてなかったのを修正

Ref: remote.requireしてなかったのを修正

--- src/gui/js/setting.coffee
+++ src/gui/js/setting.coffee
@@ -3,9 +3,9 @@
 config = remote.require("./config")
 cache = remote.require("./cache")
 util = remote.require("./util")
-fs = require "fs"
-os = require "os"
+fs = remote.require("fs")
 path = remote.require("path")
+os = remote.require("os")

 lang = config.get("lang")
 langList = config.LANG_LIST


OutputView: support to stringify provided objects

--- client/admin/lib/views/stacks/outputview.coffee
+++ client/admin/lib/views/stacks/outputview.coffee
@@ -1,9 +1,10 @@
 kd             = require 'kd'
+hljs           = require 'highlight.js'
+dateFormat     = require 'dateformat'

-hljs           = require 'highlight.js'
 JView          = require 'app/jview'
 curryIn        = require 'app/util/curryIn'
-dateFormat     = require 'dateformat'
+objectToString = require 'app/util/objectToString'

 module.exports = class OutputView extends kd.ScrollView
@@ -34,10 +35,18 @@
     @code.updatePartial ''
     return this

+  stringify = (content) ->
+
+    for item,i in content
+      content[i] = if typeof item is 'object' \
+                   then objectToString item else item
+
+    content = content.join ' '
+

   add: (content...) ->

-    content = content.join ' '
+    content = stringify content
     content = "[#{dateFormat Date.now(), 'HH:MM:ss'}] #{content}\n"
     @code.setPartial hljs.highlight(@highlight, content).value
     @scrollToBottom()
@@ -47,7 +56,7 @@

   set: (content...) ->

-    content = content.join ' '
+    content = stringify content
     @code.updatePartial hljs.highlight(@highlight, content).value
     @scrollToBottom()


add conditional for lead paragraph

add conditional for lead paragraph

--- client/apps/edit/components/layout/index.coffee
+++ client/apps/edit/components/layout/index.coffee
@@ -116,7 +116,7 @@

   getBodyText: =>
     @fullText = []
-    if @article.get('lead_paragraph').length
+    if @article.get('lead_paragraph')?.length
       @fullText.push @article.get('lead_paragraph')
     for section in @article.sections.models when section.get('type') is 'text'
       @fullText.push section.get('body')


IDE: temp boilerplate

IDE: temp boilerplate

--- client/ide/views/tabview/idefilestabview.coffee
+++ client/ide/views/tabview/idefilestabview.coffee
@@ -8,38 +8,36 @@

     ideAppController = KD.getSingleton('appManager').getFrontApp()

-    dummyPane  = new KDTabPaneView
+    filesPane  = new KDTabPaneView
+      name     : 'Files'
+      closable : no
+
+    filesPane.addSubView new FinderPane
+    @tabView.addPane filesPane
+
+    actionsPane  = new KDTabPaneView
       name     : 'Actions'
       closable : no

-    dummyPane.addSubView new KDButtonView
+    actionsPane.addSubView new KDButtonView
       title      : 'Vertical'
       cssClass   : 'compact solid green'
       attributes :
         style    : 'display: block; margin: 20px; width: 200px; '
       callback   : -> ideAppController.splitTabView 'vertical'

-    dummyPane.addSubView new KDButtonView
+    actionsPane.addSubView new KDButtonView
       title      : 'Horizontal'
       cssClass   : 'compact solid green'
       attributes :
         style    : 'display: block; margin: 20px; width: 200px; '
       callback   : -> ideAppController.splitTabView 'horizontal'

-    dummyPane.addSubView new KDButtonView
+    actionsPane.addSubView new KDButtonView
       title      : 'Merge'
       cssClass   : 'compact solid green'
       attributes :
         style    : 'display: block; margin: 20px; width: 200px; '
       callback   : -> ideAppController.mergeSplitView()

-    @tabView.addPane dummyPane
-
-    ################################
-
-    tabPane    = new KDTabPaneView
-      name     : 'Files'
-      closable : no
-
-    tabPane.addSubView new FinderPane
-    @tabView.addPane tabPane
+    @tabView.addPane actionsPane


Fixed navigation bar

Fixed navigation bar

Placed the right control arrow into the page-nav container

--- client/landing/app/MainApp/book/bookview.coffee
+++ client/landing/app/MainApp/book/bookview.coffee
@@ -56,6 +56,15 @@
         title   : "Table of contents"
         gravity : "sw"

+    @showMeButton = new KDCustomHTMLView
+      tagName   : "a"
+      partial   : "Show me how!"
+      cssClass  : "cta_button"
+      click     : (pubInst, event)=> @showMeButtonClicked()
+
+    @pagerWrapper.addSubView @showMeButton
+
+
     @pageNav.addSubView new KDCustomHTMLView
       tagName   : "a"
       partial   : "◀"
@@ -64,20 +73,7 @@
         title   : "Press: Left Arrow Key"
         gravity : "sw"

-
-
-
-    @showMeButton = new KDCustomHTMLView
-      tagName   : "a"
-      partial   : "Show ME HOW!"
-      click     : (pubInst, event)=> @showMeButtonClicked()
-      tooltip   :
-        title   : "help me right here!"
-
-    @pagerWrapper.addSubView @showMeButton
-
-
-    @pagerWrapper.addSubView new KDCustomHTMLView
+    @pageNav.addSubView new KDCustomHTMLView
       tagName   : "a"
       partial   : "▶"
       click     : (pubInst, event)=> @fillNextPage()
@@ -180,7 +176,7 @@
     # check if page has tutorial
     if @page.data.howToSteps.length < 1
       @showMeButton.hide()
-    else
+    else
       @showMeButton.show()

@@ -199,7 +195,7 @@

   showMeButtonClicked:->
-
+
     @pointer or = new KDCustomHTMLView
       partial : ''
       cssClass : 'point'
@@ -208,11 +204,11 @@

     @pagerWrapper.addSubView @pointer
     #!!! we should check here if has tutorial available for current topic
-    if @page.data.menuItem
+    if @page.data.menuItem
       @navigateCursorToMenuItem(@page.data.menuItem)
-    else
+    else
       @continueNextMove()
-
+
   navigateCursorToMenuItem:(menuItem)->

     @pointer.once 'transitionend', =>
@@ -225,7 +221,7 @@
       @utils.wait 600, =>
         @continueNextMove()

-    @selectedMenuItem = @mainView.sidebar.nav.items.filter (x) -> x.name is menuItem
+    @selectedMenuItem = @mainView.sidebar.nav.items.filter (x) -> x.name is menuItem
     selectedMenuItemOffset = @selectedMenuItem[0].$().offset()

     @pointer.$().offset selectedMenuItemOffset
@@ -304,8 +300,8 @@
     # find offset of submit button
     submitButtonOffset = @mainView.mainTabView.activePane.mainView.widgetController.updateWidget.submitBtn.$().offset()
     # navigate submit button
-    @pointer.$().offset submitButtonOffset
-
+    @pointer.$().offset submitButtonOffset
+
   clickFolderOnFileTree:->
     @mainView.sidebar.animateLeftNavOut()
     @pointer.once 'transitionend', =>
@@ -328,20 +324,20 @@
       # move cursor to file tree menu
       @pointer.$().offset
         top     : vmOffset.top
-        left    : vmOffset.left
+        left    : vmOffset.left

   showVMMenu:->
     @mainView.sidebar.animateLeftNavOut()
     @pointer.once 'transitionend', =>
       # make click action
       @clickAnimation()
-      # open VM menu
+      # open VM menu
       @mainView.sidebar.resourcesController.itemsOrdered[0].chevron.$().click()
       # wait 3 sec.
       @utils.wait 2000, =>
         # remove pointer
         #@pointer.destroy()
-
+
     # TODO !!! should remove that class on pageNext
     @setClass 'moveUp'
     @mainView.once 'transitionend', =>
@@ -350,19 +346,19 @@
         vmMenuOffset = @mainView.sidebar.resourcesController.itemsOrdered[0].chevron.$().offset()
         # move cursor to VM's menu position
         @pointer.$().offset vmMenuOffset
-
+
   showVMTerminal:->
     @mainView.sidebar.animateLeftNavOut()
     @pointer.once 'transitionend', =>
       # make click action
       @clickAnimation()
-      # open VM menu
+      # open VM menu
       # wait 3 sec.
       @utils.wait 2000, =>
         @mainView.sidebar.resourcesController.itemsOrdered[0].buttonTerm.$().click()
         # remove pointer
         #@pointer.destroy()
-
+
     # TODO !!! should remove that class on pageNext
     @setClass 'moveUp'
     @mainView.once 'transitionend', =>
@@ -371,7 +367,7 @@
         vmMenuOffset = @mainView.sidebar.resourcesController.itemsOrdered[0].buttonTerm.$().offset()
         # move cursor to VM's menu position
         @pointer.$().offset vmMenuOffset
-
+
   showRecentFilesMenu:->
     @pointer.once 'transitionend', =>
       @utils.wait 6000, =>
@@ -383,12 +379,12 @@
     # find recent files menu
     offsetTo = @mainView.mainTabView.activePane.mainView.recentFilesWrapper.$().offset()
     log offsetTo
-    # move cursor
+    # move cursor
     @utils.wait 700, =>
       @pointer.$().offset offsetTo
-
+
     log offsetTo
-
+
   showNewVMMenu:->
     @pointer.once 'transitionend', =>
     # click animation
@@ -396,7 +392,7 @@
     # click menu
       @mainView.sidebar.createNewVMButton.$().click()

-    # move book to up to make button visible
+    # move book to up to make button visible
     @setClass 'moveUp'
     # if sidebar is closed opens it.
     @mainView.sidebar.animateLeftNavOut()
@@ -415,7 +411,7 @@
       KD.singletons.chatPanel.showPanel()
       @utils.wait 1000, =>
         @startNewConversation()
-
+
     # find conversations panel icon position.
     offsetTo = @mainView.chatHandler.$().offset()
     # move cursor to conv. panel button position.
@@ -443,13 +439,13 @@
     # dbl-click animation
     # find 'Hello World'
     # continue to next step
-    # find ace menu
+    # find ace menu
     # move cursor to ace menu
     # find save menu item
     # move cursor to save menu item
     # click animation

-
+


Update projectUtils.coffee

Update projectUtils.coffee

--- client/src/project/services/projectUtils.coffee
+++ client/src/project/services/projectUtils.coffee
@@ -20,8 +20,8 @@
     label: 'Commercial'
     value: 'com'
   ,
-    label: 'UX/UI Designer'
-    value: 'UX'
+    label: 'Designer'
+    value: 'designer'
   ]
   getDailyRecipient: ->
     [


Admin: Removed default options.

Admin: Removed default options.

--- client/admin/lib/views/integrations/adminintegrationdetailsview.coffee
+++ client/admin/lib/views/integrations/adminintegrationdetailsview.coffee
@@ -44,8 +44,6 @@
           selectOptions : items
           defaultValue  : data.selectedChannel
         url             :
-          type          : 'input'
-          cssClass      : 'text'
           label         : "
Webhook URL
When setting up this integration, this is the URL that you will paste into #{data.title}."
           defaultValue  : data.webhookUrl
           attributes    : readonly: 'readonly'
@@ -56,13 +54,9 @@
               cssClass  : 'link'
               click     : @bound 'regenerateToken'
         label           :
-          type          : 'input'
-          cssClass      : 'text'
           label         : '
Descriptive Label
Use this label to provide extra context in your list of integrations (optional).'
           defaultValue  : data.summary
         name            :
-          type          : 'input'
-          cssClass      : 'text'
           label         : '
Customize Name
Choose the username that this integration will post as.'
           defaultValue  : data.title
       buttons           :


Fix bad month counting in exec test

Fix bad month counting in exec test

--- Src/coffeescript/cql-execution/test/elm/clinical/test.coffee
+++ Src/coffeescript/cql-execution/test/elm/clinical/test.coffee
@@ -161,16 +161,16 @@

     # this is getting the possible number of months in years with the addtion of an offset
     # to get the correct number of months
-    @full_months = ((@today.getFullYear() - 1980) * 12) + (@today.getMonth() - 6)
+    month_offset = if @today.getMonth() == 5 && @today.getDate() < 17 then 6 else 5
+    @full_months = ((@today.getFullYear() - 1980) * 12) + (@today.getMonth() - month_offset)
+
     @timediff = @today - @bday # diff in milliseconds

   it 'should execute age in years', ->
     @years.exec(@ctx).should.equal @full_months // 12

   it 'should execute age in months', ->
-    # what is returned will depend on whether the day in the current month has
-    # made it to the 17th day of the month as declared in the birthday
-    [@full_months, @full_months-1].indexOf(@months.exec(@ctx)).should.not.equal -1
+    @months.exec(@ctx).should.equal @full_months

   it 'should execute age in days', ->
     @days.exec(@ctx).should.equal @timediff // 1000 // 60 // 60 // 24


:memo: Link to non-deprecated method

:memo: Link to non-deprecated method

--- src/keymap-manager.coffee
+++ src/keymap-manager.coffee
@@ -183,11 +183,10 @@
         new File(filePath).on 'contents-changed moved removed', =>
           @reloadKeymap(filePath)

-  # Public: Remove the key bindings added with {::addKeymap} or
-  # {::loadKeymap}.
+  # Public: Remove the key bindings added with {::add} or {::loadKeymap}.
   #
   # source - A {String} representing the `source` in a previous call to
-  #   {::addKeymap} or the path in {::loadKeymap}.
+  #          {::add} or the path in {::loadKeymap}.
   remove: (source) ->
     @keyBindings = @keyBindings.filter (keyBinding) -> keyBinding.source isnt source


Use postfix if

Use postfix if

--- src/keymap-manager.coffee
+++ src/keymap-manager.coffee
@@ -519,8 +519,7 @@
       # whose default action was prevented and no binding is matched, we'll
       # simulate the text input event that was previously prevented to insert
       # the missing characters.
-      if event.defaultPrevented
-        @simulateTextInput(event)
+      @simulateTextInput(event) if event.defaultPrevented
       queuedKeystrokes = null

     return {keystroke, exactMatch, partialMatches, queuedKeystrokes}