/*
 * Apply Motion Token — After Effects script
 * Part of motion-tokens · https://github.com/soylepanke/motion-tokens
 * Made by Juan Carlos · lepanke.com · MIT License
 *
 * Applies a cubic-bezier easing token to the selected keyframes, converting it
 * to After Effects temporal speed and influence.
 *
 * How to use
 *   1. Select two or more neighbouring keyframes on one or more properties.
 *   2. File > Scripts > Run Script File... > apply-motion-token.jsx
 *      (or copy it to "Scripts/ScriptUI Panels" and open it from the Window menu).
 *   3. Pick a token and press Apply. Every segment between two selected,
 *      consecutive keyframes gets the curve. One undo step.
 *
 * The conversion, for a 1D property that changes by dv in dt seconds:
 *   out influence = x1 * 100        out speed = (y1 / x1) * (dv / dt)
 *   in influence  = (1 - x2) * 100  in speed  = ((1 - y2) / (1 - x2)) * (dv / dt)
 * Multi-dimensional properties (Scale, Color...) are converted per dimension.
 * Spatial properties (Position, Anchor Point) use the distance between the two
 * keyframes as dv. AE needs an influence of at least 0.1%, so x1 = 0 or x2 = 1
 * are treated as 0.1%, which keeps the shape of the curve.
 *
 * Requires After Effects CC 2015 or later. Plain ExtendScript (ES3).
 */

// @tokens:start (generated by `npm run build` from tokens/motion.tokens.json — do not edit by hand)
var MOTION_TOKENS = [
  { name: "linear", bezier: [0, 0, 1, 1], description: "Constant speed. Mechanical moves, progress bars, loops that must not breathe." },
  { name: "standard", bezier: [0.2, 0, 0, 1], description: "Default for UI. Quick start, long soft landing." },
  { name: "enter", bezier: [0.16, 1, 0.3, 1], description: "Things arriving on screen. Fast in, settles gently (expo out)." },
  { name: "exit", bezier: [0.7, 0, 0.84, 0], description: "Things leaving. Builds speed and is gone (expo in). Pair with a shorter duration." },
  { name: "move", bezier: [0.83, 0, 0.17, 1], description: "Travel from A to B: camera moves, layout shifts, slides (quint in-out)." },
  { name: "smooth", bezier: [0.65, 0, 0.35, 1], description: "Gentle in-out for ambient and looping motion (cubic in-out)." },
  { name: "easy-ease", bezier: [0.333, 0, 0.667, 1], description: "After Effects 'Easy Ease' (F9): 33.33% influence, zero speed on both keys." },
  { name: "pop", bezier: [0.05, 0.7, 0.1, 1], description: "Snappy arrival with almost no wind-up. Small elements, icons, toasts." },
  { name: "overshoot", bezier: [0.34, 1.56, 0.64, 1], description: "Goes past the target and comes back (back out). Playful entrances." },
  { name: "anticipate", bezier: [0.36, 0, 0.66, -0.56], description: "Pulls back before leaving (back in). Exits with character." }
];
// @tokens:end

var MIN_INFLUENCE = 0.1; // percent; the smallest influence After Effects accepts

/**
 * Pure maths, no After Effects objects: converts a cubic-bezier to AE ease
 * values for one dimension. dv = value change, dt = time in seconds.
 * Returns { outSpeed, outInfluence, inSpeed, inInfluence }.
 */
function bezierToAE(bezier, dv, dt) {
  var minX = MIN_INFLUENCE / 100;
  var x1 = Math.max(bezier[0], minX);
  var y1 = bezier[1];
  var x2 = Math.min(bezier[2], 1 - minX);
  var y2 = bezier[3];
  var rate = dt > 0 ? dv / dt : 0;
  return {
    outInfluence: x1 * 100,
    outSpeed: (y1 / x1) * rate,
    inInfluence: (1 - x2) * 100,
    inSpeed: ((1 - y2) / (1 - x2)) * rate
  };
}

/** Value change between two keyframe values, one entry per ease dimension. */
function valueDeltas(v1, v2, easeCount) {
  var deltas = [];
  var i;
  if (!(v1 instanceof Array)) {
    deltas.push(v2 - v1);
    return deltas;
  }
  if (easeCount === 1) {
    // spatial property (or one ease for an array value): distance along the path
    var sum = 0;
    for (i = 0; i < v1.length; i++) sum += (v2[i] - v1[i]) * (v2[i] - v1[i]);
    deltas.push(Math.sqrt(sum));
    return deltas;
  }
  for (i = 0; i < easeCount; i++) deltas.push(v2[i] - v1[i]);
  return deltas;
}

