<commit_before>/**
 * 変数
 */
var map;
var points = [];
var sidebar = {};
/** 表示中のデータ配列*/
var dispDatas = [];

/**
 * Leafletの表示
 */
function initLeaflet(lat, lng) {
  // LeafletのOSM表示
  map = L.map('map').setView([lat, lng], 17);
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
	attribution: '© OpenStreetMap contributors'
  }).addTo(map);
}

/** コメントからタイトルを取り出して返す
 * コメントの1行目がタイトル。改行がない場合は全体がタイトル
 */
function getTitle(comm) {
  return comm.split("\n")[0].replace(/\r/g,"").trim();
}

/**
 * コメントからコメントのみを取り出す。改行はbrタグに変換
 */
function getComment(comm) {
  var lines = comm.replace(/\r/g,"").split("\n");
  // 1行の時はコメントなし
  if (lines.length <= 1) {
    return "";
  }
  // 改行をbrタグに変換して返す
  lines.shift();
  return lines.join("
");
}

function setMarker(datas) {
  var mk;
  var pop;
  for(var i=0 ; i<datas.length ; i++) {
    mk = L.marker(
      [datas[i].lat,datas[i].lng],
      {
        title: getTitle(datas[i].comment),
        alt: datas[i].tags[0]
      }
    ).on('click', function() {
      mk.bounce();
    });
    pop =
    "
"+getTitle(datas[i].comment)+"
"
    +""
    +"
Tags:";
    for (var j=0 ; j<datas[i].tags.length ; j++) {
      if (j > 0) pop+=", ";
      pop += datas[i].tags[j];
    }
    mk.bindPopup(pop);
    points.push(mk);
    mk.addTo(map);
  }
}

function setButtons() {
  var helloPopup = L.popup().setContent('Hello World!');

  L.easyButton('glyphicon-list', function(btn, map){
    sidebar.toggle();
  }).addTo( map ); // probably just `map`

  L.easyButton('glyphicon-search', function(btn, map){
      helloPopup.setLatLng(map.getCenter()).openOn(map);
  }).addTo( map ); // probably just `map`

  L.easyButton('glyphicon-floppy-disk', function(btn, map){
      helloPopup.setLatLng(map.getCenter()).openOn(map);
  }).addTo( map ); // probably just `map`
}

/**　渡されたデータの内容をサイドバーに列挙して、出力*/
function setSidebar(datas) {
  var authdate = "";
  sidebar = L.control.sidebar('data-list', {
    position: 'right'
  });
  map.addControl(sidebar);

  // データを列挙
  dispDatas = datas;
  var dlist = "";//"
";
  dlist += "
";
  for (var i=0 ; i<datas.length; i++) {
    dlist += "
";

    // 画像
    dlist += "";
    dlist += "";
    dlist += "	";

    // 情報欄
    dlist += "";

    dlist += getInfoRow(datas,i);

    // 列終わり
    dlist += "
";

  }
  dlist += "
";
  dlist += "";//"
";
  //
  $('#data-list').html(dlist);
  sidebar.show();
}

/**
 * 編集へ
 */
function changeEdit(idx) {
  var id = "#info"+idx;
  $(id).html(getInfoEditRow(dispDatas, idx));
}

/**
 * 情報パネルに戻る
 */
function backInfo(idx) {
  var id = "#info"+idx;
  $(id).html(getInfoRow(dispDatas, idx));
}

/**
 * 指定の配列の指定のインデックスの詳細を編集する右側のtdタグ内のHTMLを返す
 * @param [] datas データ配列
 * @param idx 作成するデータのインデックス
 */
function getInfoEditRow(datas, idx) {
  // 公開状況とタイトルとコメント
  var dlist = "
";
  var accessIcon = "";
  var accessLabel = "公開";
  var accessIcons = [
    "",
    ""
  ];

  //// 限定公開(glyphicon-user)
  if (datas[idx].access == "protected") {
      accessIcon = accessIcons[0];
      accessLabel = "限定公開";
  }
  //// 非公開(glyphicon-lock)
  else if (datas[idx].access == "private") {
    accessIcon = accessIcons[1];
    accessLabel = "非公開";
  }

  //// 切り替え
  dlist += "
";
  dlist += "<button class='btn btn-default dropdown-toggle btn-sm' type='button' id='access"+idx+"' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>";
  dlist += accessIcon+accessLabel;
  dlist += "";
  dlist += "</button>";
  dlist += "
";
  dlist += "
公開
";
  dlist += "
"+accessIcons[0]+"限定公開
";
  dlist += "
"+accessIcons[1]+"非公開
";
  dlist += "
";
  dlist += "
";
  dlist += "
";

  // タイトルとコメント
  dlist += "<textarea class='form-control input-sm' rows='3'>";
  dlist += datas[idx].comment;
  dlist += "</textarea>";

  // 付加情報
  dlist += "";
  // コメント者と日時
  // 入力者と日時
  dlist += "
";
  if (datas[idx].hasOwnProperty("author")) {
    dlist += "<input type='text' class='form-control input-sm' placeholder='作成者名' value='"+datas[idx].author+"' />";
  }
  dlist += "<input type='text' class='form-control input-sm' placeholder='2015/10/10 1:2:3' value='"+datas[idx].datetime+"' />
";

  // 緯度経度
  dlist += "
";
  dlist += "緯度";
  dlist += "
";
  dlist += "<input type='text' class='form-control input-sm' placeholder='35.151515' value='"+datas[idx].lat+"' />";
  dlist += "
";

  dlist += "経度";
  dlist += "
";
  dlist += "<input type='text' class='form-control input-sm' placeholder='139.151515' value='"+datas[idx].lng+"' />";
  dlist += "

";

  // タグ
  dlist += "
";
  dlist += "tags:";
  dlist += "
";
  dlist += "<input type='text' class='form-control input-sm' placeholder='例)カモ 鳥' value='";
  for (var j=0 ; j<datas[idx].tags.length ; j++) {
    if (j>0) {
      dlist += ' ';
    }
    dlist += datas[idx].tags[j];
  }
  dlist += "' />

";

  // 公開情報

  // ボタン配置
  dlist += "";
  //// 編集ボタン
  dlist += "<button type='button' class='btn btn-default btn-xs' aria-label='Edit' data-toggle='tooltip' data-placement='right' title='更新'";
  dlist += " onclick='backInfo("+idx+")'>";
  dlist += "";
  dlist += "</button>";
  //// 削除ボタン
  dlist += "<button type='button' class='btn btn-default btn-xs' aria-label='Remove' data-toggle='tooltip' data-placement='right' title='キャンセル'>";
  dlist += "";
  dlist += "</button>";
  dlist += "";

  dlist += "
";
  return dlist;
}

/**
 * 指定の配列の指定のインデックスの詳細を描画するためのtrタグで囲んだHTMLを返す
 * @param [] datas データ配列
 * @param idx 作成するデータのインデックス
 */
function getInfoRow(datas, idx) {
  // 公開状況とタイトルとコメント
  var dlist = "
";

  //// 限定公開(glyphicon-user)
  if (datas[idx].access == "protected") {
      dlist += "";
  }
  //// 非公開(glyphicon-lock)
  else if (datas[idx].access == "private") {
    dlist += "";
  }
  // タイトル
  dlist += ""+getTitle(datas[idx].comment)+"
";
  // コメント
  dlist += "
"+getComment(datas[idx].comment)+"
";

  // 付加情報
  dlist += "";
  // コメント者と日時
  // 入力者と日時
  dlist += "
";
  if (datas[idx].hasOwnProperty("author")) {
    dlist += ""+datas[idx].author+" ";
  }
  dlist += datas[idx].datetime+"
";

  // 緯度経度
  dlist += "lat,lng:"+datas[idx].lat+", "+datas[idx].lng;

  // タグ
  dlist += "
tags:";
  for (var j=0 ; j<datas[idx].tags.length ; j++) {
    dlist += " "+datas[idx].tags[j];
  }
  // ボタン配置
  dlist += "";
  //// 編集ボタン
  dlist += "<button type='button' class='btn btn-default btn-xs' aria-label='Edit' data-toggle='tooltip' data-placement='right' title='編集'";
  dlist += " onclick='changeEdit("+idx+")'>";
  dlist += "";
  dlist += "</button>";
  //// 削除ボタン
  dlist += "<button type='button' class='btn btn-default btn-xs' aria-label='Remove' data-toggle='tooltip' data-placement='right' title='削除'>";
  dlist += "";
  dlist += "</button>";
  dlist += "";

  dlist += "
";

  return dlist;
}
<commit_msg>キャンセルボタンで閉じる<commit_after>/**
 * 変数
 */
var map;
var points = [];
var sidebar = {};
/** 表示中のデータ配列*/
var dispDatas = [];

/**
 * Leafletの表示
 */
function initLeaflet(lat, lng) {
  // LeafletのOSM表示
  map = L.map('map').setView([lat, lng], 17);
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
	attribution: '© OpenStreetMap contributors'
  }).addTo(map);
}

/** コメントからタイトルを取り出して返す
 * コメントの1行目がタイトル。改行がない場合は全体がタイトル
 */
function getTitle(comm) {
  return comm.split("\n")[0].replace(/\r/g,"").trim();
}

/**
 * コメントからコメントのみを取り出す。改行はbrタグに変換
 */
