﻿// =====================================================================
// Digitação no tempo da voz (recriação @subzmotion "On My Way")
// Liga ao Texto-fonte de uma camada de texto uma expressão que digita letra a letra:
// as letras da palavra i entram entre o início da palavra i e o início da palavra i+1
// (a última termina em "fim"). Cursor "|" aparece enquanto digita e some "cursorFica" s depois.
// Uso (ES3):  $.evalFile(".../ae/digitar.jsx");
//   DIGITAR(camadaTexto, ["Revisar","a","timeline","do","cliente"], [0.00,0.18,0.42,0.74,0.96], 1.20, {cursor:true});
// Opções: cursor (padrão true), cursorFica (s, padrão 0.25), maiusculas (padrão false),
//         ritmo: "palavra" (padrão: letras espalhadas no intervalo da palavra) ou "letra" (q quadros por letra, opção q).
// Para trocar o texto depois, edite os dois arrays no topo da expressão (ou rode DIGITAR de novo).
// =====================================================================
function DIGITAR(lay, palavras, inicios, fim, op) {
  op = op || {};
  var cursor = (op.cursor === undefined) ? true : op.cursor;
  var fica = (op.cursorFica === undefined) ? 0.25 : op.cursorFica;
  var q = op.q || 2;
  var ritmo = op.ritmo || "palavra";
  function arr(a, str) { var s = [], i; for (i = 0; i < a.length; i++) s.push(str ? ('"' + String(a[i]).replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"') : a[i]); return "[" + s.join(",") + "]"; }
  var ex = [
    "var P = " + arr(palavras, true) + ";",
    "var T = " + arr(inicios, false) + ";",
    "var FIM = " + fim + ", CURSOR = " + (cursor ? "true" : "false") + ", FICA = " + fica + ", RITMO = \"" + ritmo + "\", Q = " + q + ";",
    "var txt = '', ativo = false, i, n;",
    "for (i = 0; i < P.length; i++) {",
    "  var w = P[i] + (i < P.length - 1 ? ' ' : '');",
    "  var a = T[i], b = (i < P.length - 1) ? T[i + 1] : FIM;",
    "  if (time < a) break;",
    "  if (RITMO == 'letra') { n = Math.floor((time - a) / (Q * thisComp.frameDuration)) + 1; }",
    "  else { n = Math.floor((time - a) / Math.max(b - a, thisComp.frameDuration) * P[i].length) + 1; }",
    "  n = Math.min(n, w.length); txt += w.substr(0, n); if (n < w.length) { ativo = true; break; }",
    "}",
    "var fimDig = (RITMO == 'letra') ? 0 : FIM;",
    "if (CURSOR && time >= T[0] && (ativo || time < FIM + FICA)) txt += '|';",
    "txt;"
  ].join("\n");
  lay.property("ADBE Text Properties").property("ADBE Text Document").expression = ex;
  return lay;
}
