Pony.fm/public/scripts/app/directives/popup.coffee

84 lines
2 KiB
CoffeeScript
Raw Normal View History

2013-07-27 05:00:45 +02:00
angular.module('ponyfm').directive 'pfmPopup', () ->
(scope, element, attrs) ->
2013-07-28 19:45:21 +02:00
align = 'left'
elementId = attrs.pfmPopup
if elementId.indexOf ',' != -1
parts = elementId.split ','
elementId = parts[0]
align = parts[1]
2013-07-27 05:00:45 +02:00
$popup = $ '#' + attrs.pfmPopup
$element = $ element
2013-07-28 08:07:25 +02:00
$positionParent = null
2013-07-27 05:00:45 +02:00
open = false
2013-07-28 08:07:25 +02:00
$popup.parents().each () ->
$this = $ this
$positionParent = $this if $positionParent == null && ($this.css('position') == 'relative' || $this.is 'body')
2013-07-27 05:00:45 +02:00
documentClickHandler = () ->
return if !open
$popup.removeClass 'open'
open = false
2013-07-28 08:07:25 +02:00
calculatePosition = ->
position = $element.offset()
parentPosition = $positionParent.offset()
2013-07-28 19:45:21 +02:00
windowWidth = $(window).width() - 15
2013-07-28 08:07:25 +02:00
left = position.left
right = left + $popup.width()
2013-07-28 19:45:21 +02:00
if align == 'left' && right > windowWidth
2013-07-28 08:07:25 +02:00
left -= right - windowWidth
2013-07-28 19:45:21 +02:00
else if align == 'right'
left -= $popup.outerWidth() - $element.outerWidth()
2013-07-28 08:07:25 +02:00
height = 'auto'
top = position.top + $element.height() + 10
bottom = top + $popup.height()
windowHeight = $(window).height()
if bottom > windowHeight
height = windowHeight - top;
return {
left: left - parentPosition.left - 2
top: top - parentPosition.top,
2013-07-28 19:45:21 +02:00
height: height - 15}
2013-07-27 05:00:45 +02:00
2013-07-28 08:07:25 +02:00
windowResizeHandler = () ->
return if !open
$popup.css 'height', 'auto'
position = calculatePosition()
$popup.css
left: position.left
top: position.top
height: position.height
$(document.body).bind 'click', documentClickHandler
$(window).bind 'resize', windowResizeHandler
2013-07-27 05:00:45 +02:00
$(element).click (e) ->
e.preventDefault()
e.stopPropagation()
if open
open = false
$popup.removeClass 'open'
return
$popup.addClass 'open'
2013-07-28 06:37:32 +02:00
2013-07-28 08:07:25 +02:00
$popup.css 'height', 'auto'
position = calculatePosition()
2013-07-27 05:00:45 +02:00
$popup.css
2013-07-28 08:07:25 +02:00
left: position.left
top: position.top
height: position.height
2013-07-27 05:00:45 +02:00
open = true
scope.$on '$destroy', () ->
$(document.body).unbind 'click', documentClickHandler
2013-07-28 08:07:25 +02:00
$(window).unbind 'click', windowResizeHandler