function getComment(comm) {
  var lines = comm.replace(/\r/g,"").split("\n");
  // 1行の時はコメントなし
  if (lines.length <= 1) {
    return "";
  }
  // 改行をbrタグに変換して返す
  lines.shift();
  return lines.join("
");
}

function setMarker(datas) {
  var mk;
  var pop;
  for(var i=0 ; i<datas.length ; i++) {
    mk = L.marker(
      [datas[i].lat,datas[i].lng],
      {
        title: getTitle(datas[i].comment),
        alt: datas[i].tags[0]
      }
    ).on('click', function() {
      mk.bounce();
    });
    pop =
    "
"+getTitle(datas[i].comment)+"
"
    +""
    +"
Tags:";
    for (var j=0 ; j<datas[i].tags.length ; j++) {
      if (j > 0) pop+=", ";
      pop += datas[i].tags[j];
    }
    mk.bindPopup(pop);
    points.push(mk);
    mk.addTo(map);
  }
}

function setButtons() {
  var helloPopup = L.popup().setContent('Hello World!');

  L.easyButton('glyphicon-list', function(btn, map){
    sidebar.toggle();
  }).addTo( map ); // probably just `map`

  L.easyButton('glyphicon-search', function(btn, map){
      helloPopup.setLatLng(map.getCenter()).openOn(map);
  }).addTo( map ); // probably just `map`

  L.easyButton('glyphicon-floppy-disk', function(btn, map){
      helloPopup.setLatLng(map.getCenter()).openOn(map);
  }).addTo( map ); // probably just `map`
}

/**　渡されたデータの内容をサイドバーに列挙して、出力*/
function setSidebar(datas) {
  var authdate = "";
  sidebar = L.control.sidebar('data-list', {
    position: 'right'
  });
  map.addControl(sidebar);

  // データを列挙
  dispDatas = datas;
  var dlist = "";//"
";
  dlist += "
";
  for (var i=0 ; i<datas.length; i++) {
    dlist += "
";

    // 画像
    dlist += "";
    dlist += "";
    dlist += "	";

    // 情報欄
    dlist += "";

    dlist += getInfoRow(datas,i);

    // 列終わり
    dlist += "
";

  }
  dlist += "
";
  dlist += "";//"
";
  //
  $('#data-list').html(dlist);
  sidebar.show();
}

/**
 * 編集へ
 */
function changeEdit(idx) {
  var id = "#info"+idx;
  $(id).html(getInfoEditRow(dispDatas, idx));
}

/**
 * 情報パネルに戻る
 */
function backInfo(idx) {
  var id = "#info"+idx;
  $(id).html(getInfoRow(dispDatas, idx));
}

/**
 * 指定の配列の指定のインデックスの詳細を編集する右側のtdタグ内のHTMLを返す
 * @param [] datas データ配列
 * @param idx 作成するデータのインデックス
 */
function getInfoEditRow(datas, idx) {
  // 公開状況とタイトルとコメント
  var dlist = "
";
  var accessIcon = "";
  var accessLabel = "公開";
  var accessIcons = [
    "",
    ""
  ];

  //// 限定公開(glyphicon-user)
  if (datas[idx].access == "protected") {
      accessIcon = accessIcons[0];
      accessLabel = "限定公開";
  }
  //// 非公開(glyphicon-lock)
  else if (datas[idx].access == "private") {
    accessIcon = accessIcons[1];
    accessLabel = "非公開";
  }

  //// 切り替え
  dlist += "
";
  dlist += "<button class='btn btn-default dropdown-toggle btn-sm' type='button' id='access"+idx+"' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>";
  dlist += accessIcon+accessLabel;
  dlist += "";
  dlist += "</button>";
  dlist += "
";
  dlist += "
公開
";
  dlist += "
"+accessIcons[0]+"限定公開
";
  dlist += "
"+accessIcons[1]+"非公開
";
  dlist += "
";
  dlist += "
";
  dlist += "
";

  // タイトルとコメント
  dlist += "<textarea class='form-control input-sm' rows='3'>";
  dlist += datas[idx].comment;
  dlist += "</textarea>";

  // 付加情報
  dlist += "";
  // コメント者と日時
  // 入力者と日時
  dlist += "
";
  if (datas[idx].hasOwnProperty("author")) {
    dlist += "<input type='text' class='form-control input-sm' placeholder='作成者名' value='"+datas[idx].author+"' />";
  }
  dlist += "<input type='text' class='form-control input-sm' placeholder='2015/10/10 1:2:3' value='"+datas[idx].datetime+"' />
";

  // 緯度経度
  dlist += "
";
  dlist += "緯度";
  dlist += "
";
  dlist += "<input type='text' class='form-control input-sm' placeholder='35.151515' value='"+datas[idx].lat+"' />";
  dlist += "
";

  dlist += "経度";
  dlist += "
";
  dlist += "<input type='text' class='form-control input-sm' placeholder='139.151515' value='"+datas[idx].lng+"' />";
  dlist += "

";

  // タグ
  dlist += "
";
  dlist += "tags:";
  dlist += "
";
  dlist += "<input type='text' class='form-control input-sm' placeholder='例)カモ 鳥' value='";
  for (var j=0 ; j<datas[idx].tags.length ; j++) {
    if (j>0) {
      dlist += ' ';
    }
    dlist += datas[idx].tags[j];
  }
  dlist += "' />

";

  // 公開情報

  // ボタン配置
  dlist += "";
  //// 編集ボタン
  dlist += "<button type='button' class='btn btn-default btn-xs' aria-label='Edit' data-toggle='tooltip' data-placement='right' title='更新'";
  dlist += " onclick='backInfo("+idx+")'>";
  dlist += "";
  dlist += "</button>";
  //// キャンセルボタン
  dlist += "<button type='button' class='btn btn-default btn-xs' aria-label='Remove' data-toggle='tooltip' data-placement='right' title='キャンセル'";
  dlist += " onclick='backInfo("+idx+")'>";
  dlist += "";
  dlist += "</button>";
  dlist += "";

  dlist += "
";
  return dlist;
}

/**
 * 指定の配列の指定のインデックスの詳細を描画するためのtrタグで囲んだHTMLを返す
 * @param [] datas データ配列
 * @param idx 作成するデータのインデックス
 */
function getInfoRow(datas, idx) {
  // 公開状況とタイトルとコメント
  var dlist = "
";

  //// 限定公開(glyphicon-user)
  if (datas[idx].access == "protected") {
      dlist += "";
  }
  //// 非公開(glyphicon-lock)
  else if (datas[idx].access == "private") {
    dlist += "";
  }
  // タイトル
  dlist += ""+getTitle(datas[idx].comment)+"
";
  // コメント
  dlist += "
"+getComment(datas[idx].comment)+"
";

  // 付加情報
  dlist += "";
  // コメント者と日時
  // 入力者と日時
  dlist += "
";
  if (datas[idx].hasOwnProperty("author")) {
    dlist += ""+datas[idx].author+" ";
  }
  dlist += datas[idx].datetime+"
";

  // 緯度経度
  dlist += "lat,lng:"+datas[idx].lat+", "+datas[idx].lng;

  // タグ
  dlist += "
tags:";
  for (var j=0 ; j<datas[idx].tags.length ; j++) {
    dlist += " "+datas[idx].tags[j];
  }
  // ボタン配置
  dlist += "";
  //// 編集ボタン
  dlist += "<button type='button' class='btn btn-default btn-xs' aria-label='Edit' data-toggle='tooltip' data-placement='right' title='編集'";
  dlist += " onclick='changeEdit("+idx+")'>";
  dlist += "";
  dlist += "</button>";
  //// 削除ボタン
  dlist += "<button type='button' class='btn btn-default btn-xs' aria-label='Remove' data-toggle='tooltip' data-placement='right' title='削除'>";
  dlist += "";
  dlist += "</button>";
  dlist += "";

  dlist += "
";

  return dlist;
}
<|endoftext|>


<commit_before>var MockupFoundry = (function (document) {
  var MockupFoundry = function (el) {
    var canvas;
    if (typeof el === 'string') {
      canvas = document.getElementById (el);
    } else {
      canvas = el;
    }

    this.context = canvas.getContext ('2d');
    this.elements = [];
    this.opts = {
      'plane-scale': 1,
      'plane-translate-x': 0,
      'plane-translate-y': 0
    };
  };

  MockupFoundry.prototype.addElement = function (source, x, y) {
    var elem = {};
    elem.source = source || 'default.png'
    elem.x = x || 0;
    elem.y = y || 0;
    var img = new Image ();
    img.src = elem.source;
    elem.img = img;
    this.elements.push (elem);
    return this;
  };

  MockupFoundry.prototype.option = function (key, val) {
    this.opts[key] = val;
    return this;
  };

  MockupFoundry.prototype.render = function (type) {
    var context = this.context;
    /* plane options */
    context.scale (this.opts['plane-scale'], this.opts['plane-scale']);
    context.translate (this.opts['plane-translate-x'], this.opts['plane-translate-y']);

    context.save ();
    /* actual rendering */
    if (type === 'perspective') {
      context.scale (1, 0.5);
      context.rotate (-45/180*Math.PI);
    }
    context.save ()
    /* draw shadows */
    this.elements.forEach (function (element) {
      context.shadowColor = 'rgba(0,0,0,0.5)';
      context.shadowBlur = 30;
      if (type === 'perspective') {
        context.shadowOffsetY = 30;
      }
      context.fillStyle = 'rgb(255,255,255)';
      context.fillRect (element.x+10, element.y+10, 620, 1110);
    });
    /* draw mocks */
    context.restore ();
    this.elements.forEach (function (element) {
      context.drawImage (element.img, element.x, element.y);
    });

    /* draw edges */
    if (type === 'perspective') {
      var initialCanvas = document.createElement ('canvas');
      var initialContext = initialCanvas.getContext ('2d');
      this.elements.forEach (function (element) {
        var width = element.img.width;
        var height = element.img.height;
        var thickness = 15;

        /* rendering the initial picture to get the left and bottom pixels */
        var initialImage = element.img;
        initialCanvas.width = width;
        initialCanvas.height = height;
        initialContext.drawImage (initialImage, 0, 0, width, height);
        var initialImageData = initialContext.getImageData (0, 0, width, height);

        /* iterating over the imageData.data to get the actual pixels */
        var data = initialImageData.data;
        var dataLength = data.length;
        var leftPixels = [];
        var bottomPixels = [];
        var j = 0, k = 0;
        for (var i = 0; i < dataLength; i+=4) {
          if ((i/4)%width === 0) {
            leftPixels[j] = data[i];
            leftPixels[j+1] = data[i+1];
            leftPixels[j+2] = data[i+2];
            leftPixels[j+3] = data[i+3];
            j+=4;
          }
          if (i >= (dataLength - width*4)) {
            bottomPixels[k] = data[i];
            bottomPixels[k+1] = data[i+1];
            bottomPixels[k+2] = data[i+2];
            bottomPixels[k+3] = data[i+3];
            k+=4;
          }
        }
        /* left edge */
        var leftImageData = context.createImageData (thickness, height);
        var k = 0;
        for (var j = 0; j < leftPixels.length; j+=4) {
          for (var i = 0; i < thickness; i++) {
            leftImageData.data[k] = leftPixels[j];
            leftImageData.data[k+1] = leftPixels[j+1];
            leftImageData.data[k+2] = leftPixels[j+2];
            leftImageData.data[k+3] = leftPixels[j+3];
            k+=4;
          }
        }
        var leftCanvas = document.createElement ('canvas');
        var leftContext = leftCanvas.getContext ('2d');
        leftCanvas.width = thickness;
        leftCanvas.height = height;
        leftContext.putImageData (leftImageData, 0, 0);
        leftContext.fillStyle = 'rgba(0,0,0,0.35)';
        leftContext.fillRect (0, 0, thickness, height);
        context.save ();
        context.translate (element.x - thickness, element.y + thickness);
        context.transform (1, -1, 0, 1, 0, 0)
        context.drawImage (leftCanvas, 0, 0);
        context.restore ();

        /* bottom edge */
        var bottomImageData = context.createImageData (width, thickness);
        k = 0;
        for (var i = 0; i < thickness; i++) {
          for (var j = 0; j < bottomPixels.length; j+=4) {
            bottomImageData.data[k] = bottomPixels[j];
            bottomImageData.data[k+1] = bottomPixels[j+1];
            bottomImageData.data[k+2] = bottomPixels[j+2];
            bottomImageData.data[k+3] = bottomPixels[j+3];
            k+=4;
          }
        }
        var bottomCanvas = document.createElement ('canvas');
        bottomCanvas.width = width;
        bottomCanvas.height = thickness;
        var bottomContext = bottomCanvas.getContext ("2d");
        bottomContext.putImageData (bottomImageData, 0, 0);
        bottomContext.fillStyle = 'rgba(0,0,0,0.35)';
        bottomContext.fillRect (0, 0, width, thickness);
        context.save ();
        context.translate (element.x, element.y + height);
        context.transform (1, 0, -1, 1, 0, 0)
        context.drawImage (bottomCanvas, 0, 0);
        context.restore ();
      });
    }
    return this;
  };

  return MockupFoundry;
}) (document);
<commit_msg>add plane width and height parameters and change option to param<commit_after>var MockupFoundry = (function (document) {
  var MockupFoundry = function (el) {
    var canvas;
    if (typeof el === 'string') {
      canvas = document.getElementById (el);
    } else {
      canvas = el;
    }

    this.context = canvas.getContext ('2d');
    this.canvas = canvas;
    this.elements = [];
    this.params = {
      'plane-scale': 1,
      'plane-translate-x': 0,
      'plane-translate-y': 0,
      'plane-width': 1440,
      'plane-height': 900
    };
  };

  MockupFoundry.prototype.addElement = function (source, x, y) {
    var elem = {};
    elem.source = source || 'default.png'
    elem.x = x || 0;
    elem.y = y || 0;
    var img = new Image ();
    img.src = elem.source;
    elem.img = img;
    this.elements.push (elem);
    return this;
  };

  MockupFoundry.prototype.param = function (key, val) {
    this.params[key] = val;
    return this;
  };

  MockupFoundry.prototype.render = function (type) {
    var context = this.context;
    /* plane options */
    this.canvas.width = this.params['plane-width'];
    this.canvas.height = this.params['plane-height'];
    context.scale (this.params['plane-scale'], this.params['plane-scale']);
    context.translate (this.params['plane-translate-x'], this.params['plane-translate-y']);

    context.save ();
    /* actual rendering */
    if (type === 'perspective') {
      context.scale (1, 0.5);
      context.rotate (-45/180*Math.PI);
    }
    context.save ()
    /* draw shadows */
    this.elements.forEach (function (element) {
      context.shadowColor = 'rgba(0,0,0,0.5)';
      context.shadowBlur = 30;
      if (type === 'perspective') {
        context.shadowOffsetY = 30;
      }
      context.fillStyle = 'rgb(255,255,255)';
      context.fillRect (element.x+10, element.y+10, element.img.width - 20, element.img.height - 20);
    });
    /* draw mocks */
    context.restore ();
    this.elements.forEach (function (element) {
      context.drawImage (element.img, element.x, element.y);
    });

    /* draw edges */
    if (type === 'perspective') {
      var initialCanvas = document.createElement ('canvas');
      var initialContext = initialCanvas.getContext ('2d');
      this.elements.forEach (function (element) {
        var width = element.img.width;
        var height = element.img.height;
        var thickness = 15;

        /* rendering the initial picture to get the left and bottom pixels */
        var initialImage = element.img;
        initialCanvas.width = width;
        initialCanvas.height = height;
        initialContext.drawImage (initialImage, 0, 0, width, height);
        var initialImageData = initialContext.getImageData (0, 0, width, height);

        /* iterating over the imageData.data to get the actual pixels */
        var data = initialImageData.data;
        var dataLength = data.length;
        var leftPixels = [];
        var bottomPixels = [];
        var j = 0, k = 0;
        for (var i = 0; i < dataLength; i+=4) {
          if ((i/4)%width === 0) {
            leftPixels[j] = data[i];
            leftPixels[j+1] = data[i+1];
            leftPixels[j+2] = data[i+2];
            leftPixels[j+3] = data[i+3];
            j+=4;
          }
          if (i >= (dataLength - width*4)) {
            bottomPixels[k] = data[i];
            bottomPixels[k+1] = data[i+1];
            bottomPixels[k+2] = data[i+2];
            bottomPixels[k+3] = data[i+3];
            k+=4;
          }
        }
        /* left edge */
        var leftImageData = context.createImageData (thickness, height);
        var k = 0;
        for (var j = 0; j < leftPixels.length; j+=4) {
          for (var i = 0; i < thickness; i++) {
            leftImageData.data[k] = leftPixels[j];
            leftImageData.data[k+1] = leftPixels[j+1];
            leftImageData.data[k+2] = leftPixels[j+2];
            leftImageData.data[k+3] = leftPixels[j+3];
            k+=4;
          }
        }
        var leftCanvas = document.createElement ('canvas');
        var leftContext = leftCanvas.getContext ('2d');
        leftCanvas.width = thickness;
        leftCanvas.height = height;
        leftContext.putImageData (leftImageData, 0, 0);
        leftContext.fillStyle = 'rgba(0,0,0,0.35)';
        leftContext.fillRect (0, 0, thickness, height);
        context.save ();
        context.translate (element.x - thickness, element.y + thickness);
        context.transform (1, -1, 0, 1, 0, 0)
        context.drawImage (leftCanvas, 0, 0);
        context.restore ();

        /* bottom edge */
        var bottomImageData = context.createImageData (width, thickness);
        k = 0;
        for (var i = 0; i < thickness; i++) {
          for (var j = 0; j < bottomPixels.length; j+=4) {
            bottomImageData.data[k] = bottomPixels[j];
            bottomImageData.data[k+1] = bottomPixels[j+1];
            bottomImageData.data[k+2] = bottomPixels[j+2];
            bottomImageData.data[k+3] = bottomPixels[j+3];
            k+=4;
          }
        }
        var bottomCanvas = document.createElement ('canvas');
        bottomCanvas.width = width;
        bottomCanvas.height = thickness;
        var bottomContext = bottomCanvas.getContext ("2d");
        bottomContext.putImageData (bottomImageData, 0, 0);
        bottomContext.fillStyle = 'rgba(0,0,0,0.35)';
        bottomContext.fillRect (0, 0, width, thickness);
        context.save ();
        context.translate (element.x, element.y + height);
        context.transform (1, 0, -1, 1, 0, 0)
        context.drawImage (bottomCanvas, 0, 0);
        context.restore ();
      });
    }
    return this;
  };

  return MockupFoundry;
}) (document);
<|endoftext|>


<commit_before>var count = document.getElementById("count");
var canvas = document.getElementById("canvas");
var dc = canvas.getContext("2d");

var ms = new Array();

var gen_color = function(){
  return "rgb(" +
    parseInt(Math.random()*255) + "," +
    parseInt(Math.random()*255) + "," +
    parseInt(Math.random()*255) + ")";
}
var on_click = function(){
  for(i=0;i<count.value;i++){
    obj = {
      x : 640, y : 100,
      sx : Math.random() * 10 - 5, sy : Math.random() * 10,
      alpha : 255,
      size : parseInt(Math.random() * 20 + 20),
      color : gen_color()
    }
    ms.push( obj );
  }
}

setInterval( function(){
  dc.clearRect(0,0,1280,960);
  //dc.globalCompositeOperation = "lighter";

  for( var i in ms ){
    var obj = ms[i];

    dc.font = obj.size + "px Arial";
    dc.globalAlpha = obj.alpha / 255;
    dc.fillStyle = obj.color;
    dc.fillText( "민수천재야", obj.x,obj.y );

    obj.x += obj.sx;
    obj.y += obj.sy;
    obj.alpha -= 2.5;

    if( obj.alpha == 0 ){
      ms.splice( i, 1 );
    }
  }

  dc.fill();
}, 33 );
<commit_msg>Update minsoo.js<commit_after>var count = document.getElementById("count");
var canvas = document.getElementById("canvas");
var dc = canvas.getContext("2d");

var ms = new Array();

var gen_color = function(){
  return "rgb(" +
    parseInt(Math.random()*255) + "," +
    parseInt(Math.random()*255) + "," +
    parseInt(Math.random()*255) + ")";
}
var on_click = function(){
  for(i=0;i<count.value;i++){
    obj = {
      x : 640, y : 100,
      sx : Math.random() * 10 - 5, sy : Math.random() * 10,
      alpha : 255,
      size : parseInt(Math.random() * 20 + 20),
      color : gen_color()
    }
    ms.push( obj );
  }
}

setInterval( function(){
  dc.clearRect(0,0,1280,960);
  dc.globalCompositeOperation = "darker";

  for( var i in ms ){
    var obj = ms[i];

    dc.font = obj.size + "px Arial";
    dc.globalAlpha = obj.alpha / 255;
    dc.fillStyle = obj.color;
    dc.fillText( "민수천재야", obj.x,obj.y );

    obj.x += obj.sx;
    obj.y += obj.sy;
    obj.alpha -= 2.5;

    if( obj.alpha == 0 ){
      ms.splice( i, 1 );
    }
  }

  dc.globalCompositeOperation = "copy";

  var grd = dc.createRadialGradient(75,50,5,90,60,100);
  grd.addColorStop(0,"red");
  grd.addColorStop(1,"white");

  dc.fillStyle = grd;
  dc.beginPath();
    dc.arc(95,50,400,0,2*Math.PI);
  dc.closePath();

  dc.fill();
}, 33 );
<|endoftext|>


<commit_before>// Builds content service instance based on source media.

'use strict';

var _ = require('underscore');
var elmoCS = require('./content-services/elmo-content-service');
var facebookCS = require('./content-services/facebook-content-service');
var rssCS = require('./content-services/rss-content-service');
var twitterCS = require('./content-services/twitter-content-service');

var contentServices = {
  elmo: elmoCS,
  facebook: facebookCS,
  rss: rssCS,
  twitter: twitterCS
};

var ContentServiceFactory = function() {};

// Creates a new content service to match the given source.
ContentServiceFactory.prototype.create = function(source) {
  var Service = contentServices[source.media];

  // Content services use only the lastReportDate, url, and keywords params.
  var basicSource = _.pick(source, 'lastReportDate', 'url', 'keywords');

  if (Service.fetchType === 'subscribe') {
    // There should only be one content service for this media
    return Service;
  }

  return new Service(basicSource);
};

// Export a new instance, ensuring a singleton
module.exports = new ContentServiceFactory();
<commit_msg>Bug fix: dummy content service was not handled<commit_after>// Builds content service instance based on source media.

'use strict';

var _ = require('underscore');
var elmoCS = require('./content-services/elmo-content-service');
var facebookCS = require('./content-services/facebook-content-service');
var rssCS = require('./content-services/rss-content-service');
var twitterCS = require('./content-services/twitter-content-service');
var dummyCS = require('./content-services/dummy-content-service');
var dummyPullCS = require('./content-services/dummy-pull-content-service');

var contentServices = {
  elmo: elmoCS,
  facebook: facebookCS,
  rss: rssCS,
  twitter: twitterCS,
  dummy: dummyCS,
  'dummy-pull': dummyPullCS,
};

var ContentServiceFactory = function() {};

// Creates a new content service to match the given source.
ContentServiceFactory.prototype.create = function(source) {
  var Service = contentServices[source.media];
  /*
  console.log("source");
  console.log(source);
  console.log("Service");
  console.log(Service);
  */
  // Content services use only the lastReportDate, url, and keywords params.
  var basicSource = _.pick(source, 'lastReportDate', 'url', 'keywords');

  if (Service.fetchType === 'subscribe') {
    // There should only be one content service for this media
    return Service;
  }

  return new Service(basicSource);
};

// Export a new instance, ensuring a singleton
module.exports = new ContentServiceFactory();
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
      files: ['app/**/*.js', 'public/scripts/**/*.js']
    },
    concurrent: {
      start: {
        tasks: ['nodemon', 'watch'],
        options: {
          logConcurrentOutput: true
        }
      }
    },
    watch: {
      options: {
        livereload: true,
        dateFormat: function(time) {
          grunt.log.writeln('The watch finished in ' + time + 'ms at' + (new Date()).toString());
          grunt.log.writeln('Waiting for more changes...');
        },
      },
      scripts: {
        files: ['public/scripts/*.js'],
        tasks: ['browserify'],
        options: {
          debounceDelay: 250
        }
      },
      layout: {
        files: ['public/images/*', 'public/stylesheets/*', 'app/views/*']
      }
    },
    nodemon: {
      dev: {
        options: {
          file: 'app.js',
          nodeArgs: ['--debug']
        }
      }
    },
    browserify: {
      basic: {
        src: ['public/scripts/main.js'],
        dest: 'public/build/build.js'
      }
    }
  });

  require('load-grunt-tasks')(grunt, 'grunt-*');
  grunt.registerTask('default', ['browserify', 'concurrent']);
};
<commit_msg>made the  statement an itty bit more terse<commit_after>'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
      files: ['app/**/*.js', 'public/scripts/**/*.js']
    },
    concurrent: {
      start: {
        tasks: ['nodemon', 'watch'],
        options: {
          logConcurrentOutput: true
        }
      }
    },
    watch: {
      options: {
        livereload: true,
        dateFormat: function(time) {
          grunt.log.writeln('The watch finished in ' + time + 'ms at' + (new Date()).toString());
          grunt.log.writeln('Waiting for more changes...');
        },
      },
      scripts: {
        files: ['public/scripts/*.js'],
        tasks: ['browserify'],
        options: {
          debounceDelay: 250
        }
      },
      layout: {
        files: ['public/images/*', 'public/stylesheets/*', 'app/views/*']
      }
    },
    nodemon: {
      dev: {
        options: {
          file: 'app.js',
          nodeArgs: ['--debug']
        }
      }
    },
    browserify: {
      basic: {
        src: ['public/scripts/main.js'],
        dest: 'public/build/build.js'
      }
    }
  });

  require('load-grunt-tasks')(grunt);
  grunt.registerTask('default', ['browserify', 'concurrent']);
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var initGulpTasks = require('react-component-gulp-tasks');

