Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cha0s/5cc2fd1fe4e9e9a3cc14 to your computer and use it in GitHub Desktop.
Save cha0s/5cc2fd1fe4e9e9a3cc14 to your computer and use it in GitHub Desktop.
New image resizers :)

Reddichat - Markdown - Expando - Image - Resizer

path = require 'path'

exports.pkgmanRegister = (registrar) ->

  registrar.registerHook 'shrubAngularDirective', -> [
    '$compile', '$window'
    ($compile, $window) ->

      directive = {}

      directive.link = (scope, elm) ->

        scope.wasResized = false
        scope.isResizing = false

        $img = elm.find 'img'
        $img.on 'load', ->
          scope.origin = width: $img.width()
          scope.ratio = $img.width() / $img.height()

        recalculateOrigin = ({pageX, pageY}) ->
          scope.origin.x = pageX
          scope.origin.y = pageY
          scope.origin.movingWidth = $img.width()

Only register 'click' if the image wasn't resized.

        scope.click = ($event) -> $event.preventDefault() if @wasResized

        scope.mouseDown = ($event) ->
          {pageX, pageY} = $event

          @wasResized = false
          @isResizing = true

          recalculateOrigin $event

          $event.preventDefault()

Toggle global event handlers (since they need to apply even if the mouse moves off the image element) based on whether the image is expanded.

        scope.$watch 'expanded', (expanded) ->

          if expanded

            angular.element($window).on 'mousemove', mouseMove = ($event) ->
              return unless scope.isResizing
              scope.wasResized = true

              {pageX, pageY} = $event

Set the new width from the delta -- Y delta factors in image ratio.

              deltaX = pageX - scope.origin.x
              deltaY = scope.ratio * (pageY - scope.origin.y)
              width = Math.round(
                scope.origin.movingWidth + 2 * (deltaY + deltaX)
              )

Clamp min/max and recalculate origin if clamping to prevent needing to pull back from overcompensation.

              if width < scope.origin.width
                $img.css 'width', 'auto'
                recalculateOrigin $event
                return

              recalculateOrigin $event if width > $img.width()
              $img.css 'width', width

            angular.element($window).on 'mouseup', mouseUp = ->
              return unless scope.isResizing
              scope.isResizing = false

          else

            angular.element($window).off(mouseUp).off(mouseMove)

      directive.scope = true

      directive.template = '''
<img
  data-ng-click="click($event)"
  data-ng-mousedown="mouseDown($event)"
  data-ng-src="{{src}}"
/>
'''

      return directive

  ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment