steveruizok
2/20/2018 - 12:10 AM

constrain.coffee

# Set a layer's contraints to its parent
# @example    Utils.constrain(layer, {left: true, top: true, asepectRatio: true})
Utils.constrain = (layer, opts...) ->
  if not layer.parent? then throw 'Utils.constrain requires a layer with a parent.'

  options =
    left: false, 
    top: false, 
    right: false, 
    bottom: false,
    height: false
    width: false
    aspectRatio: false

  for opt in opts
    options[opt] = true

  values = 
    left: if options.left then layer.x else null
    height: layer.height
    centerAnchorX: layer.midX / layer.parent?.width
    width: layer.width
    right: if options.right then layer.parent?.width - layer.maxX else null
    top: if options.top then layer.y else null
    centerAnchorY: layer.midY / layer.parent?.height
    bottom: if options.bottom then layer.parent?.height - layer.maxY else null
    widthFactor: null
    heightFactor: null
    aspectRatioLocked: options.aspectRatio

  unless options.top and options.bottom
    if options.height
      values.heightFactor = layer.height / layer.parent?.height

  unless options.left and options.right 
    if options.width
      values.widthFactor = layer.width / layer.parent?.width

  layer.constraintValues = values