/**
 * Tasks are added by the react-component-gulp-tasks package
 *
 * See https://github.com/JedWatson/react-component-gulp-tasks
 * for documentation.
 *
 * You can also add your own additional gulp tasks if you like.
 */

var taskConfig = {

	component: {
		name: '<%= componentName %>',
		dependencies: [
			'classnames',
			'react'
		],
		lib: 'lib'
	},

	example: {
		src: 'example/src',
		dist: 'example/dist',
		files: [
			'index.html',
			'.gitignore'
		],
		scripts: [
			'example.js'
		],
		less: [
			'example.less'
		]
	}

};

initGulpTasks(gulp, taskConfig);
<commit_msg>Fix React double inclusion in the examples<commit_after>var gulp = require('gulp');
var initGulpTasks = require('react-component-gulp-tasks');

/**
 * Tasks are added by the react-component-gulp-tasks package
 *
 * See https://github.com/JedWatson/react-component-gulp-tasks
 * for documentation.
 *
 * You can also add your own additional gulp tasks if you like.
 */

var taskConfig = {

	component: {
		name: '<%= componentName %>',
		dependencies: [
			'classnames',
			'react',
			'react-dom'
		],
		lib: 'lib'
	},

	example: {
		src: 'example/src',
		dist: 'example/dist',
		files: [
			'index.html',
			'.gitignore'
		],
		scripts: [
			'example.js'
		],
		less: [
			'example.less'
		]
	}

};