function applyTokenToSegment(prop, k1, k2, bezier, warnings) {
  var t1 = prop.keyTime(k1);
  var t2 = prop.keyTime(k2);
  var v1 = prop.keyValue(k1);
  var v2 = prop.keyValue(k2);
  var count = prop.keyOutTemporalEase(k1).length;
  var deltas = valueDeltas(v1, v2, count);
  var spatial = count === 1 && v1 instanceof Array;
  if (spatial && (bezier[1] < 0 || bezier[1] > 1 || bezier[3] < 0 || bezier[3] > 1)) {
    // the speed graph of a spatial path cannot leave the path
    warnings.push(prop.name + ": this curve goes outside 0-1, and a spatial property cannot overshoot its motion path. For a real overshoot, use Separate Dimensions.");
  }

  var outEases = [];
  var inEases = [];
  for (var d = 0; d < count; d++) {
    var ae = bezierToAE(bezier, deltas[d], t2 - t1);
    outEases.push(new KeyframeEase(ae.outSpeed, ae.outInfluence));
    inEases.push(new KeyframeEase(ae.inSpeed, ae.inInfluence));
  }

  // keep the side of each key that does not belong to this segment
  var keepIn = prop.keyInTemporalEase(k1);
  var keepOut = prop.keyOutTemporalEase(k2);

  prop.setTemporalContinuousAtKey(k1, false);
  prop.setTemporalContinuousAtKey(k2, false);
  prop.setTemporalAutoBezierAtKey(k1, false);
  prop.setTemporalAutoBezierAtKey(k2, false);
  prop.setInterpolationTypeAtKey(k1, prop.keyInInterpolationType(k1), KeyframeInterpolationType.BEZIER);
  prop.setInterpolationTypeAtKey(k2, KeyframeInterpolationType.BEZIER, prop.keyOutInterpolationType(k2));
  prop.setTemporalEaseAtKey(k1, keepIn, outEases);
  prop.setTemporalEaseAtKey(k2, inEases, keepOut);
}

function applyToken(token) {
  var comp = app.project.activeItem;
  if (!(comp instanceof CompItem)) {
    alert("Open a composition and select some keyframes first.");
    return;
  }
  var props = comp.selectedProperties;
  var segments = 0;
  var warnings = [];

  app.beginUndoGroup("Apply motion token: " + token.name);
  try {
    for (var p = 0; p < props.length; p++) {
      var prop = props[p];
      if (prop.propertyType !== PropertyType.PROPERTY || !prop.canVaryOverTime) continue;
      var keys = prop.selectedKeys;
      if (!keys || keys.length < 2) continue;
      for (var i = 0; i < keys.length - 1; i++) {
        if (keys[i + 1] === keys[i] + 1) {
          applyTokenToSegment(prop, keys[i], keys[i + 1], token.bezier, warnings);
          segments++;
        }
      }
    }
  } catch (err) {
    alert("Could not apply the token: " + err.toString());
  }
  app.endUndoGroup();

  if (segments === 0) {
    alert("Select at least two neighbouring keyframes on a property.");
  } else if (warnings.length) {
    alert(segments + " segment(s) eased with '" + token.name + "'.\n\n" + warnings[0]);
  }
}

function buildUI(thisObj) {
  var win = thisObj instanceof Panel
    ? thisObj
    : new Window("palette", "Apply Motion Token", undefined, { resizeable: true });
  win.orientation = "column";
  win.alignChildren = ["fill", "top"];
  win.spacing = 8;
  win.margins = 12;

  var names = [];
  for (var i = 0; i < MOTION_TOKENS.length; i++) {
    var b = MOTION_TOKENS[i].bezier;
    names.push(MOTION_TOKENS[i].name + "   (" + b.join(", ") + ")");
  }
  var list = win.add("dropdownlist", undefined, names);
  list.selection = 1;

  var info = win.add("statictext", undefined, MOTION_TOKENS[1].description, { multiline: true });
  info.preferredSize = [260, 40];
  list.onChange = function () {
    if (list.selection) info.text = MOTION_TOKENS[list.selection.index].description;
  };

  var apply = win.add("button", undefined, "Apply to selected keyframes");
  apply.onClick = function () {
    if (list.selection) applyToken(MOTION_TOKENS[list.selection.index]);
  };

  var credit = win.add("statictext", undefined, "motion-tokens · lepanke.com");
  credit.graphics.foregroundColor = credit.graphics.newPen(credit.graphics.PenType.SOLID_COLOR, [0.55, 0.55, 0.55], 1);

  win.onResizing = win.onResize = function () { this.layout.resize(); };
  if (win instanceof Window) {
    win.center();
    win.show();
  } else {
    win.layout.layout(true);
  }
  return win;
}

if (typeof app !== "undefined" && typeof app.project !== "undefined") {
  buildUI(this);
}