initGulpTasks(gulp, taskConfig);
<|endoftext|>


<commit_before>'use strict'
/*
Usage:

node scripts/changelog.js [comittish]

Generates changelog entries in our format as best as its able based on
commits starting at comittish, or if that's not passed, master.

Ordinarily this is run via the gen-changelog shell script, which appends
the result to the changelog.

*/
const execSync = require('child_process').execSync
const branch = process.argv[2] || 'master'
const log = execSync(`git log --pretty='format:%h %H%d %s (%aN)%n%b%n---%n' ${branch}...`).toString().split(/\n/)
const authormap = {
  'Rebecca Turner': 'iarna',
  'Forrest L Norvell': 'othiym23',
  'Kyle Mitchell': 'kemitchell',
  'Chris Rebert': 'cvrebert',
  'Kat Marchán': 'zkat'
}

main()

function print_commit (c) {
  let m
  console.log(`* [\`${c.shortid}\`](https://github.com/npm/npm/commit/${c.fullid})`)
  if (c.fixes) {
    console.log(`  [#${c.fixes}](https://github.com/npm/npm/issues/${c.fixes})`)
  } else if (c.prurl && (m = c.prurl.match(/https:\/\/github.com\/([^/]+\/[^/]+)\/pull\/(\d+)/))) {
    let repo = m[1]
    let prid = m[2]
    if (repo !== 'npm/npm') {
      console.log(`  [${repo}#${prid}](${c.prurl})`)
    } else {
      console.log(`  [#${prid}](${c.prurl})`)
    }
  } else if (c.prurl) {
    console.log(`  [#](${c.prurl})`)
  }
  let msg = c.message
    .replace(/^\s+/mg, '')
    .replace(/^[-a-z]+: /, '')
    .replace(/^/mg, '  ')
    .replace(/\n$/, '')
  // backtickify package@version
    .replace(/^(\s*[^@\s]+@\d+[.]\d+[.]\d+)(\s*\S)/g, '$1:$2')
    .replace(/\b([^@\s]+@\d+[.]\d+[.]\d+)\b/g, '`$1`')
  // linkify commitids
    .replace(/\b([a-f0-9]{7,8})\b/g, '[`$1`](https://github.com/npm/npm/commit/$1)')
    .replace(/\b#(\d+)\b/g, '[#$1](https://github.com/npm/npm/issues/$1)')
  console.log(msg)
  if (c.credit) {
    console.log(`  ([@${c.credit}](https://github.com/${c.credit}))`)
  } else {
    console.log(`  ([@${c.author}](https://github.com/${c.author}))`)
  }
}

function main () {
  let commit
  log.forEach(function (line) {
    let m
    /*eslint no-cond-assign:0*/
    if (/^---$/.test(line)) {
      print_commit(commit)
    } else if (m = line.match(/^([a-f0-9]{7}) ([a-f0-9]+) (?:[(]([^)]+)[)] )?(.*?) [(](.*?)[)]/)) {
      commit = {
        shortid: m[1],
        fullid: m[2],
        branch: m[3],
        message: m[4],
        author: authormap[m[5]] || m[5],
        prurl: null,
        fixes: null,
        credit: null
      }
    } else if (m = line.match(/^PR-URL: (.*)/)) {
      commit.prurl = m[1]
    } else if (m = line.match(/^Credit: @(.*)/)) {
      commit.credit = m[1]
    } else if (m = line.match(/^Fixes: #(.*)/)) {
      commit.fixes = m[1]
    } else if (m = line.match(/^Reviewed-By: @(.*)/)) {
      commit.reviewed = m[1]
    } else if (/\S/.test(line)) {
      commit.message += `\n${line}`
    }
  })
}
<commit_msg>gen-changelog: Support multiple credits<commit_after>'use strict'
/*
Usage:

node scripts/changelog.js [comittish]

Generates changelog entries in our format as best as its able based on
commits starting at comittish, or if that's not passed, master.

Ordinarily this is run via the gen-changelog shell script, which appends
the result to the changelog.

*/
const execSync = require('child_process').execSync
const branch = process.argv[2] || 'master'
const log = execSync(`git log --pretty='format:%h %H%d %s (%aN)%n%b%n---%n' ${branch}...`).toString().split(/\n/)
const authormap = {
  'Rebecca Turner': 'iarna',
  'Forrest L Norvell': 'othiym23',
  'Kyle Mitchell': 'kemitchell',
  'Chris Rebert': 'cvrebert',
  'Kat Marchán': 'zkat'
}

main()

function print_commit (c) {
  let m
  console.log(`* [\`${c.shortid}\`](https://github.com/npm/npm/commit/${c.fullid})`)
  if (c.fixes) {
    console.log(`  [#${c.fixes}](https://github.com/npm/npm/issues/${c.fixes})`)
  } else if (c.prurl && (m = c.prurl.match(/https:\/\/github.com\/([^/]+\/[^/]+)\/pull\/(\d+)/))) {
    let repo = m[1]
    let prid = m[2]
    if (repo !== 'npm/npm') {
      console.log(`  [${repo}#${prid}](${c.prurl})`)
    } else {
      console.log(`  [#${prid}](${c.prurl})`)
    }
  } else if (c.prurl) {
    console.log(`  [#](${c.prurl})`)
  }
  let msg = c.message
    .replace(/^\s+/mg, '')
    .replace(/^[-a-z]+: /, '')
    .replace(/^/mg, '  ')
    .replace(/\n$/, '')
  // backtickify package@version
    .replace(/^(\s*[^@\s]+@\d+[.]\d+[.]\d+)(\s*\S)/g, '$1:$2')
    .replace(/\b([^@\s]+@\d+[.]\d+[.]\d+)\b/g, '`$1`')
  // linkify commitids
    .replace(/\b([a-f0-9]{7,8})\b/g, '[`$1`](https://github.com/npm/npm/commit/$1)')
    .replace(/\b#(\d+)\b/g, '[#$1](https://github.com/npm/npm/issues/$1)')
  console.log(msg)
  if (c.credit) {
    c.credit.forEach(function (credit) {
      console.log(`  ([@${credit}](https://github.com/${credit}))`)
    })
  } else {
    console.log(`  ([@${c.author}](https://github.com/${c.author}))`)
  }
}

function main () {
  let commit
  log.forEach(function (line) {
    let m
    /*eslint no-cond-assign:0*/
    if (/^---$/.test(line)) {
      print_commit(commit)
    } else if (m = line.match(/^([a-f0-9]{7}) ([a-f0-9]+) (?:[(]([^)]+)[)] )?(.*?) [(](.*?)[)]/)) {
      commit = {
        shortid: m[1],
        fullid: m[2],
        branch: m[3],
        message: m[4],
        author: authormap[m[5]] || m[5],
        prurl: null,
        fixes: null,
        credit: null
      }
    } else if (m = line.match(/^PR-URL: (.*)/)) {
      commit.prurl = m[1]
    } else if (m = line.match(/^Credit: @(.*)/)) {
      if (!commit.credit) commit.credit = []
      commit.credit.push(m[1])
    } else if (m = line.match(/^Fixes: #(.*)/)) {
      commit.fixes = m[1]
    } else if (m = line.match(/^Reviewed-By: @(.*)/)) {
      commit.reviewed = m[1]
    } else if (/\S/.test(line)) {
      commit.message += `\n${line}`
    }
  })
}
<|endoftext|>


<commit_before>define(['jquery', 'config', 'citeproc', 'linkify'], function ($, config) {

    var citations = null;

    function getCiteKeyFromNote(note) {

        var matches = /^citekey: *(.+) *$/gm.exec(note);
        return matches[1];
    }

    function fetch(start) {
        $.ajax({
            url: 'https://api.zotero.org/users/' + config.citation.zotero_id + '/items?format=csljson&limit=99&start=' + start,
            beforeSend: function (request) {
                request.setRequestHeader("Zotero-API-Version", "2");
            },
            dataType: 'json',
            async: false,
            success: function (result) {

                result.items.forEach(function (item, index) {

                    var citekey = getCiteKeyFromNote(item.note);

                    if (citekey != null) {
                        citations[citekey] = item;
                        citations[citekey].id = citekey;
                    } else {
                        console.log("no citekey was found for " + item);
                        citations[item.id] = item;
                    }
                })
            },
            error: function (e) {
                console.log("failed to contact zotero.org to fetch citation:" + alias, e);
            }
        });
    }

    function loadZoteroLibrary() {

        var local_storage_key = 'citations_' + config.citation.zotero_id;
        var storage_supported = typeof(Storage) != "undefined";
        if (storage_supported) {
            citations = JSON.parse(localStorage.getItem(local_storage_key));
        }

        if (citations == null) {
            console.log('fetching citation database from zotero');
            citations = {};
            var response;
            $.ajax({
                url: 'https://api.zotero.org/users/' + config.citation.zotero_id + '/items?format=keys',
                dataType: 'text',
                async: false,
                success: function (result) {
                    response = result.trim().split('\n');
                },
                error: function (e) {
                    console.log("failed to load " + this.url, e);
                }
            });

            var to_be_fetched = response.length;
            var fetch_count = 0;
            while (to_be_fetched > 0) {

                fetch(fetch_count * 99);
                fetch_count++;
                to_be_fetched -= 99;
            }

            if (storage_supported) {
                localStorage.setItem(local_storage_key, JSON.stringify(citations));
            }
        }
    }

    var system = {
        retrieveLocale: function (lang) {
            var locale;
            $.ajax({
                url: 'https://cdn.rawgit.com/citation-style-language/locales/master/locales-' + lang + '.xml',
                dataType: 'text',
                async: false,
                success: function (result) {
                    locale = result;
                },
                error: function (e) {
                    console.log("failed to load " + this.url, e);
                }
            });
            return locale
        },

        retrieveItem: function (id) {
            if (citations[id] == undefined) {
                console.log("failed to find citation with key " + id);
                return null;
            } else {
                return citations[id];
            }
        }
    };

    var csl;
    $.ajax({
        url: 'https://cdn.rawgit.com/citation-style-language/styles/master/' + config.citation.style + '.csl',
        dataType: 'text',
        async: false,
        success: function (result) {
            console.log("loaded " + this.url);
            csl = result;
        },
        error: function (e) {
            console.log("failed to load " + this.url, e);
        }
    });

    var processor = new CSL.Engine(system, csl, config.citation.locale);
    loadZoteroLibrary();
    var citekeys = Object.keys(citations);
    processor.updateItems(citekeys);

    return {
        database: citations,
        processor: processor,
        cite: function (cite_object) {
            return this.processor.appendCitationCluster(cite_object, true)[0][1];
        },
        renderBibliography: function () {

            var bibliography = this.processor.makeBibliography();
            var bib_body = $(bibliography[0].bibstart + bibliography[0].bibend);
            bibliography[1].forEach(function (entry_html, index) {

                var entry = $(entry_html);
                entry.linkify();
                entry.attr("id", 'cite_' + bibliography[0].entry_ids[index])
                bib_body.append(entry);
            });

            return bib_body.html();

        },
        getItem: function (id) {
            return system.retrieveItem(id);
        },
        getItemBib: function (id) {
            this.processor.setOutputFormat('text');
            var select = this.processor.makeBibliography({
                "select": [
                    {
                        "field": "id",
                        "value": id
                    }
                ]
            });
            this.processor.setOutputFormat('html');
            return select[1][0];
        }
    }
});<commit_msg>tidied ajax call with custom header<commit_after>define(['jquery', 'config', 'citeproc', 'linkify'], function ($, config) {

    var citations = null;

    function getCiteKeyFromNote(note) {

        var matches = /^citekey: *(.+) *$/gm.exec(note);
        return matches[1];
    }

    function fetch(start) {
        $.ajax({
            url: 'https://api.zotero.org/users/' + config.citation.zotero_id + '/items?format=csljson&limit=99&start=' + start,
            headers: {
                "Zotero-API-Version": "2"
            },
            dataType: 'json',
            async: false,
            success: function (result) {

                result.items.forEach(function (item, index) {

                    var citekey = getCiteKeyFromNote(item.note);

                    if (citekey != null) {
                        citations[citekey] = item;
                        citations[citekey].id = citekey;
                    } else {
                        console.log("no citekey was found for " + item);
                        citations[item.id] = item;
                    }
                })
            },
            error: function (e) {
                console.log("failed to contact zotero.org to fetch citation:" + alias, e);
            }
        });
    }

    function loadZoteroLibrary() {

        var local_storage_key = 'citations_' + config.citation.zotero_id;
        var storage_supported = typeof(Storage) != "undefined";
        if (storage_supported) {
            citations = JSON.parse(localStorage.getItem(local_storage_key));
        }

        if (citations == null) {
            console.log('fetching citation database from zotero');
            citations = {};
            var response;
            $.ajax({
                url: 'https://api.zotero.org/users/' + config.citation.zotero_id + '/items?format=keys',
                dataType: 'text',
                async: false,
                success: function (result) {
                    response = result.trim().split('\n');
                },
                error: function (e) {
                    console.log("failed to load " + this.url, e);
                }
            });

            var to_be_fetched = response.length;
            var fetch_count = 0;
            while (to_be_fetched > 0) {

                fetch(fetch_count * 99);
                fetch_count++;
                to_be_fetched -= 99;
            }

            if (storage_supported) {
                localStorage.setItem(local_storage_key, JSON.stringify(citations));
            }
        }
    }

    var system = {
        retrieveLocale: function (lang) {
            var locale;
            $.ajax({
                url: 'https://cdn.rawgit.com/citation-style-language/locales/master/locales-' + lang + '.xml',
                dataType: 'text',
                async: false,
                success: function (result) {
                    locale = result;
                },
                error: function (e) {
                    console.log("failed to load " + this.url, e);
                }
            });
            return locale
        },

        retrieveItem: function (id) {
            if (citations[id] == undefined) {
                console.log("failed to find citation with key " + id);
                return null;
            } else {
                return citations[id];
            }
        }
    };

    var csl;
    $.ajax({
        url: 'https://cdn.rawgit.com/citation-style-language/styles/master/' + config.citation.style + '.csl',
        dataType: 'text',
        async: false,
        success: function (result) {
            console.log("loaded " + this.url);
            csl = result;
        },
        error: function (e) {
            console.log("failed to load " + this.url, e);
        }
    });

    var processor = new CSL.Engine(system, csl, config.citation.locale);
    loadZoteroLibrary();
    var citekeys = Object.keys(citations);
    processor.updateItems(citekeys);

    return {
        database: citations,
        processor: processor,
        cite: function (cite_object) {
            return this.processor.appendCitationCluster(cite_object, true)[0][1];
        },
        renderBibliography: function () {

            var bibliography = this.processor.makeBibliography();
            var bib_body = $(bibliography[0].bibstart + bibliography[0].bibend);
            bibliography[1].forEach(function (entry_html, index) {

                var entry = $(entry_html);
                entry.linkify();
                entry.attr("id", 'cite_' + bibliography[0].entry_ids[index])
                bib_body.append(entry);
            });

            return bib_body.html();

        },
        getItem: function (id) {
            return system.retrieveItem(id);
        },
        getItemBib: function (id) {
            this.processor.setOutputFormat('text');
            var select = this.processor.makeBibliography({
                "select": [
                    {
                        "field": "id",
                        "value": id
                    }
                ]
            });
            this.processor.setOutputFormat('html');
            return select[1][0];
        }
    }
});<|endoftext|>


<commit_before>/**
 * See routes defined in `config.json`.
 */

var Joi = require('joi');
var Promise = require('es6-promise').Promise;

var utils = require('../../lib/utils');
var Game = require('../../lib/models/game').Game;

var validate = utils.promisify(Joi.validate);  // Promise-based `Joi.validate`

var gameKeys = {
  // Game Descripion is optional.
  description: Joi.string().example('Mario Bros. is a sweet adventure game.'),

  // Game URL must start with `https://` or `http://`.
  game_url: Joi.string().regex(/^https?:\/\//).required()
    .example('http://nintendo.com/mario-bros/'),

  // Game Name cannot be longer than 150 characters long.
  name: Joi.string().max(150).required()
    .example('Mario Bros.'),

  // Game Slug cannot be all digits, all underscores, or all hyphens
  // and must contain only letters, numbers, underscores, and hyphens.
  // TODO: Throw an error if `slug` is already taken.
  slug: Joi.string().regex(/^(?!\d*$)(?!_*$)(?!-*$)[\w-]+$/).required()
    .example('mario-bros')
};

// Define schema for JSON payloads. (Run `Joi.describe` to see examples.)
var gameSchema = Joi.object().keys(gameKeys).example({
  description: 'Mario Bros. is a sweet adventure game.'
  game_url: 'http://nintendo.com/mario-bros/',
  name: 'Mario Bros.',
  slug: 'mario-bros',
});

// For PATCH, use the same schema except every field is optional.
var gameKeysPatch = {};
Object.keys(gameKeys).forEach(function (key) {
  gameKeysPatch[key] = gameKeys[key].optional();
});

var gameSchemaPatch = Joi.object().keys(gameKeysPatch);

/**
 * GET all games.
 */
exports.all = function *() {
  var response = new utils.Response(this);

  yield Game.all()
  .then(response.success)
  .catch(response.dbError);
};

/**
 * POST a new game.
 */
exports.create = function *() {
  var payload = this.request.body;
  var response = new utils.Response(this);

  yield validate(payload, gameSchema, {abortEarly: false})
  .then(function () {
    return Game.create(payload)
    .then(response.success, response.validationError)
    .catch(response.dbError);
  }, response.validationError);
};

/**
 * GET a single game.
 */
exports.get = function *() {
  var response = new utils.Response(this);
  var slug = this.params.slug;

  // Return 200 with game data if the slug exists.
  yield Game.get({slug: slug})
  .then(response.success)
  .catch(function (err) {
    utils.CaughtResponse(response, err);
  });
};

/**
 * PATCH a single game (change only the fields supplied).
 */
exports.update = function *() {
  var payload = this.request.body;
  var response = new utils.Response(this);

  var oldSlug = this.params.slug;
  // Use the new slug or the old slug, depending on whether's it in the payload.
  var newSlug = 'slug' in payload ? payload.slug : oldSlug;

  yield validate(payload, gameSchemaPatch, {abortEarly: false})
  .then(function () {
    return Game.get({slug: oldSlug})
    .then(function (gameModel) {
      return Game.update(gameModel, payload);
    })
    .then(function (updateResponse) {
      // Return 200 with success.
      response.success();
    });
  }, response.validationError)
  .catch(function (err) {
    utils.CaughtResponse(response, err);
  });
};

/**
 * DELETE a single game.
 */
exports.delete = function *() {
  var response = new utils.Response(this);
  var slug = this.params.slug;

  yield Game.get({slug: slug})
  .then(function (gameModel) {
    return Game.delete(gameModel);
  })
  .then(function (deleteResponse) {
    if (deleteResponse === 1) {
      // Return 200 with success.
      response.success();
    } else {
      // Return 500 with error.
      response.dbError('Unexpected response upon deletion: ' +
        deleteResponse);
    }
  })
  .catch(function (err) {
    utils.CaughtResponse(response, err);
  });
};
<commit_msg>fix typo in game schema<commit_after>/**
 * See routes defined in `config.json`.
 */

var Joi = require('joi');
var Promise = require('es6-promise').Promise;

var utils = require('../../lib/utils');
var Game = require('../../lib/models/game').Game;

var validate = utils.promisify(Joi.validate);  // Promise-based `Joi.validate`

var gameKeys = {
  // Game Descripion is optional.
  description: Joi.string().example('Mario Bros. is a sweet adventure game.'),

  // Game URL must start with `https://` or `http://`.
  game_url: Joi.string().regex(/^https?:\/\//).required()
    .example('http://nintendo.com/mario-bros/'),

  // Game Name cannot be longer than 150 characters long.
  name: Joi.string().max(150).required()
    .example('Mario Bros.'),

  // Game Slug cannot be all digits, all underscores, or all hyphens
  // and must contain only letters, numbers, underscores, and hyphens.
  // TODO: Throw an error if `slug` is already taken.
  slug: Joi.string().regex(/^(?!\d*$)(?!_*$)(?!-*$)[\w-]+$/).required()
    .example('mario-bros')
};

// Define schema for JSON payloads. (Run `Joi.describe` to see examples.)
var gameSchema = Joi.object().keys(gameKeys).example({
  description: 'Mario Bros. is a sweet adventure game.',
  game_url: 'http://nintendo.com/mario-bros/',
  name: 'Mario Bros.',
  slug: 'mario-bros',
});

// For PATCH, use the same schema except every field is optional.
var gameKeysPatch = {};
Object.keys(gameKeys).forEach(function (key) {
  gameKeysPatch[key] = gameKeys[key].optional();
});

var gameSchemaPatch = Joi.object().keys(gameKeysPatch);

/**
 * GET all games.
 */
exports.all = function *() {
  var response = new utils.Response(this);

  yield Game.all()
  .then(response.success)
  .catch(response.dbError);
};

/**
 * POST a new game.
 */
exports.create = function *() {
  var payload = this.request.body;
  var response = new utils.Response(this);

  yield validate(payload, gameSchema, {abortEarly: false})
  .then(function () {
    return Game.create(payload)
    .then(response.success, response.validationError)
    .catch(response.dbError);
  }, response.validationError);
};

/**
 * GET a single game.
 */
exports.get = function *() {
  var response = new utils.Response(this);
  var slug = this.params.slug;

  // Return 200 with game data if the slug exists.
  yield Game.get({slug: slug})
  .then(response.success)
  .catch(function (err) {
    utils.CaughtResponse(response, err);
  });
};

/**
 * PATCH a single game (change only the fields supplied).
 */
exports.update = function *() {
  var payload = this.request.body;
  var response = new utils.Response(this);

  var oldSlug = this.params.slug;
  // Use the new slug or the old slug, depending on whether's it in the payload.
  var newSlug = 'slug' in payload ? payload.slug : oldSlug;

  yield validate(payload, gameSchemaPatch, {abortEarly: false})
  .then(function () {
    return Game.get({slug: oldSlug})
    .then(function (gameModel) {
      return Game.update(gameModel, payload);
    })
    .then(function (updateResponse) {
      // Return 200 with success.
      response.success();
    });
  }, response.validationError)
  .catch(function (err) {
    utils.CaughtResponse(response, err);
  });
};

/**
 * DELETE a single game.
 */
exports.delete = function *() {
  var response = new utils.Response(this);
  var slug = this.params.slug;

  yield Game.get({slug: slug})
  .then(function (gameModel) {
    return Game.delete(gameModel);
  })
  .then(function (deleteResponse) {
    if (deleteResponse === 1) {
      // Return 200 with success.
      response.success();
    } else {
      // Return 500 with error.
      response.dbError('Unexpected response upon deletion: ' +
        deleteResponse);
    }
  })
  .catch(function (err) {
    utils.CaughtResponse(response, err);
  });
};
<|endoftext|>


<commit_before>import Ember from "ember";
import { Promise } from "liquid-fire";

// Explode is not, by itself, an animation. It exists to pull apart
// other elements so that each of the pieces can be targeted by
// animations.

export default function explode(...pieces) {
  return Promise.all(pieces.map((piece) => {
    if (piece.matchBy) {
      return matchAndExplode(this, piece);
    } else {
      return explodePiece(this, piece);
    }
  })).then(() => {
    // The default transition guarantees that we didn't leave our
    // original new element invisible
    this.lookup('default').apply(this);
  });
}

function explodePiece(context, piece) {
  var childContext = Ember.copy(context);
  var selectors = [piece.pick, piece.pick];
  var cleanupOld, cleanupNew;

  if (piece.pickOld) {
    selectors[0] = piece.pickOld;
  }
  if (piece.pickNew) {
    selectors[1] = piece.pickNew;
  }

  if (selectors[0]) {
    cleanupOld = _explodePart(context, 'oldElement', childContext, selectors[0]);
  }

  if (selectors[1]) {
    cleanupNew = _explodePart(context, 'newElement', childContext, selectors[1]);
  }

  return new Promise((resolve, reject) => {
    animationFor(context, piece).apply(childContext).then(resolve, reject);
  }).finally(() => {
    if (cleanupOld) { cleanupOld(); }
    if (cleanupNew) { cleanupNew(); }
  });
}

function _explodePart(context, field, childContext, selector) {
  var child, childOffset, width, height, newChild;
  var elt = context[field];
  childContext[field] = null;
  if (elt) {
    child = elt.find(selector);
    if (child.length > 0) {
      childOffset = child.offset();
      width = child.width();
      height = child.height();
      newChild = child.clone();

      // Hide the original element
      child.css({visibility: 'hidden'});

      // If the original element's parent was hidden, hide our clone
      // too.
      if (elt.css('visibility') === 'hidden') {
        newChild.css({ visibility: 'hidden' });
      }
      newChild.width(width);
      newChild.height(height);
      newChild.appendTo(elt.parent());
      newChild.offset(childOffset);

      // Pass the clone to the next animation
      childContext[field] = newChild;
      return function cleanup() {
        newChild.remove();
        child.css({visibility: ''});
      };
    }
  }
}

function animationFor(context, piece) {
  var name, args, func;
  if (!piece.use) {
    throw new Error("every argument to the 'explode' animation must include a followup animation to 'use'");
  }
  if (Ember.isArray(piece.use) ) {
    name = piece.use[0];
    args = piece.use.slice(1);
  } else {
    name = piece.use;
    args = [];
  }
  if (typeof name === 'function') {
    func = name;
  } else {
    func = context.lookup(name);
  }
  return function() {
    return Promise.resolve(func.apply(this, args));
  };
}

function matchAndExplode(context, piece) {
  if (!context.oldElement) {
    return Promise.resolve();
  }

  var hits = Ember.A(context.oldElement.find(`[${piece.matchBy}]`).toArray());
  return Promise.all(hits.map((elt) => {
    return explodePiece(context, {
      pick: `[${piece.matchBy}=${Ember.$(elt).attr(piece.matchBy)}]`,
      use: piece.use
    });
  }));
}
<commit_msg>show new and hide old immediately after giving each exploded piece a chance to animate<commit_after>import Ember from "ember";
import { Promise } from "liquid-fire";

// Explode is not, by itself, an animation. It exists to pull apart
// other elements so that each of the pieces can be targeted by
// animations.

export default function explode(...pieces) {
  var result = Promise.all(pieces.map((piece) => {
    if (piece.matchBy) {
      return matchAndExplode(this, piece);
    } else {
      return explodePiece(this, piece);
    }
  }));

  if (this.newElement) {
    this.newElement.css({visibility: ''});
  }
  if (this.oldElement) {
    this.oldElement.css({visibility: 'hidden'});
  }

  return result;
}

function explodePiece(context, piece) {
  var childContext = Ember.copy(context);
  var selectors = [piece.pick, piece.pick];
  var cleanupOld, cleanupNew;

  if (piece.pickOld) {
    selectors[0] = piece.pickOld;
  }
  if (piece.pickNew) {
    selectors[1] = piece.pickNew;
  }

  if (selectors[0]) {
    cleanupOld = _explodePart(context, 'oldElement', childContext, selectors[0]);
  }

  if (selectors[1]) {
    cleanupNew = _explodePart(context, 'newElement', childContext, selectors[1]);
  }

  return new Promise((resolve, reject) => {
    animationFor(context, piece).apply(childContext).then(resolve, reject);
  }).finally(() => {
    if (cleanupOld) { cleanupOld(); }
    if (cleanupNew) { cleanupNew(); }
  });
}

function _explodePart(context, field, childContext, selector) {
  var child, childOffset, width, height, newChild;
  var elt = context[field];
  childContext[field] = null;
  if (elt) {
    child = elt.find(selector);
    if (child.length > 0) {
      childOffset = child.offset();
      width = child.width();
      height = child.height();
      newChild = child.clone();

      // Hide the original element
      child.css({visibility: 'hidden'});

      // If the original element's parent was hidden, hide our clone
      // too.
      if (elt.css('visibility') === 'hidden') {
        newChild.css({ visibility: 'hidden' });
      }
      newChild.width(width);
      newChild.height(height);
      newChild.appendTo(elt.parent());
      newChild.offset(childOffset);

      // Pass the clone to the next animation
      childContext[field] = newChild;
      return function cleanup() {
        newChild.remove();
        child.css({visibility: ''});
      };
    }
  }
}

function animationFor(context, piece) {
  var name, args, func;
  if (!piece.use) {
    throw new Error("every argument to the 'explode' animation must include a followup animation to 'use'");
  }
  if (Ember.isArray(piece.use) ) {
    name = piece.use[0];
    args = piece.use.slice(1);
  } else {
    name = piece.use;
    args = [];
  }
  if (typeof name === 'function') {
    func = name;
  } else {
    func = context.lookup(name);
  }
  return function() {
    return Promise.resolve(func.apply(this, args));
  };
}

function matchAndExplode(context, piece) {
  if (!context.oldElement) {
    return Promise.resolve();
  }

  var hits = Ember.A(context.oldElement.find(`[${piece.matchBy}]`).toArray());
  return Promise.all(hits.map((elt) => {
    return explodePiece(context, {
      pick: `[${piece.matchBy}=${Ember.$(elt).attr(piece.matchBy)}]`,
      use: piece.use
    });
  }));
}
<|endoftext|>


<commit_before>"use strict";
var ApiClient = require('nativescript-apiclient');
var Enumerable = require('nativescript-enumerable');
var TypeUtils = require('utils/types');
/**
 * List of entry types.
 */
(function (EntryType) {
    /**
     * Folder
     */
    EntryType[EntryType["Folder"] = 0] = "Folder";
    /**
     * File
     */
    EntryType[EntryType["File"] = 1] = "File";
})(exports.EntryType || (exports.EntryType = {}));
var EntryType = exports.EntryType;
/**
 * A DropBox client.
 */
var DropBoxClient = (function () {
    /**
     * Initializes a new instance of that class.
     *
     * @param {string} token The access token to use.
     */
    function DropBoxClient(token) {
        this._accessToken = token;
    }
    Object.defineProperty(DropBoxClient.prototype, "accessToken", {
        /**
         * Gets the access token.
         */
        get: function () {
            return this._accessToken;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Lists a folder.
     *
     * @param {string} Path The path.
     * @param {Function} callback The result callback.
     */
    DropBoxClient.prototype.listFolder = function (path, callback) {
        if (path === void 0) { path = ''; }
        var me = this;
        var client = ApiClient.newClient({
            baseUrl: 'https://api.dropboxapi.com/2/files/list_folder',
            authorizer: new ApiClient.BearerAuth(this._accessToken),
        });
        var code = 1;
        var entries;
        var error;
        var hasMore;
        var finish = function () {
            callback({
                code: code,
                entries: entries,
                error: error,
                hasMore: hasMore,
                path: path,
            });
        };
        client.succeededRequest(function (result) {
            var jsonResp = result.getJSON();
            code = 0;
            hasMore = jsonResp.has_more;
            if (TypeUtils.isNullOrUndefined(jsonResp.entries)) {
                entries = [];
            }
            else {
                entries = Enumerable.fromArray(jsonResp.entries)
                    .where(function (x) { return !TypeUtils.isNullOrUndefined(x); })
                    .select(function (x) {
                    // IFolderEntry
                    var entry;
                    entry = {
                        delete: function (delCallback) {
                            var terminator = ApiClient.newClient({
                                authorizer: new ApiClient.BearerAuth(me.accessToken),
                                baseUrl: 'https://api.dropboxapi.com/2/files/delete',
                            });
                            var termCode = 1;
                            var termError;
                            var termFinish = function () {
                                if (!TypeUtils.isNullOrUndefined(delCallback)) {
                                    delCallback({
                                        code: termCode,
                                        error: termError,
                                    });
                                }
                            };
                            terminator.succeededRequest(function () {
                                termCode = 0;
                            }).clientOrServerError(function (delResult) {
                                termCode = -2;
                                termError = 'Server returned code: ' + delResult.code + ' => ' + delResult.getString();
                            }).error(function (delCtx) {
                                termCode = -1;
                                termError = delCtx.error;
                            }).complete(function () {
                                termFinish();
                            });
                            terminator.post({
                                content: {
                                    path: entry.path,
                                },
                                type: ApiClient.HttpRequestType.JSON,
                            });
                        },
                        id: x.id,
                        name: x.name,
                        path: x.path_display,
                    };
                    var tag = (TypeUtils.isNullOrUndefined(x['.tag']) ? '' : ('' + x['.tag'])).toLowerCase().trim();
                    switch (tag) {
                        case 'folder':
                            entry.type = EntryType.Folder;
                            entry.uploadFile = function (fileToUpload, ulCallback) {
                                me.uploadFileTo(fileToUpload, path, ulCallback);
                            };
                            break;
                        case 'file':
                            entry.type = EntryType.File;
                            entry.download = function (callback) {
                                var downloadClient = ApiClient.newClient({
                                    authorizer: new ApiClient.BearerAuth(me.accessToken),
                                    baseUrl: 'https://content.dropboxapi.com/2/files/download',
                                });
                                downloadClient.addLogger(function (dlMsg) {
                                    console.log('DropBoxDemo.DropBoxClient.download(' + entry.path + '): ' + dlMsg.message);
                                });
                                var dlCode = 1;
                                var dlError;
                                var dlFile;
                                var finishDownload = function () {
                                    callback({
                                        code: dlCode,
                                        file: entry,
                                        localFile: dlFile,
                                    });
                                };
                                downloadClient.succeededRequest(function (dlResult) {
                                    try {
                                        dlFile = dlResult.getFile();
                                        dlCode = 0;
                                    }
                                    catch (dlE) {
                                        dlCode = -3;
                                        dlError = dlE;
                                    }
                                }).clientOrServerError(function (dlResult) {
                                    dlCode = -2;
                                    dlError = 'Server returned code: ' + dlResult.code + ' => ' + dlResult.getString();
                                }).error(function (dlCtx) {
                                    dlCode = -1;
                                    dlError = dlCtx.error;
                                }).complete(function () {
                                    finishDownload();
                                });
                                var apiArgs = {
                                    path: entry.path,
                                };
                                downloadClient.post({
                                    headers: {
                                        'Content-Type': '',
                                        'Dropbox-API-Arg': JSON.stringify(apiArgs),
                                    },
                                });
                            };
                            break;
                    }
                    return entry;
                })
                    .orderBy(function (x) { return x.type; })
                    .thenBy(function (x) { return x.path.toLowerCase().trim(); })
                    .toArray();
            }
        }).clientOrServerError(function (result) {
            code = -2;
            error = 'Server returned code: ' + result.code;
        }).error(function (ctx) {
            code = -1;
            error = ctx.error;
        }).complete(function () {
            finish();
        });
        client.post({
            content: {
                path: path,
                recursive: false,
                include_media_info: true,
                include_deleted: false,
                include_has_explicit_shared_members: false
            },
            type: ApiClient.HttpRequestType.JSON,
        });
    };
    /**
     * Uploads a file.
     *
     * @param {FileSystem.File} localFile The file to upload.
     * @param {String} [targetFolder] The custom target folder.
     * @param {Function} [callback] The optional result callback.
     */
    DropBoxClient.prototype.uploadFileTo = function (localFile, targetPath, callback) {
        if (targetPath === void 0) { targetPath = ''; }
        var readError;
        var dataToUpload = localFile.readSync(function (fileErr) {
            readError = fileErr;
        });
        var code = 1;
        var error;
        var finish = function () {
            if (!TypeUtils.isNullOrUndefined(callback)) {
                callback({
                    code: code,
                    error: error,
                });
            }
        };
        if (!TypeUtils.isNullOrUndefined(readError)) {
            code = -2;
            error = readError;
            finish();
        }
        else {
            var client = ApiClient.newClient({
                authorizer: new ApiClient.BearerAuth(this.accessToken),
                baseUrl: 'https://content.dropboxapi.com/2/files/upload',
            });
            client.succeededRequest(function () {
                code = 0;
            }).clientOrServerError(function (ulResult) {
                code = -2;
                error = 'Server returned code: ' + ulResult.code + ' => ' + ulResult.getString();
            }).error(function (ulCtx) {
                code = -1;
                error = ulCtx.error;
            }).complete(function () {
                finish();
            });
            var args = {
                path: targetPath,
                mode: "overwrite",
                autorename: true,
                mute: false
            };
            client.post({
                content: dataToUpload,
                type: ApiClient.HttpRequestType.Binary,
                headers: {
                    'Dropbox-API-Arg': JSON.stringify(args),
                }
            });
        }
    };
    return DropBoxClient;
}());
exports.DropBoxClient = DropBoxClient;
//# sourceMappingURL=DropBox.js.map<commit_msg>debug logs<commit_after>"use strict";
var ApiClient = require('nativescript-apiclient');
var Enumerable = require('nativescript-enumerable');
var TypeUtils = require('utils/types');
/**
 * List of entry types.
 */
(function (EntryType) {
    /**
     * Folder
     */
    EntryType[EntryType["Folder"] = 0] = "Folder";
    /**
     * File
     */
    EntryType[EntryType["File"] = 1] = "File";
})(exports.EntryType || (exports.EntryType = {}));
var EntryType = exports.EntryType;
/**
 * A DropBox client.
 */
var DropBoxClient = (function () {
    /**
     * Initializes a new instance of that class.
     *
     * @param {string} token The access token to use.
     */
    function DropBoxClient(token) {
        this._accessToken = token;
    }
    Object.defineProperty(DropBoxClient.prototype, "accessToken", {
        /**
         * Gets the access token.
         */
        get: function () {
            return this._accessToken;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Lists a folder.
     *
     * @param {string} Path The path.
     * @param {Function} callback The result callback.
     */
    DropBoxClient.prototype.listFolder = function (path, callback) {
        if (path === void 0) { path = ''; }
        var me = this;
        var client = ApiClient.newClient({
            baseUrl: 'https://api.dropboxapi.com/2/files/list_folder',
            authorizer: new ApiClient.BearerAuth(this._accessToken),
        });
        var code = 1;
        var entries;
        var error;
        var hasMore;
        var finish = function () {
            callback({
                code: code,
                entries: entries,
                error: error,
                hasMore: hasMore,
                path: path,
            });
        };
        client.succeededRequest(function (result) {
            var jsonResp = result.getJSON();
            code = 0;
            hasMore = jsonResp.has_more;
            if (TypeUtils.isNullOrUndefined(jsonResp.entries)) {
                entries = [];
            }
            else {
                entries = Enumerable.fromArray(jsonResp.entries)
                    .where(function (x) { return !TypeUtils.isNullOrUndefined(x); })
                    .select(function (x) {
                    // IFolderEntry
                    var entry;
                    entry = {
                        delete: function (delCallback) {
                            var terminator = ApiClient.newClient({
                                authorizer: new ApiClient.BearerAuth(me.accessToken),
                                baseUrl: 'https://api.dropboxapi.com/2/files/delete',
                            });
                            var termCode = 1;
                            var termError;
                            var termFinish = function () {
                                if (!TypeUtils.isNullOrUndefined(delCallback)) {
                                    delCallback({
                                        code: termCode,
                                        error: termError,
                                    });
                                }
                            };
                            terminator.succeededRequest(function () {
                                termCode = 0;
                            }).clientOrServerError(function (delResult) {
                                termCode = -2;
                                termError = 'Server returned code: ' + delResult.code + ' => ' + delResult.getString();
                            }).error(function (delCtx) {
                                termCode = -1;
                                termError = delCtx.error;
                            }).complete(function () {
                                termFinish();
                            });
                            terminator.post({
                                content: {
                                    path: entry.path,
                                },
                                type: ApiClient.HttpRequestType.JSON,
                            });
                        },
                        id: x.id,
                        name: x.name,
                        path: x.path_display,
                    };
                    var tag = (TypeUtils.isNullOrUndefined(x['.tag']) ? '' : ('' + x['.tag'])).toLowerCase().trim();
                    switch (tag) {
                        case 'folder':
                            entry.type = EntryType.Folder;
                            entry.uploadFile = function (fileToUpload, ulCallback) {
                                me.uploadFileTo(fileToUpload, path, ulCallback);
                            };
                            break;
                        case 'file':
                            entry.type = EntryType.File;
                            entry.download = function (callback) {
                                var downloadClient = ApiClient.newClient({
                                    authorizer: new ApiClient.BearerAuth(me.accessToken),
                                    baseUrl: 'https://content.dropboxapi.com/2/files/download',
                                });
                                downloadClient.addLogger(function (dlMsg) {
                                    console.log('DropBoxDemo.DropBoxClient.download(' + entry.path + '): ' + dlMsg.message);
                                });
                                var dlCode = 1;
                                var dlError;
                                var dlFile;
                                var finishDownload = function () {
                                    callback({
                                        code: dlCode,
                                        file: entry,
                                        localFile: dlFile,
                                    });
                                };
                                downloadClient.succeededRequest(function (dlResult) {
                                    try {
                                        dlFile = dlResult.getFile();
                                        dlCode = 0;
                                    }
                                    catch (dlE) {
                                        dlCode = -3;
                                        dlError = dlE;
                                    }
                                }).clientOrServerError(function (dlResult) {
                                    dlCode = -2;
                                    dlError = 'Server returned code: ' + dlResult.code + ' => ' + dlResult.getString();
                                }).error(function (dlCtx) {
                                    dlCode = -1;
                                    dlError = dlCtx.error;
                                }).complete(function () {
                                    finishDownload();
                                });
                                var apiArgs = {
                                    path: entry.path,
                                };
                                downloadClient.post({
                                    headers: {
                                        'Content-Type': '',
                                        'Dropbox-API-Arg': JSON.stringify(apiArgs),
                                    },
                                });
                            };
                            break;
                    }
                    return entry;
                })
                    .orderBy(function (x) { return x.type; })
                    .thenBy(function (x) { return x.path.toLowerCase().trim(); })
                    .toArray();
            }
        }).clientOrServerError(function (result) {
            code = -2;
            error = 'Server returned code: ' + result.code;
        }).error(function (ctx) {
            code = -1;
            error = ctx.error;
        }).complete(function () {
            finish();
        });
        client.post({
            content: {
                path: path,
                recursive: false,
                include_media_info: true,
                include_deleted: false,
                include_has_explicit_shared_members: false
            },
            type: ApiClient.HttpRequestType.JSON,
        });
    };
    /**
     * Uploads a file.
     *
     * @param {FileSystem.File} localFile The file to upload.
     * @param {String} [targetFolder] The custom target folder.
     * @param {Function} [callback] The optional result callback.
     */
    DropBoxClient.prototype.uploadFileTo = function (localFile, targetPath, callback) {
		var _logs = '';
        if (targetPath === void 0) { targetPath = ''; }
		_logs += '1\n';
        var readError;
        var dataToUpload = localFile.readSync(function (fileErr) {
            readError = fileErr;
        });
		_logs += '2\n';
        var code = 1;
        var error;
        var finish = function () {
            if (!TypeUtils.isNullOrUndefined(callback)) {
                callback({
                    code: code,
                    error: error,
                });
            }
        };
        if (!TypeUtils.isNullOrUndefined(readError)) {
            code = -2;
            error = readError;
            finish();
			_logs += '3\n';
			alert(_logs);
        }
        else {
			_logs += '4\n';
			alert(_logs);
            var client = ApiClient.newClient({
                authorizer: new ApiClient.BearerAuth(this.accessToken),
                baseUrl: 'https://content.dropboxapi.com/2/files/upload',
            });
            client.succeededRequest(function () {
                code = 0;
            }).clientOrServerError(function (ulResult) {
                code = -2;
                error = 'Server returned code: ' + ulResult.code + ' => ' + ulResult.getString();
            }).error(function (ulCtx) {
                code = -1;
                error = ulCtx.error;
            }).complete(function () {
                finish();
            });
            var args = {
                path: targetPath,
                mode: "overwrite",
                autorename: true,
                mute: false
            };
            client.post({
                content: dataToUpload,
                type: ApiClient.HttpRequestType.Binary,
                headers: {
                    'Dropbox-API-Arg': JSON.stringify(args),
                }
            });
        }
    };
    return DropBoxClient;
}());
exports.DropBoxClient = DropBoxClient;
//# sourceMappingURL=DropBox.js.map<|endoftext|>