<commit_before>

/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_new(performance) {

  var div = document.createElement("div");
  var name = performance.name;

  var row = document.createElement("div");
  row.className = 'row';
  var column = document.createElement('div');
  column.className = 'large-12 columns';
  column.innerHTML = "
 " + name + "
";
  row.appendChild(column);
  div.appendChild(row);

  div.column_length = {Judges: slam.num_judges, Time: 2, Penalty: 1, Score: 1, Subscore: 1, "Total Score": 1, Rank:1};
  div.titles = ["Judges", "Time", "Penalty", "Score", "Subscore", "Total Score", "Rank"];
  p_div_build_columns_hash(div);

  div.performance = performance;
  div.id = makeid(20);

  p_div_build_titles_row(div);
  p_div_build_sub_titles(div);
  p_div_build_data_row(div);

  div.style.backgroundColor = '#F4F4F4';
  div.style.borderStyle = 'solid';
  div.style.borderWidth = '1px';

  row = document.createElement("div");
  row.className = "row";

  column = document.createElement("div");
  column.className = "large-12 columns";
  column.style.minHeight = "15px"; //http://stackoverflow.com/a/25431669

  row.appendChild(column);
  div.appendChild(row);

  return div;
}

/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_columns_hash(div) {

  var num_columns = 12;

  var columns = div.columns = {};
  var titles = div.titles;

  var remaining_columns = num_columns;
  for (var i=0; i<titles.length; i++) {
    columns[titles[i]] = remaining_columns;
    remaining_columns -= div.column_length[titles[i]];

    if (i > 0) {
      for (j=0; j<i; j++) {
	columns[titles[j]] = div.column_length[titles[j]];
      }
    }
  }
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_titles_row(div) {

  var row = document.createElement("div");
  row.className = "row";

  for (var i=0; i<div.titles.length; i++) {

    var column = document.createElement("div");
    column.className = "large-" + div.columns[div.titles[i]] + " columns";
    column.innerHTML = "" + div.titles[i] + "";

    row.appendChild(column);

  }
  div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_sub_titles(div) {

  var num_columns = 12;

  var row = document.createElement("div");
  row.className = "row";

  // Add Judges
  var column;
  for (var i=0; i<slam.num_judges; i++) {

    column = document.createElement("div");

    column.className = "large-1 columns";
    column.innerHTML = "" + (i + 1) + "";

    row.appendChild(column);
  }
  // Add Timel
  column = document.createElement("div");
  column.className = "large-1 columns";
  column.innerHTML = "minutes";
  row.appendChild(column);

  column = document.createElement("div");
  column.className = "large-" + (num_columns - slam.num_judges -1) + " columns";
  column.innerHTML = "seconds";
  row.appendChild(column);

  div.appendChild(row);
}

/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_setup_indexes(div) {

  div.data_columns = [];
  div.data_indexes = {};

  var i = slam.num_judges;

  div.data_indexes.minutes_i = i++;
  div.data_indexes.seconds_i = i++;
  div.data_indexes.penalty_i = i++;
  div.data_indexes.score_i = i++;
  div.data_indexes.subscore_i = i++;
  div.data_indexes.total_score_i = i++;
  div.data_indexes.rank = i;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_input_entered(input) {

 var i = parseInt(input.getAttribute('data-index'));
 var div = input.div;

 switch (i)
 {
   case div.data_indexes.minutes_i:
     console.log('Minutes:');
     break;
   case div.data_indexes.seconds_i:
     console.log('Seconds:');
     break;
   case div.data_indexes.penalty_i:
     console.log('Penalty:');
     break;
   default:
     if (i >= 0 && i < div.data_indexes.minutes_i)
       console.log('Score (' + i + ')');
   }

     console.log(input.value);
 }
 /*----------------------------------------------------------------------------------------------------------------------------------*/
 function p_div_build_data_row(div) {

   p_div_setup_indexes(div);

   var row = document.createElement("div");
   row.className = "row";

   var num_columns = slam.num_judges + 3; // Judges + Minutes + Seconds + Penalty

   var i;
   for (i=0; i<num_columns; i++) {
     var column = document.createElement("div");
     column.className = "large-1 columns";

     var input = document.createElement("input");
     input.div = div;
     input.setAttribute('size', 4);
     input.setAttribute('onchange', 'p_div_input_entered(this)');
     input.setAttribute('data-index', i);

     column.appendChild(input);
     div.data_columns.push(input);

     row.appendChild(column);
   }

   num_columns = 12;
   for (; i< num_columns; i++) {

     var column = document.createElement("div");
     column.className = "large-1 columns";
     row.appendChild(column);

     div.data_columns.push(column);
   }

   div.appendChild(row);
 }
 /*----------------------------------------------------------------------------------------------------------------------------------*/

<commit_msg>getting input from user<commit_after>

/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_new(performance) {

  var div = document.createElement("div");
  var name = performance.name;

  var row = document.createElement("div");
  row.className = 'row';
  var column = document.createElement('div');
  column.className = 'large-12 columns';
  column.innerHTML = "
 " + name + "
";
  row.appendChild(column);
  div.appendChild(row);

  div.column_length = {Judges: slam.num_judges, Time: 2, Penalty: 1, Score: 1, Subscore: 1, "Total Score": 1, Rank:1};
  div.titles = ["Judges", "Time", "Penalty", "Score", "Subscore", "Total Score", "Rank"];
  p_div_build_columns_hash(div);

  div.performance = performance;
  div.id = makeid(20);

  p_div_build_titles_row(div);
  p_div_build_sub_titles(div);
  p_div_build_data_row(div);

  div.style.backgroundColor = '#F4F4F4';
  div.style.borderStyle = 'solid';
  div.style.borderWidth = '1px';

  row = document.createElement("div");
  row.className = "row";

  column = document.createElement("div");
  column.className = "large-12 columns";
  column.style.minHeight = "15px"; //http://stackoverflow.com/a/25431669

  row.appendChild(column);
  div.appendChild(row);

  return div;
}

/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_columns_hash(div) {

  var num_columns = 12;

  var columns = div.columns = {};
  var titles = div.titles;

  var remaining_columns = num_columns;
  for (var i=0; i<titles.length; i++) {
    columns[titles[i]] = remaining_columns;
    remaining_columns -= div.column_length[titles[i]];

    if (i > 0) {
      for (j=0; j<i; j++) {
	columns[titles[j]] = div.column_length[titles[j]];
      }
    }
  }
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_titles_row(div) {

  var row = document.createElement("div");
  row.className = "row";

  for (var i=0; i<div.titles.length; i++) {

    var column = document.createElement("div");
    column.className = "large-" + div.columns[div.titles[i]] + " columns";
    column.innerHTML = "" + div.titles[i] + "";

    row.appendChild(column);

  }
  div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_sub_titles(div) {

  var num_columns = 12;

  var row = document.createElement("div");
  row.className = "row";

  // Add Judges
  var column;
  for (var i=0; i<slam.num_judges; i++) {

    column = document.createElement("div");

    column.className = "large-1 columns";
    column.innerHTML = "" + (i + 1) + "";

    row.appendChild(column);
  }
  // Add Timel
  column = document.createElement("div");
  column.className = "large-1 columns";
  column.innerHTML = "minutes";
  row.appendChild(column);

  column = document.createElement("div");
  column.className = "large-" + (num_columns - slam.num_judges -1) + " columns";
  column.innerHTML = "seconds";
  row.appendChild(column);

  div.appendChild(row);
}

/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_setup_indexes(div) {

  div.data_columns = [];
  div.data_indexes = {};

  var i = slam.num_judges;

  div.data_indexes.minutes_i = i++;
  div.data_indexes.seconds_i = i++;
  div.data_indexes.penalty_i = i++;
  div.data_indexes.score_i = i++;
  div.data_indexes.subscore_i = i++;
  div.data_indexes.total_score_i = i++;
  div.data_indexes.rank = i;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_input_entered(input) {

 var i = parseInt(input.getAttribute('data-index'));
 var div = input.div;

 switch (i)
 {
   case div.data_indexes.minutes_i:
     console.log('Minutes:');
     break;
   case div.data_indexes.seconds_i:
     console.log('Seconds:');
     break;
   case div.data_indexes.penalty_i:
     console.log('Penalty:');
     break;
   default:
     if (i >= 0 && i < div.data_indexes.minutes_i)
       console.log('Score (' + i + ')');
   }

     console.log(input.value);
 }

 /*----------------------------------------------------------------------------------------------------------------------------------*/
 function p_div_build_data_row(div) {

   p_div_setup_indexes(div);

   var row = document.createElement("div");
   row.className = "row";

   var num_columns = slam.num_judges + 3; // Judges + Minutes + Seconds + Penalty

   var i;
   for (i=0; i<num_columns; i++) {
     var column = document.createElement("div");
     column.className = "large-1 columns";

     var input = document.createElement("input");
     input.div = div;
     input.setAttribute('size', 4);
     input.setAttribute('onchange', 'p_div_input_entered(this)');
     input.setAttribute('data-index', i);

     column.appendChild(input);
     div.data_columns.push(input);

     row.appendChild(column);
   }

   num_columns = 12;
   for (; i< num_columns; i++) {

     var column = document.createElement("div");
     column.className = "large-1 columns";
     row.appendChild(column);

     div.data_columns.push(column);
   }

   div.appendChild(row);
 }
/*----------------------------------------------------------------------------------------------------------------------------------*/

<|endoftext|>


<commit_before>import RepoHelper from './repo_helper';

const RepoStore = {
  ideEl: {},
  monacoInstance: {},
  service: '',
  editor: '',
  sidebar: '',
  editButton: '',
  editMode: false,
  isTree: false,
  prevURL: '',
  trees: [],
  blobs: [],
  submodules: [],
  blobRaw: '',
  blobRendered: '',
  openedFiles: [],
  activeFile: {
    active: true,
    binary: false,
    extension: '',
    html: '',
    mime_type: '',
    name: 'loading...',
    plain: '',
    size: 0,
    url: '',
    raw: false,
    newContent: '',
    changed: false,
  },
  activeFileIndex: 0,
  activeLine: 0,
  activeFileLabel: 'Raw',
  files: [],
  binary: false,
  binaryMimeType: '',
  // scroll bar space for windows
  scrollWidth: 0,
  binaryTypes: {
    png: false,
    markdown: false,
  },
  loading: {
    tree: false,
    blob: false,
  },

  // mutations

  addFilesToDirectory(inDirectory, currentList, newList) {
    RepoStore.files = RepoHelper.getNewMergedList(inDirectory, currentList, newList);
  },

  toggleRawPreview() {
    RepoStore.activeFile.raw = !RepoStore.activeFile.raw;
    RepoStore.activeFileLabel = RepoStore.activeFile.raw ? 'Display rendered file' : 'Display source';
  },

  setActiveFiles(file) {
    if (RepoStore.isActiveFile(file)) return;

    RepoStore.openedFiles = RepoStore.openedFiles
      .map((openedFile, i) => RepoStore.w(openedFile, i));

    RepoStore.setActiveToRaw();

    if (file.binary) {
      RepoStore.blobRaw = file.base64;
    } else {
      RepoStore.blobRaw = file.plain;
    }

    if (!file.loading) RepoHelper.toURL(file.url);
    RepoStore.binary = file.binary;
  },

  w(file, i) {
    const activeFile = file;
    activeFile.active = activeFile.url === activeFile.url;

    if (activeFile.active) RepoStore.setActiveFile(activeFile, i);

    return activeFile;
  },

  setActiveFile(activeFile, i) {
    RepoStore.activeFile = activeFile;
    RepoStore.activeFileIndex = i;
  },

  setActiveToRaw() {
    RepoStore.activeFile.raw = false;
    // can't get vue to listen to raw for some reason so RepoStore for now.
    RepoStore.activeFileLabel = 'Display source';
  },

  removeChildFilesOfTree(tree) {
    let foundTree = false;
    const treetoClose = tree;
    RepoStore.files = RepoStore.files.filter((file) => {
      if (file.url === treetoClose.url) foundTree = true;

      if (foundTree) return file.level <= treetoClose.level;
      return true;
    });

    treetoClose.opened = false;
    treetoClose.icon = 'fa-folder';
    return treetoClose;
  },

  removeFromOpenedFiles(file) {
    if (file.type === 'tree') return;

    RepoStore.openedFiles = RepoStore.openedFiles.filter(openedFile => openedFile.url !== file.url);
  },

  addPlaceholderFile() {
    const randomURL = RepoHelper.Time.now();
    const newFakeFile = {
      active: false,
      binary: true,
      type: 'blob',
      loading: true,
      mime_type: 'loading',
      name: 'loading',
      url: randomURL,
    };

    RepoStore.openedFiles.push(newFakeFile);

    return newFakeFile;
  },

  addToOpenedFiles(file) {
    const openFile = file;

    const openedFilesAlreadyExists = RepoStore.openedFiles
      .some(openedFile => openedFile.url === openFile.url);

    if (openedFilesAlreadyExists) return;

    openFile.changed = false;
    RepoStore.openedFiles.push(openFile);
  },

  setActiveFileContents(contents) {
    if (!RepoStore.editMode) return;

    RepoStore.activeFile.newContent = contents;
    RepoStore.activeFile.changed = RepoStore.activeFile.plain !== RepoStore.activeFile.newContent;
    RepoStore.openedFiles[RepoStore.activeFileIndex].changed = RepoStore.activeFile.changed;
  },

  // getters

  isActiveFile(file) {
    return file && file.url === RepoStore.activeFile.url;
  },
};
export default RepoStore;
<commit_msg>Fixes directory opening closing bug<commit_after>import RepoHelper from './repo_helper';

const RepoStore = {
  ideEl: {},
  monacoInstance: {},
  service: '',
  editor: '',
  sidebar: '',
  editButton: '',
  editMode: false,
  isTree: false,
  prevURL: '',
  trees: [],
  blobs: [],
  submodules: [],
  blobRaw: '',
  blobRendered: '',
  openedFiles: [],
  activeFile: {
    active: true,
    binary: false,
    extension: '',
    html: '',
    mime_type: '',
    name: 'loading...',
    plain: '',
    size: 0,
    url: '',
    raw: false,
    newContent: '',
    changed: false,
  },
  activeFileIndex: 0,
  activeLine: 0,
  activeFileLabel: 'Raw',
  files: [],
  binary: false,
  binaryMimeType: '',
  // scroll bar space for windows
  scrollWidth: 0,
  binaryTypes: {
    png: false,
    markdown: false,
  },
  loading: {
    tree: false,
    blob: false,
  },

  // mutations

  addFilesToDirectory(inDirectory, currentList, newList) {
    RepoStore.files = RepoHelper.getNewMergedList(inDirectory, currentList, newList);
  },

  toggleRawPreview() {
    RepoStore.activeFile.raw = !RepoStore.activeFile.raw;
    RepoStore.activeFileLabel = RepoStore.activeFile.raw ? 'Display rendered file' : 'Display source';
  },

  setActiveFiles(file) {
    if (RepoStore.isActiveFile(file)) return;

    RepoStore.openedFiles = RepoStore.openedFiles
      .map((openedFile, i) => RepoStore.w(openedFile, i));

    RepoStore.setActiveToRaw();

    if (file.binary) {
      RepoStore.blobRaw = file.base64;
    } else {
      RepoStore.blobRaw = file.plain;
    }

    if (!file.loading) RepoHelper.toURL(file.url);
    RepoStore.binary = file.binary;
  },

  w(file, i) {
    const activeFile = file;
    activeFile.active = activeFile.url === activeFile.url;

    if (activeFile.active) RepoStore.setActiveFile(activeFile, i);

    return activeFile;
  },

  setActiveFile(activeFile, i) {
    RepoStore.activeFile = activeFile;
    RepoStore.activeFileIndex = i;
  },

  setActiveToRaw() {
    RepoStore.activeFile.raw = false;
    // can't get vue to listen to raw for some reason so RepoStore for now.
    RepoStore.activeFileLabel = 'Display source';
  },

  removeChildFilesOfTree(tree) {
    let foundTree = false;
    const treeToClose = tree;
    let wereDone = false;
    RepoStore.files = RepoStore.files.filter((file) => {
      const isItTheTreeWeWant = file.url === treeToClose.url;
      // if it's the next tree
      if(foundTree && file.type === 'tree' && !isItTheTreeWeWant) {
        wereDone = true;
        return true;
      }
      if(wereDone) return true;

      if (isItTheTreeWeWant) foundTree = true;

      if (foundTree) return file.level <= treeToClose.level;
      return true;
    });

    treeToClose.opened = false;
    treeToClose.icon = 'fa-folder';
    return treeToClose;
  },

  removeFromOpenedFiles(file) {
    if (file.type === 'tree') return;

    RepoStore.openedFiles = RepoStore.openedFiles.filter(openedFile => openedFile.url !== file.url);
  },

  addPlaceholderFile() {
    const randomURL = RepoHelper.Time.now();
    const newFakeFile = {
      active: false,
      binary: true,
      type: 'blob',
      loading: true,
      mime_type: 'loading',
      name: 'loading',
      url: randomURL,
    };

    RepoStore.openedFiles.push(newFakeFile);

    return newFakeFile;
  },

  addToOpenedFiles(file) {
    const openFile = file;

    const openedFilesAlreadyExists = RepoStore.openedFiles
      .some(openedFile => openedFile.url === openFile.url);

    if (openedFilesAlreadyExists) return;

    openFile.changed = false;
    RepoStore.openedFiles.push(openFile);
  },

  setActiveFileContents(contents) {
    if (!RepoStore.editMode) return;

    RepoStore.activeFile.newContent = contents;
    RepoStore.activeFile.changed = RepoStore.activeFile.plain !== RepoStore.activeFile.newContent;
    RepoStore.openedFiles[RepoStore.activeFileIndex].changed = RepoStore.activeFile.changed;
  },

  // getters

  isActiveFile(file) {
    return file && file.url === RepoStore.activeFile.url;
  },
};
export default RepoStore;
<|endoftext|>


<commit_before>//= require datatables

// Create custom field ajax
$("#modal-create-custom-field").on("show.bs.modal", function(event) {
    // Clear input when modal is opened
    input = $(this).find("input#name-input");
    input.val("");
    input.closest(".form-group").removeClass("has-error");
    input.closest(".form-group").find(".help-block").remove();
});
$("#modal-create-custom-field").on("shown.bs.modal", function(event) {
    $(this).find("input#name-input").focus();
});

$("form#new_custom_field").on("ajax:success", function(ev, data, status) {
    $("#modal-create-custom-field").modal("hide");

    // Reload page with URL parameter of newly created field
    window.location.href = addParam(window.location.href, "new_col");
});

$("form#new_custom_field").on("ajax:error", function(e, data, status, xhr) {
    input = $(this).find("#name-input");
    input.closest(".form-group").find(".help-block").remove();
    input.closest(".form-group").addClass("has-error");

    $.each(data.responseJSON, function(i, val) {
        input.parent().append("" + val[0].charAt(0).toUpperCase() + val[0].slice(1) +"
");
    });
});

// Create sample type ajax
$("#modal-create-sample-type").on("show.bs.modal", function(event) {
    // Clear input when modal is opened
    input = $(this).find("input#name-input");
    input.val("");
    input.closest(".form-group").removeClass("has-error");
    input.closest(".form-group").find(".help-block").remove();
});

$("#modal-create-sample-type").on("shown.bs.modal", function(event) {
    $(this).find("input#name-input").focus();
});

$("form#new_sample_type").on("ajax:success", function(ev, data, status) {
    $("#modal-create-sample-type").modal("hide");
    updateSamplesTypesandGroups();
    sampleAlertMsg(data.flash);
});

$("form#new_sample_type").on("ajax:error", function(e, data, status, xhr) {
    input = $(this).find("#name-input");
    input.closest(".form-group").find(".help-block").remove();
    input.closest(".form-group").addClass("has-error");

    $.each(data.responseJSON, function(i, val) {
        input.parent().append("" + val[0].charAt(0).toUpperCase() + val[0].slice(1) +"
");
    });
});

// Create sample group ajax
$("#modal-create-sample-group").on("show.bs.modal", function(event) {
    // Clear input when modal is opened
    input = $(this).find("input#name-input");
    input.val("");
    input.closest(".form-group").removeClass("has-error");
    input.closest(".form-group").find(".help-block").remove();
});

$("#modal-create-sample-group").on("shown.bs.modal", function(event) {
    $(this).find("input#name-input").focus();
});

$("form#new_sample_group").on("ajax:success", function(ev, data, status) {
    $("#modal-create-sample-group").modal("hide");
    updateSamplesTypesandGroups();
    sampleAlertMsg(data.flash);
});

$("form#new_sample_group").on("ajax:error", function(e, data, status, xhr) {
    input = $(this).find("#name-input");
    input.closest(".form-group").find(".help-block").remove();
    input.closest(".form-group").addClass("has-error");

    $.each(data.responseJSON, function(i, val) {
        input.parent().append("" + val[0].charAt(0).toUpperCase() + val[0].slice(1) +"
");
    });
});

// Create import samples ajax
$("#modal-import-samples").on("show.bs.modal", function(event) {
    formGroup = $(this).find(".form-group");
    formGroup.removeClass("has-error");
    formGroup.find(".help-block").remove();
});

$("form#form-samples-file")
.on("ajax:success", function(ev, data, status) {
  $("#modal-parse-samples").html(data.html);
  $("#modal-import-samples").modal("hide");
  $("#modal-parse-samples").modal("show");
})
.on("ajax:error", function(ev, data, status) {
  $(this).find(".form-group").addClass("has-error");
  $(this).find(".form-group").find(".help-block").remove();
  $(this).find(".form-group").append("" + data.responseJSON.message + "");
});

// Fetch samples data and updates the select options fields for
// sample group and sample type column
function updateSamplesTypesandGroups() {
  changeToEditMode();
  updateButtons();

  $.ajax({
    url: $("table#samples").data("new-sample"),
    type: "GET",
    dataType: "json",
    success: function (data) {
      $("select[name=sample_group_id]").each(function(){
        var sample_group = $(this).val();
        var selectGroup = createSampleGroupSelect(data.sample_groups, sample_group);
        var gtd = $(this).parent("td");
        gtd.html(selectGroup[0]);
      });
      $("select[name=sample_type_id]").each(function(){
        var sample_type = $(this).val();
        var selectType = createSampleTypeSelect(data.sample_types, sample_type);
        var ttd = $(this).parent("td");
        ttd.html(selectType[0]);
      });

      $("select[name=sample_group_id]").selectpicker();
      $("select[name=sample_type_id]").selectpicker();
    },
    error: function (e, eData, status, xhr) {
      if (e.status == 403)
        showAlertMessage(I18n.t("samples.js.permission_error"));
        changeToViewMode();
        updateButtons();
      }
    });
}

function sampleAlertMsg(message) {
  var html_snippet = '
' +
                      '
' +
                        '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>' +
                          '' +
                          ''+ message +'' +
                        '
' +
                      '
';
  $('#notifications').html(html_snippet);
}

function initTutorial() {
  var currentStep = parseInt(Cookies.get('current_tutorial_step'), 10);
  if (currentStep == 8)
    currentStep++;
  if (showTutorial() && (currentStep > 12 &&  currentStep < 16)) {
    var samplesTutorial =$("#samples-toolbar").attr("data-samples-step-text");
    var breadcrumbsTutorial = $("#samples-toolbar").attr("data-breadcrumbs-step-text");

    introJs()
      .setOptions({
        steps: [
          {
            element: document.getElementById("samples-toolbar"),
            intro: samplesTutorial
          },
          {
            element: document.getElementById("secondary-menu"),
            intro: breadcrumbsTutorial,
            tooltipClass: 'custom next-page-link'
          }
        ],
        overlayOpacity: '0.1',
        nextLabel: 'Next',
        doneLabel: 'End tutorial',
        skipLabel: 'End tutorial',
        showBullets: false,
        showStepNumbers: false,
        exitOnOverlayClick: false,
        exitOnEsc: false,
        disableInteraction: true,
        tooltipClass: "custom"
      })
      .onafterchange(function (tarEl) {
        Cookies.set('current_tutorial_step', this._currentStep + 14);

        if (this._currentStep == 1) {
          setTimeout(function() {
            $('.next-page-link a.introjs-nextbutton')
              .removeClass('introjs-disabled')
              .attr('href', $("#reports-nav-tab a").attr('href'));
            $('.introjs-disableInteraction').remove();
            positionTutorialTooltip();
          }, 500);
        } else {
          positionTutorialTooltip();
        }
      })
      .goToStep(currentStep == 15 ? 2 : 1)
      .start();

    // Destroy first-time tutorial cookies when skip tutorial
    // or end tutorial is clicked
    $(".introjs-skipbutton").each(function (){
      $(this).click(function (){
        Cookies.remove('tutorial_data');
        Cookies.remove('current_tutorial_step');
        restore_after_tutorial();
      });
    });
  }
}

function positionTutorialTooltip() {
  if (Cookies.get('current_tutorial_step') == 13) {
    if ($("#reports-nav-tab").offset().left == 0) {
      $(".introjs-tooltip").css("left", (window.innerWidth / 2 - 50)  + "px");
      $(".introjs-tooltip").addClass("repositioned");
    } else if ($(".introjs-tooltip").hasClass("repositioned")) {
      $(".introjs-tooltip").css("left", "");
      $(".introjs-tooltip").removeClass("repositioned");
    }
  } else {
    if ($(".introjs-tooltip").offset().left > window.innerWidth) {
      $(".introjs-tooltip").css("left", (window.innerWidth / 2 - 50)  + "px");
      $(".introjs-tooltip").addClass("repositioned");
    } else if ($(".introjs-tooltip").hasClass("repositioned")) {
      $(".introjs-tooltip").css("left", "");
      $(".introjs-tooltip").removeClass("repositioned");
    }
  }
};

function showTutorial() {
  var tutorialData;
  if (Cookies.get('tutorial_data'))
    tutorialData = JSON.parse(Cookies.get('tutorial_data'));
  else
    return false;
  var tutorialModuleId = tutorialData[0].qpcr_module;
  var currentModuleId = $("#samples-toolbar").attr("data-module-id");
  return tutorialModuleId == currentModuleId;
}

function samples_tutorial_helper(){
  $(document).ready(function(){
    if( $('div').hasClass('introjs-showElement') ){
      $('#secondary-menu')
        .find('a')
        .css({ 'pointer-events': 'none' });
    }
  });
}

function restore_after_tutorial(){
  $('#secondary-menu')
    .find('a')
    .css({ 'pointer-events': 'auto' });
}
// Initialize first-time tutorial
initTutorial();
samples_tutorial_helper();
<commit_msg>update buttons<commit_after>//= require datatables

// Create custom field ajax
$("#modal-create-custom-field").on("show.bs.modal", function(event) {
    // Clear input when modal is opened
    input = $(this).find("input#name-input");
    input.val("");
    input.closest(".form-group").removeClass("has-error");
    input.closest(".form-group").find(".help-block").remove();
});
$("#modal-create-custom-field").on("shown.bs.modal", function(event) {
    $(this).find("input#name-input").focus();
});

$("form#new_custom_field").on("ajax:success", function(ev, data, status) {
    $("#modal-create-custom-field").modal("hide");

    // Reload page with URL parameter of newly created field
    window.location.href = addParam(window.location.href, "new_col");
});

$("form#new_custom_field").on("ajax:error", function(e, data, status, xhr) {
    input = $(this).find("#name-input");
    input.closest(".form-group").find(".help-block").remove();
    input.closest(".form-group").addClass("has-error");

    $.each(data.responseJSON, function(i, val) {
        input.parent().append("" + val[0].charAt(0).toUpperCase() + val[0].slice(1) +"
");
    });
});

// Create sample type ajax
$("#modal-create-sample-type").on("show.bs.modal", function(event) {
    // Clear input when modal is opened
    input = $(this).find("input#name-input");
    input.val("");
    input.closest(".form-group").removeClass("has-error");
    input.closest(".form-group").find(".help-block").remove();
});

$("#modal-create-sample-type").on("shown.bs.modal", function(event) {
    $(this).find("input#name-input").focus();
});

$("form#new_sample_type").on("ajax:success", function(ev, data, status) {
    $("#modal-create-sample-type").modal("hide");
    updateSamplesTypesandGroups();
    sampleAlertMsg(data.flash);
    currentMode = "viewMode";
    updateButtons();
});

$("form#new_sample_type").on("ajax:error", function(e, data, status, xhr) {
    input = $(this).find("#name-input");
    input.closest(".form-group").find(".help-block").remove();
    input.closest(".form-group").addClass("has-error");

    $.each(data.responseJSON, function(i, val) {
        input.parent().append("" + val[0].charAt(0).toUpperCase() + val[0].slice(1) +"
");
    });
});

// Create sample group ajax
$("#modal-create-sample-group").on("show.bs.modal", function(event) {
    // Clear input when modal is opened
    input = $(this).find("input#name-input");
    input.val("");
    input.closest(".form-group").removeClass("has-error");
    input.closest(".form-group").find(".help-block").remove();
});

$("#modal-create-sample-group").on("shown.bs.modal", function(event) {
    $(this).find("input#name-input").focus();
});

$("form#new_sample_group").on("ajax:success", function(ev, data, status) {
    $("#modal-create-sample-group").modal("hide");
    updateSamplesTypesandGroups();
    sampleAlertMsg(data.flash);
    currentMode = "viewMode";
    updateButtons();
});

$("form#new_sample_group").on("ajax:error", function(e, data, status, xhr) {
    input = $(this).find("#name-input");
    input.closest(".form-group").find(".help-block").remove();
    input.closest(".form-group").addClass("has-error");

    $.each(data.responseJSON, function(i, val) {
        input.parent().append("" + val[0].charAt(0).toUpperCase() + val[0].slice(1) +"
");
    });
});

// Create import samples ajax
$("#modal-import-samples").on("show.bs.modal", function(event) {
    formGroup = $(this).find(".form-group");
    formGroup.removeClass("has-error");
    formGroup.find(".help-block").remove();
});

$("form#form-samples-file")
.on("ajax:success", function(ev, data, status) {
  $("#modal-parse-samples").html(data.html);
  $("#modal-import-samples").modal("hide");
  $("#modal-parse-samples").modal("show");
})
.on("ajax:error", function(ev, data, status) {
  $(this).find(".form-group").addClass("has-error");
  $(this).find(".form-group").find(".help-block").remove();
  $(this).find(".form-group").append("" + data.responseJSON.message + "");
});

// Fetch samples data and updates the select options fields for
// sample group and sample type column
function updateSamplesTypesandGroups() {
  changeToEditMode();
  updateButtons();

  $.ajax({
    url: $("table#samples").data("new-sample"),
    type: "GET",
    dataType: "json",
    success: function (data) {
      $("select[name=sample_group_id]").each(function(){
        var sample_group = $(this).val();
        var selectGroup = createSampleGroupSelect(data.sample_groups, sample_group);
        var gtd = $(this).parent("td");
        gtd.html(selectGroup[0]);
      });
      $("select[name=sample_type_id]").each(function(){
        var sample_type = $(this).val();
        var selectType = createSampleTypeSelect(data.sample_types, sample_type);
        var ttd = $(this).parent("td");
        ttd.html(selectType[0]);
      });

      $("select[name=sample_group_id]").selectpicker();
      $("select[name=sample_type_id]").selectpicker();
    },
    error: function (e, eData, status, xhr) {
      if (e.status == 403)
        showAlertMessage(I18n.t("samples.js.permission_error"));
        changeToViewMode();
        updateButtons();
      }
    });
}

function sampleAlertMsg(message) {
  var html_snippet = '
' +
                      '
' +
                        '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>' +
                          '' +
                          ''+ message +'' +
                        '
' +
                      '
';
  $('#notifications').html(html_snippet);
}

function initTutorial() {
  var currentStep = parseInt(Cookies.get('current_tutorial_step'), 10);
  if (currentStep == 8)
    currentStep++;
  if (showTutorial() && (currentStep > 12 &&  currentStep < 16)) {
    var samplesTutorial =$("#samples-toolbar").attr("data-samples-step-text");
    var breadcrumbsTutorial = $("#samples-toolbar").attr("data-breadcrumbs-step-text");

    introJs()
      .setOptions({
        steps: [
          {
            element: document.getElementById("samples-toolbar"),
            intro: samplesTutorial
          },
          {
            element: document.getElementById("secondary-menu"),
            intro: breadcrumbsTutorial,
            tooltipClass: 'custom next-page-link'
          }
        ],
        overlayOpacity: '0.1',
        nextLabel: 'Next',
        doneLabel: 'End tutorial',
        skipLabel: 'End tutorial',
        showBullets: false,
        showStepNumbers: false,
        exitOnOverlayClick: false,
        exitOnEsc: false,
        disableInteraction: true,
        tooltipClass: "custom"
      })
      .onafterchange(function (tarEl) {
        Cookies.set('current_tutorial_step', this._currentStep + 14);

        if (this._currentStep == 1) {
          setTimeout(function() {
            $('.next-page-link a.introjs-nextbutton')
              .removeClass('introjs-disabled')
              .attr('href', $("#reports-nav-tab a").attr('href'));
            $('.introjs-disableInteraction').remove();
            positionTutorialTooltip();
          }, 500);
        } else {
          positionTutorialTooltip();
        }
      })
      .goToStep(currentStep == 15 ? 2 : 1)
      .start();

    // Destroy first-time tutorial cookies when skip tutorial
    // or end tutorial is clicked
    $(".introjs-skipbutton").each(function (){
      $(this).click(function (){
        Cookies.remove('tutorial_data');
        Cookies.remove('current_tutorial_step');
        restore_after_tutorial();
      });
    });
  }
}

function positionTutorialTooltip() {
  if (Cookies.get('current_tutorial_step') == 13) {
    if ($("#reports-nav-tab").offset().left == 0) {
      $(".introjs-tooltip").css("left", (window.innerWidth / 2 - 50)  + "px");
      $(".introjs-tooltip").addClass("repositioned");
    } else if ($(".introjs-tooltip").hasClass("repositioned")) {
      $(".introjs-tooltip").css("left", "");
      $(".introjs-tooltip").removeClass("repositioned");
    }
  } else {
    if ($(".introjs-tooltip").offset().left > window.innerWidth) {
      $(".introjs-tooltip").css("left", (window.innerWidth / 2 - 50)  + "px");
      $(".introjs-tooltip").addClass("repositioned");
    } else if ($(".introjs-tooltip").hasClass("repositioned")) {
      $(".introjs-tooltip").css("left", "");
      $(".introjs-tooltip").removeClass("repositioned");
    }
  }
};

function showTutorial() {
  var tutorialData;
  if (Cookies.get('tutorial_data'))
    tutorialData = JSON.parse(Cookies.get('tutorial_data'));
  else
    return false;
  var tutorialModuleId = tutorialData[0].qpcr_module;
  var currentModuleId = $("#samples-toolbar").attr("data-module-id");
  return tutorialModuleId == currentModuleId;
}

function samples_tutorial_helper(){
  $(document).ready(function(){
    if( $('div').hasClass('introjs-showElement') ){
      $('#secondary-menu')
        .find('a')
        .css({ 'pointer-events': 'none' });
    }
  });
}

function restore_after_tutorial(){
  $('#secondary-menu')
    .find('a')
    .css({ 'pointer-events': 'auto' });
}
// Initialize first-time tutorial
initTutorial();
samples_tutorial_helper();
<|endoftext|>


<commit_before>import { shallowMount } from '@vue/test-utils'
import PlantPreview from '@/app/overview/components/PlantPreview'

describe('app/overview/PlantPreview.vue', () => {
  const defaultProps = {
    deleteMode: false,
    categoriseMode: false,
    pressedMode: false,
    guid: '',
    name: '',
    imageUrl: '',
    defaultSelected: false
  }

  it('is a Vue component', () => {
    const wrapper = shallowMount(PlantPreview, { propsData: defaultProps })
    expect(wrapper.isVueInstance()).toEqual(true)
  })

  it('has correct default props data', () => {
    const wrapper = shallowMount(PlantPreview, { propsData: defaultProps })
    expect(wrapper.props().deleteMode).toEqual(false)
    expect(wrapper.props().categoriseMode).toEqual(false)
    expect(wrapper.props().pressedMode).toEqual(false)
    expect(wrapper.props().guid).toEqual('')
    expect(wrapper.props().name).toEqual('')
    expect(wrapper.props().imageUrl).toEqual('')
    expect(wrapper.props().defaultSelected).toEqual(false)
  })
})
<commit_msg>:white_check_mark: Updated test for <PlantPreview /><commit_after>import { shallowMount } from '@vue/test-utils'
import PlantPreview from '@/app/overview/components/PlantPreview'

describe('app/overview/PlantPreview.vue', () => {
  const defaultProps = {
    type: 'grid',
    deleteMode: false,
    categoriseMode: false,
    pressedMode: false,
    guid: '',
    name: '',
    imageUrl: '',
    defaultSelected: false
  }

  it('is a Vue component', () => {
    const wrapper = shallowMount(PlantPreview, { propsData: defaultProps })
    expect(wrapper.isVueInstance()).toEqual(true)
  })

  it('has correct default props data', () => {
    const wrapper = shallowMount(PlantPreview, { propsData: defaultProps })
    expect(wrapper.props().type).toEqual('grid')
    expect(wrapper.props().deleteMode).toEqual(false)
    expect(wrapper.props().categoriseMode).toEqual(false)
    expect(wrapper.props().pressedMode).toEqual(false)
    expect(wrapper.props().guid).toEqual('')
    expect(wrapper.props().name).toEqual('')
    expect(wrapper.props().imageUrl).toEqual('')
    expect(wrapper.props().defaultSelected).toEqual(false)
  })
})
<|endoftext|>


<commit_before>import { RecurrenceParser, DateObj } from 'recurrence-parser'
import { Conductor, DeviceType, TriggerType } from 'timeline-state-resolver'
import Store from '../renderer/store/index'
import { MediaScanner } from './media'
import { Resolver } from 'superfly-timeline'

const conductor = new Conductor()
const scanner = new MediaScanner()
const parser = new RecurrenceParser(name => scanner.getMediaDuration(name), name => scanner.getFolderContents(name), null, () => null)

conductor.on('error', (...err) => console.log(...err))
// conductor.on('debug', (...info) => console.log(...info))

conductor.init()
  .then(() => {
    conductor.mapping = {
      'bg': {
        device: DeviceType.CASPARCG,
        deviceId: 'ccg',
        channel: 1,
        layer: 10
      },
      'PLAYOUT': {
        device: DeviceType.CASPARCG,
        deviceId: 'ccg',
        channel: 1,
        layer: 20
      }
    }
  })
  .then(() => {
    return conductor.addDevice('ccg', { type: DeviceType.CASPARCG, options: { host: '127.0.0.1', port: 5250, useScheduling: false } })
  })
  .then(() => {
    createTimeline()
    scanner.on('changed', () => createTimeline())
    Store.watch(state => state.playoutSchedule, () => createTimeline())
    Store.watch(state => state.settings.decklinkInput, () => createTimeline())
  })

let timeout = setTimeout(() => createTimeline(), 0)

function createTimeline () {
  if (Store.state.playoutSchedule.length === 0) {
    clearTimeout(timeout)
    timeout = setTimeout(() => createTimeline(), 12 * 3600 * 1000) // re-parse in 12 hours
    return
  }
  const tls = []
  let time = Date.now() - 6 * 3600 * 1000 // 6 hrs ago
  let stopCondition = Date.now() + 18 * 3600 * 1000 // 18 hrs ahead

  parser.schedule = JSON.parse(JSON.stringify(Store.state.playoutSchedule))

  while (time < stopCondition) {
    const tl = parser.getNextTimeline(new DateObj(time))
    tls.push(tl)
    time = tl.end + 1
  }

  const decklink = (volume, start, end) => {
    const tlObj = {
      id: `bg_decklink_${volume ? 'unmute' : 'mute'}_${start}`,
      LLayer: 'bg',
      trigger: {
        type: TriggerType.TIME_ABSOLUTE,
        value: start
      },
      duration: end ? end - start : 0,
      content: {
        type: 'input',
        attributes: {
          device: Number(Store.state.settings.decklinkInput)
        },
        mixer: {
          volume: volume ? 1 : 0,
          inTransition: {
            duration: 250
          }
        }
      }
    }

    return tlObj
  }

  const timeline = []
  let last = Date.now()
  for (const tl of tls) {
    timeline.push(decklink(true, last, tl.start))
    timeline.push(decklink(false, tl.start, tl.end))

    const bg = []
    for (let i = 0; i < tl.timeline.length; i++) { // make bg objects
      const obj = JSON.parse(JSON.stringify(tl.timeline[i]))
      obj.id += '_bg'
      obj.originalLLayer = obj.LLayer
      obj.LLayer += '_BG'
      obj.isBackground = true
      if (i === 0) {
        obj.trigger = {
          type: TriggerType.TIME_RELATIVE,
          value: `#${tl.timeline[0].id} - 2000`
        }
        obj.duration = 2000
      } else {
        obj.trigger = {
          type: TriggerType.LOGICAL,
          value: `#${tl.timeline[i - 1].id}`
        }
        obj.duration = 0
      }
      bg.push(obj)
    }

    timeline.push(...tl.timeline)
    timeline.push(...bg)

    for (const obj of tl.timeline) {
      if (obj.content.muted && obj.duration > 500) {
        const dl = {
          id: 'bg_decklink_' + obj.id,
          LLayer: 'bg',
          trigger: {
            type: TriggerType.TIME_RELATIVE,
            value: `#${obj.id}.start`
          },
          duration: obj.duration,
          priority: 1,
          content: {
            type: 'input',
            attributes: {
              device: 1
            },
            mixer: {
              volume: 1,
              inTransition: {
                duration: 250
              }
            }
          }
        }
        timeline.push(dl)
      }
    }
    last = tl.end
  }
  timeline.push(decklink(true, last))

  conductor.timeline = timeline
  clearTimeout(timeout)
  timeout = setTimeout(() => createTimeline(), 12 * 3600 * 1000) // re-parse in 12 hours
}

setInterval(() => {
  const update = {}

  if (!conductor.timeline || conductor.timeline.length === 0) return

  const tl = Resolver.getState(conductor.timeline, Date.now())

  const curLayer = tl.LLayers['PLAYOUT'] || tl.LLayers['bg']

  if (curLayer.LLayer === 'bg' && Store.state.playoutState.nowPlaying !== 'Nothing') {
    update.nowPlaying = 'Nothing'
  } else if (curLayer.LLayer === 'PLAYOUT' && curLayer.content.attributes.file !== Store.state.playoutState.nowPlaying) {
    update.nowPlaying = curLayer.content.attributes.file
  }
  if (curLayer.resolved.endTime !== Store.state.playoutState.nextUpTime) {
    update.nextUpTime = curLayer.resolved.endTime
  }
  if (curLayer.resolved.startTime !== Store.state.playoutState.startTime) {
    update.startTime = curLayer.resolved.startTime
  }

  const nextTl = Resolver.getState(conductor.timeline, curLayer.resolved.endTime)
  if (nextTl.LLayers['PLAYOUT']) {
    if (nextTl.LLayers['PLAYOUT'].content.attributes.file !== Store.state.playoutState.nextUp) {
      update.nextUp = nextTl.LLayers['PLAYOUT'].content.attributes.file
    }
  } else {
    if (Store.state.playoutState.nextUp !== 'Nothing') {
      update.nextUp = 'Nothing'
    }
  }

  if (Object.keys(update).length > 0) Store.dispatch('updatePlayoutState', update)
}, 200)
<commit_msg>fix: take the next timeline at least one second later<commit_after>import { RecurrenceParser, DateObj } from 'recurrence-parser'
import { Conductor, DeviceType, TriggerType } from 'timeline-state-resolver'
import Store from '../renderer/store/index'
import { MediaScanner } from './media'
import { Resolver } from 'superfly-timeline'

const conductor = new Conductor()
const scanner = new MediaScanner()
const parser = new RecurrenceParser(name => scanner.getMediaDuration(name), name => scanner.getFolderContents(name), null, () => null)

conductor.on('error', (...err) => console.log(...err))
// conductor.on('debug', (...info) => console.log(...info))

conductor.init()
  .then(() => {
    conductor.mapping = {
      'bg': {
        device: DeviceType.CASPARCG,
        deviceId: 'ccg',
        channel: 1,
        layer: 10
      },
      'PLAYOUT': {
        device: DeviceType.CASPARCG,
        deviceId: 'ccg',
        channel: 1,
        layer: 20
      }
    }
  })
  .then(() => {
    return conductor.addDevice('ccg', { type: DeviceType.CASPARCG, options: { host: '127.0.0.1', port: 5250, useScheduling: false } })
  })
  .then(() => {
    createTimeline()
    scanner.on('changed', () => createTimeline())
    Store.watch(state => state.playoutSchedule, () => createTimeline())
    Store.watch(state => state.settings.decklinkInput, () => createTimeline())
  })

let timeout = setTimeout(() => createTimeline(), 0)

function createTimeline () {
  if (Store.state.playoutSchedule.length === 0) {
    clearTimeout(timeout)
    timeout = setTimeout(() => createTimeline(), 12 * 3600 * 1000) // re-parse in 12 hours
    return
  }
  const tls = []
  let time = Date.now() - 6 * 3600 * 1000 // 6 hrs ago
  let stopCondition = Date.now() + 18 * 3600 * 1000 // 18 hrs ahead

  parser.schedule = JSON.parse(JSON.stringify(Store.state.playoutSchedule))

  while (time < stopCondition) {
    const tl = parser.getNextTimeline(new DateObj(time))
    tls.push(tl)
    time = tl.end + 1000
  }

  const decklink = (volume, start, end) => {
    const tlObj = {
      id: `bg_decklink_${volume ? 'unmute' : 'mute'}_${start}`,
      LLayer: 'bg',
      trigger: {
        type: TriggerType.TIME_ABSOLUTE,
        value: start
      },
      duration: end ? end - start : 0,
      content: {
        type: 'input',
        attributes: {
          device: Number(Store.state.settings.decklinkInput)
        },
        mixer: {
          volume: volume ? 1 : 0,
          inTransition: {
            duration: 250
          }
        }
      }
    }

    return tlObj
  }

  const timeline = []
  let last = Date.now()
  for (const tl of tls) {
    timeline.push(decklink(true, last, tl.start))
    timeline.push(decklink(false, tl.start, tl.end))

    const bg = []
    for (let i = 0; i < tl.timeline.length; i++) { // make bg objects
      const obj = JSON.parse(JSON.stringify(tl.timeline[i]))
      obj.id += '_bg'
      obj.originalLLayer = obj.LLayer
      obj.LLayer += '_BG'
      obj.isBackground = true
      if (i === 0) {
        obj.trigger = {
          type: TriggerType.TIME_RELATIVE,
          value: `#${tl.timeline[0].id} - 2000`
        }
        obj.duration = 2000
      } else {
        obj.trigger = {
          type: TriggerType.LOGICAL,
          value: `#${tl.timeline[i - 1].id}`
        }
        obj.duration = 0
      }
      bg.push(obj)
    }

    timeline.push(...tl.timeline)
    timeline.push(...bg)

    for (const obj of tl.timeline) {
      if (obj.content.muted && obj.duration > 500) {
        const dl = {
          id: 'bg_decklink_' + obj.id,
          LLayer: 'bg',
          trigger: {
            type: TriggerType.TIME_RELATIVE,
            value: `#${obj.id}.start`
          },
          duration: obj.duration,
          priority: 1,
          content: {
            type: 'input',
            attributes: {
              device: 1
            },
            mixer: {
              volume: 1,
              inTransition: {
                duration: 250
              }
            }
          }
        }
        timeline.push(dl)
      }
    }
    last = tl.end
  }
  timeline.push(decklink(true, last))

  conductor.timeline = timeline
  clearTimeout(timeout)
  timeout = setTimeout(() => createTimeline(), 12 * 3600 * 1000) // re-parse in 12 hours
}

setInterval(() => {
  const update = {}

  if (!conductor.timeline || conductor.timeline.length === 0) return

  const tl = Resolver.getState(conductor.timeline, Date.now())

  const curLayer = tl.LLayers['PLAYOUT'] || tl.LLayers['bg']

  if (curLayer.LLayer === 'bg' && Store.state.playoutState.nowPlaying !== 'Nothing') {
    update.nowPlaying = 'Nothing'
  } else if (curLayer.LLayer === 'PLAYOUT' && curLayer.content.attributes.file !== Store.state.playoutState.nowPlaying) {
    update.nowPlaying = curLayer.content.attributes.file
  }
  if (curLayer.resolved.endTime !== Store.state.playoutState.nextUpTime) {
    update.nextUpTime = curLayer.resolved.endTime
  }
  if (curLayer.resolved.startTime !== Store.state.playoutState.startTime) {
    update.startTime = curLayer.resolved.startTime
  }

  const nextTl = Resolver.getState(conductor.timeline, curLayer.resolved.endTime)
  if (nextTl.LLayers['PLAYOUT']) {
    if (nextTl.LLayers['PLAYOUT'].content.attributes.file !== Store.state.playoutState.nextUp) {
      update.nextUp = nextTl.LLayers['PLAYOUT'].content.attributes.file
    }
  } else {
    if (Store.state.playoutState.nextUp !== 'Nothing') {
      update.nextUp = 'Nothing'
    }
  }

  if (Object.keys(update).length > 0) Store.dispatch('updatePlayoutState', update)
}, 200)
<|endoftext|>


<commit_before>// ELMO.Views.Dashboard
//
// View model for the Dashboard
(function(ns, klass) {

  var RELOAD_INTERVAL = 10; // seconds

  // constructor
  ns.Dashboard = klass = function(params) { var self = this;
    self.params = params;

    // readjust stuff on window resize
    $(window).on('resize', function(){
      self.adjust_pane_sizes();
      self.list_view.adjust_columns();

      // clear this timeout in case this is another resize event before it ran out
      clearTimeout(self.resize_done_timeout)

      // set a timeout to refresh the report
      self.resize_done_timeout = setTimeout(function(){
        ELMO.app.report_controller.refresh_view();
      }, 1000);
    })

    // setup auto-reload
    self.reload_timer = setTimeout(function(){ self.reload(); }, RELOAD_INTERVAL * 1000);

    // adjust sizes for the initial load
    self.adjust_pane_sizes();

    self.list_view = new ELMO.Views.DashboardResponseList();
    self.map_view = new ELMO.Views.DashboardMap(self.params.map);
    self.report_view = new ELMO.Views.DashboardReport(self, self.params.report);

    self.list_view.adjust_columns();
  };

  klass.prototype.adjust_pane_sizes = function() { var self = this;
    // set 3 pane widths/heights depending on container size

    // the content window padding and space between columns
    var spacing = 15;

    // content window inner dimensions
    var cont_w = $('#content').width() - 4;
    var cont_h = $(window).height() - $('#title').outerHeight(true) - 3 * spacing;

    // height of the h2 elements
    var title_h = $('#content h2').height();

    // height of the stats pane
    var stats_h = $('.report_stats').height();

    // left col is slightly narrower than right col
    $('.recent_responses, .response_locations').width((cont_w - spacing) * .8 / 2)
    $('.report_main').width((cont_w - spacing) * 1.2 / 2);

    // for left panes height we subtract 2 title heights plus 3 spacings (2 bottom, one top)
    $('.recent_responses, .response_locations').height((cont_h - 2 * title_h - 3 * spacing) / 2);

    // for report pane we subtract 1 title height plus 2 spacings (1 bottom, 1 top) plus the stats pane height
    $('.report_main').height(cont_h - title_h - 2 * spacing - stats_h);
  };

  // reloads the page, passing the current report id
  klass.prototype.reload = function(args) { var self = this;
    // we don't set the 'auto' parameter on this request so that the session will be kept alive
    // the dashboard is meant to be a long-running page so doesn't make sense to let the session expire
    $('#content').load(Utils.build_url('dashboard?report_id=' + self.report_view.current_report_id +
      '&latest_response_id=' + self.list_view.latest_response_id()));
  };

}(ELMO.Views));<commit_msg>added handling for server errors<commit_after>// ELMO.Views.Dashboard
//
// View model for the Dashboard
(function(ns, klass) {

  var RELOAD_INTERVAL = 10; // seconds

  // constructor
  ns.Dashboard = klass = function(params) { var self = this;
    self.params = params;

    // readjust stuff on window resize
    $(window).on('resize', function(){
      self.adjust_pane_sizes();
      self.list_view.adjust_columns();

      // clear this timeout in case this is another resize event before it ran out
      clearTimeout(self.resize_done_timeout)

      // set a timeout to refresh the report
      self.resize_done_timeout = setTimeout(function(){
        ELMO.app.report_controller.refresh_view();
      }, 1000);
    })

    // setup auto-reload
    self.reload_timer = setTimeout(function(){ self.reload(); }, RELOAD_INTERVAL * 1000);

    // adjust sizes for the initial load
    self.adjust_pane_sizes();

    self.list_view = new ELMO.Views.DashboardResponseList();
    self.map_view = new ELMO.Views.DashboardMap(self.params.map);
    self.report_view = new ELMO.Views.DashboardReport(self, self.params.report);

    self.list_view.adjust_columns();
  };

  klass.prototype.adjust_pane_sizes = function() { var self = this;
    // set 3 pane widths/heights depending on container size

    // the content window padding and space between columns
    var spacing = 15;

    // content window inner dimensions
    var cont_w = $('#content').width() - 4;
    var cont_h = $(window).height() - $('#title').outerHeight(true) - 3 * spacing;

    // height of the h2 elements
    var title_h = $('#content h2').height();

    // height of the stats pane
    var stats_h = $('.report_stats').height();

    // left col is slightly narrower than right col
    $('.recent_responses, .response_locations').width((cont_w - spacing) * .8 / 2)
    $('.report_main').width((cont_w - spacing) * 1.2 / 2);

    // for left panes height we subtract 2 title heights plus 3 spacings (2 bottom, one top)
    $('.recent_responses, .response_locations').height((cont_h - 2 * title_h - 3 * spacing) / 2);

    // for report pane we subtract 1 title height plus 2 spacings (1 bottom, 1 top) plus the stats pane height
    $('.report_main').height(cont_h - title_h - 2 * spacing - stats_h);
  };

  // reloads the page, passing the current report id
  klass.prototype.reload = function(args) { var self = this;
    // we don't set the 'auto' parameter on this request so that the session will be kept alive
    // the dashboard is meant to be a long-running page so doesn't make sense to let the session expire
    $.ajax({
      url: Utils.build_url('dashboard'),
      method: 'GET',
      data: {
        report_id: self.report_view.current_report_id,
        latest_response_id: self.list_view.latest_response_id()
      },
      success: function(data) {
        $('#content').html(data);
      },
      error: function() {
        $('#content').html(I18n.t('layout.server_contact_error'));
      }
    });

  };

}(ELMO.Views));<|endoftext|>


<commit_before>TRANSLATIONS = {
	"Today": "Dnes",
	"Yesterday": "Včera",
	"Week": "Týždeň",
	"Month": "Mesiac",
	"Custom": "Dátum",
	"Previous": "Predchádzajúci",
	"Next": "Ďalší",

	"Login error": "Chyba prihlásenia",
	"Error": "Chyba",
	"Error while getting data": "Chyba pri získavaní dát",
	"No data for selected interval": "Žiadne dáta pre zvolený interval",
	"Limit of tabs reached": "Bol dosiahnutý limit záložiek",
	"Error getting settings from server": "Chyba pri načítaní nastavení zo servera",

	"Sort by": "Zoradiť podľa",
	"name": "názov",

	"Settings": "Nastavenia",
	"settings": "nastavenia",

	"Unit": "Vozidlo",
	"Add unit": "Pridať vozidlo",

	"Mileage": "Vzdialenosť",
	"mileage": "vzdialenosť",
	"km": "km",
	"km/h": "km/h",
	"mi": "",
	"mph": "",

	"violations / km": "priestupky / km",
	"( %s km/h for %s s )": "(%s km/h for %s s)",
	"( %s mph for %s s )": "(%s mph for %s s)",
	"Duration": "Trvanie",

	"Rate": "Hodnotenie",

	"Violations": "Priestupky",
	"violations": "priestupky,
	"Violations of the trip": "Priestupky na úseku trasy",
	"No violations": "Bez priestupkov",
	"Trips for %s ": "Jazdy z %s",
	"not shorter than %s": "nie kratšie ako %s",

	"trips count": "Počet trás",
	"Trip length": "Dĺžka trasy",
	"Minimal trip length": "Minimálna dĺžka trasy",

	"Acceleration": "Zrýchlenie",
	"Brake": "Brzdenie",
	"Turn": "Prejazd zákrutou",
	"Unknown": "Neznámy",

	"New tab": "Nová záložka",
	"Close tab": "Zavrieť záložku",

	"Delete statistics": "Vymazať štatistiku",

	"Show on map": "Zobraziť na mape",

	"Loyal assessment": "Lojálne hodnotenie",
	"Normal assessment": "Normálne hodnotenie",
	"Strict assessment": "Prísne hodnotenie"
};
<commit_msg>Update sk.js<commit_after>TRANSLATIONS = {
	"Today": "Dnes",
	"Yesterday": "Včera",
	"Week": "Týždeň",
	"Month": "Mesiac",
	"Custom": "Dátum",
	"Previous": "Predchádzajúci",
	"Next": "Ďalší",

	"Login error": "Chyba prihlásenia",
	"Error": "Chyba",
	"Error while getting data": "Chyba pri získavaní dát",
	"No data for selected interval": "Žiadne dáta pre zvolený interval",
	"Limit of tabs reached": "Bol dosiahnutý limit záložiek",
	"Error getting settings from server": "Chyba pri načítaní nastavení zo servera",

	"Sort by": "Zoradiť podľa",
	"name": "názov",

	"Settings": "Nastavenia",
	"settings": "nastavenia",

	"Unit": "Vozidlo",
	"Add unit": "Pridať vozidlo",

	"Mileage": "Vzdialenosť",
	"mileage": "vzdialenosť",
	"km": "km",
	"km/h": "km/h",
	"mi": "",
	"mph": "",

	"violations / km": "priestupky / km",
	"( %s km/h for %s s )": "(%s km/h for %s s)",
	"( %s mph for %s s )": "(%s mph for %s s)",
	"Duration": "Trvanie",

	"Rate": "Hodnotenie",

	"Violations": "Priestupky",
	"violations": "priestupky",
	"Violations of the trip": "Priestupky na úseku trasy",
	"No violations": "Bez priestupkov",
	"Trips for %s ": "Jazdy z %s",
	"not shorter than %s": "nie kratšie ako %s",

	"trips count": "Počet trás",
	"Trip length": "Dĺžka trasy",
	"Minimal trip length": "Minimálna dĺžka trasy",

	"Acceleration": "Zrýchlenie",
	"Brake": "Brzdenie",
	"Turn": "Prejazd zákrutou",
	"Unknown": "Neznámy",

	"New tab": "Nová záložka",
	"Close tab": "Zavrieť záložku",

	"Delete statistics": "Vymazať štatistiku",

	"Show on map": "Zobraziť na mape",

	"Loyal assessment": "Lojálne hodnotenie",
	"Normal assessment": "Normálne hodnotenie",
	"Strict assessment": "Prísne hodnotenie"
};
<|endoftext|>


<commit_before>/**
 *
 * ares.Node kind represents a direcroty or a file in HermesFileTree.
 * this kind inherits from enyo.Node
 *
 */

enyo.kind({
	name: "ares.Node",
	kind: "Node",
	events: {
		onFileClick: "",
		onFolderClick: "",
		onFileDblClick: "",
		onAdjustScroll: ""
	},
	published: {
		service: null
	},

	// expandable nodes may only be opened by tapping the icon; tapping the content label
	// will fire the nodeTap event, but will not expand the node.
	onlyIconExpands: true,

	debug: false,

	// Note: this function does not recurse
	updateNodes: function() {
		this.startLoading(this);
		if (this.debug) this.log(this) ;
		return this.service.listFiles(this.file && this.file.id)
			.response(this, function(inSender, inFiles) {
				var sortedFiles = inFiles.sort(this.fileNameSort) ;
				if (inFiles && !this.showing) {
					this.show();
				}

				if (this.debug) this.log("updating node content of ", this.name, this," with ", sortedFiles ) ;
				this.updateNodeContent(sortedFiles);
				this.render() ;
			})
			.response(this, function() {
				this.stopLoading();
			})
			.error(this, function() {
				this.stopLoading();
			})
			;
	},
	startLoading: function() {
		this.$.extra.setContent(' ');
	},
	stopLoading: function() {
		this.$.extra.setContent("");
	},
    updateNodeContent: function(files) {
		var i = 0 , nfiles, rfiles, res, modified = 0, newControl ;

		if (this.debug) this.log("updateNodeContent on",this) ;

		// Add dir property to files, which is a project-relative path
		enyo.forEach(files, function(f) {
			if (this.debug) this.log("updateNodeContent loop on",f) ;
			if (f.isDir) {
				f.dir = (this.file.dir || "/") + f.name + "/";
			} else {
				f.dir = (this.file.dir || "/");
			}
		}.bind(this));
		rfiles = this.filesToNodes(files) ; // with prefix in name
		nfiles = this.getNodeFiles() ;

		while ( i < nfiles.length || i < rfiles.length) {
			if (this.debug) this.log("considering node " + (nfiles[i] ? nfiles[i].name : '<none>') + ' and file ' + (rfiles[i] ? rfiles[i].name : '<none>') );

			res = i >= nfiles.length ? 1
			    : i >= rfiles.length ? -1
			    :                      this.fileNameSort(nfiles[i], rfiles[i]) ;

			// remember that these file lists are sorted
			switch(res) {
				case -1: // remote file removed
					if (this.debug) this.log(nfiles[i].name + " was removed") ;
					nfiles[i].destroy() ;
				    modified = 1;
					nfiles = this.getNodeFiles() ;
					// node file list reduced by one, must not increment i
					break ;

				case 0: // no change
					i++ ;
					break ;

				case 1: // file added
				    if (this.debug) this.log(rfiles[i].name + " was added") ;
					newControl = this.createComponent( rfiles[i], {kind: "ares.Node"} ) ;
					if (this.debug) this.log("updateNodeContent created ", newControl) ;
					newControl.setService(this.service);
					nfiles = this.getNodeFiles() ;
					// FIXME: ENYO-1337
					//if (nfiles[i]) {
					//	var justAdded = inNode.controls.pop() ;
					//	inNode.controls.splice(i+4, 0, justAdded);
					//}
				    modified = 1;
					if (nfiles[i].name === '$project.json') {
						// project.json file is internal to Ares
						nfiles[i].hide();
					}
					i++ ;
					break ;
			}

		}

		if (modified) {
			this.$.client.render();
		}
	},
	compareFiles: function(inFilesA, inFilesB) {
		if (inFilesA.length != inFilesB.length) {
			return false;
		}
		for (var i in inFilesA) {
			var f0 = inFilesA[i], f1 = inFilesB[i];
			if (f0.id !== f1.id) {
				return false;
			}
		}
		return true;
	},
	// Sort files by name, case-insensitively
	// TODO: I18N, and possibly platform-specific sort order
	fileNameSort: function(a, b) {
		var lowA, lowB;
		lowA=a.name.toLowerCase();
		lowB=b.name.toLowerCase();
		// compare lower-case version of name
		if (lowA < lowB) {
			return -1;
		} else if (lowB < lowA) {
			return 1;
		} else {
			// Files that differ only in case are sorted lexicographically
			if (a.name < b.name) {
				return -1;
			} else if (b.name < a.name) {
				return 1;
			} else {
				return 0;
			}
		}
	},
	getNodeFiles: function() {
		var hasPrefix = function(e){
			return (e.name.slice(0,1) === '$') ;
		} ;
		// getComponents only return the graphical items
		return this.getControls().filter( hasPrefix ).sort(this.fileNameSort) ;
	},

	/**
	 * getNodeNamed
	 * @public
	 * @param {String} name
	 * @return a ares.Node for a file or a directory named passed in parameter
	 *
	 */

	getNodeNamed: function(name) {
		var hasPrefix = function(e){
			return (e.name === '$'+ name) ;
		} ;
		return this.getControls().filter( hasPrefix )[0];
	},

	filesToNodes: function(inFiles) {
		var nodes = [];
		inFiles.sort(this.fileNameSort); // TODO: Other sort orders
		for (var i=0, f; f=inFiles[i]; i++) {
			nodes.push({
				file: f,
				name: '$' + f.name, // prefix avoids clobberring non-files components like icon
				content: f.name,
				expandable: f.isDir,
				icon: "$services/assets/images/" + (f.isDir ? "folder.png" : "file.png")
			});
		}
		return nodes;
	},
	nodeExpand: function(inSender, inEvent) {
		if (this.debug) this.log(inSender, "=>", inEvent);

		var subnode = inEvent.originator;
		if (this.debug) this.log("nodeExpand called while node Expanded is " + subnode.expanded) ;
		// update icon for expanded state
		if (subnode.file.isDir) {
			subnode.setIcon("$services/assets/images/" + (subnode.expanded ? "folder-open.png" : "folder.png"));
		}
		// handle lazy-load when expanding
		if (subnode.expanded) {
			subnode.updateNodes().
				response(this, function() {
					subnode.effectExpanded();
				});
			// tell the event originator that node expansion should be deferred
			inEvent.wait = true;
		}
		// handled here (don't bubble)
		return true;
	},

	// All parameters are optional.
	// - toSelectId is optional. refresh will select this entry if specified.
	//   Nothing is selected otherwise.
	// - tracker is an internal parameter used in inner refreshFileTree calls
	refreshTree: function(tracker, belowTop, toSelectId) {
		if (this.debug) this.log(this) ;
		var target = this ;

		if (this.debug) this.log('running refreshTree with ' +
					 this.controls.length + ' controls with content ' + this.content +
					 ' force select ' + toSelectId );

		tracker.inc() ; // for updadeNodes
		this.updateNodes().
			response(this, function(inSender, inFiles) {
				// expand node if it has clients (sub-nodes) and is expanded
				this.effectExpanded();

				enyo.forEach(this.getNodeFiles(), function(f) {
					var c = this.$[f.name] ; // c is a node
					if (this.debug) this.log('running INNER function of refreshTree on ' + f.name +
								 ' id ' + c.file.id);
					if ( c.file.id === toSelectId ) {
						if (this.debug) this.log('force select of ' + c.file.id);
						c.doNodeTap();
						this.doAdjustScroll() ;
						// force a "click" event when the item is selected
						this.doFolderClick({file: c.file});
					}
					c.effectExpanded() ;
					if (f.expanded) {
						tracker.inc() ; // for inner calls to refreshTree
						c.refreshTree(tracker, 1, toSelectId );
					}
				}, this);
				tracker.dec(); // end updateNodes
			}).
			error(this, function(inSender, inError) {
				var errMsg = "Error refreshing the file list (" + inError + ")";
				try {
					errMsg += ": " + JSON.parse(inSender.xhrResponse.body).message;
				} catch(e) {
				}
				this.showErrorPopup(errMsg);
			});

		if( belowTop ) {
			tracker.dec(); // run only for inner calls to refreshTree
		}
		this.debug && this.log("refreshTree done") ;
	}

});

<commit_msg>ENYO-1996: added getNodeWithId method<commit_after>/**
 *
 * ares.Node kind represents a direcroty or a file in HermesFileTree.
 * this kind inherits from enyo.Node
 *
 */

enyo.kind({
	name: "ares.Node",
	kind: "Node",
	events: {
		onFileClick: "",
		onFolderClick: "",
		onFileDblClick: "",
		onAdjustScroll: ""
	},
	published: {
		service: null
	},

	// expandable nodes may only be opened by tapping the icon; tapping the content label
	// will fire the nodeTap event, but will not expand the node.
	onlyIconExpands: true,

	debug: false,

	// Note: this function does not recurse
	updateNodes: function() {
		this.startLoading(this);
		if (this.debug) this.log(this) ;
		return this.service.listFiles(this.file && this.file.id)
			.response(this, function(inSender, inFiles) {
				var sortedFiles = inFiles.sort(this.fileNameSort) ;
				if (inFiles && !this.showing) {
					this.show();
				}

				if (this.debug) this.log("updating node content of ", this.name, this," with ", sortedFiles ) ;
				this.updateNodeContent(sortedFiles);
				this.render() ;
			})
			.response(this, function() {
				this.stopLoading();
			})
			.error(this, function() {
				this.stopLoading();
			})
			;
	},
	startLoading: function() {
		this.$.extra.setContent(' ');
	},
	stopLoading: function() {
		this.$.extra.setContent("");
	},
    updateNodeContent: function(files) {
		var i = 0 , nfiles, rfiles, res, modified = 0, newControl ;

		if (this.debug) this.log("updateNodeContent on",this) ;

		// Add dir property to files, which is a project-relative path
		enyo.forEach(files, function(f) {
			if (this.debug) this.log("updateNodeContent loop on",f) ;
			if (f.isDir) {
				f.dir = (this.file.dir || "/") + f.name + "/";
			} else {
				f.dir = (this.file.dir || "/");
			}
		}.bind(this));
		rfiles = this.filesToNodes(files) ; // with prefix in name
		nfiles = this.getNodeFiles() ;

		while ( i < nfiles.length || i < rfiles.length) {
			if (this.debug) this.log("considering node " + (nfiles[i] ? nfiles[i].name : '<none>') + ' and file ' + (rfiles[i] ? rfiles[i].name : '<none>') );

			res = i >= nfiles.length ? 1
			    : i >= rfiles.length ? -1
			    :                      this.fileNameSort(nfiles[i], rfiles[i]) ;

			// remember that these file lists are sorted
			switch(res) {
				case -1: // remote file removed
					if (this.debug) this.log(nfiles[i].name + " was removed") ;
					nfiles[i].destroy() ;
				    modified = 1;
					nfiles = this.getNodeFiles() ;
					// node file list reduced by one, must not increment i
					break ;

				case 0: // no change
					i++ ;
					break ;

				case 1: // file added
				    if (this.debug) this.log(rfiles[i].name + " was added") ;
					newControl = this.createComponent( rfiles[i], {kind: "ares.Node"} ) ;
					if (this.debug) this.log("updateNodeContent created ", newControl) ;
					newControl.setService(this.service);
					nfiles = this.getNodeFiles() ;
					// FIXME: ENYO-1337
					//if (nfiles[i]) {
					//	var justAdded = inNode.controls.pop() ;
					//	inNode.controls.splice(i+4, 0, justAdded);
					//}
				    modified = 1;
					if (nfiles[i].name === '$project.json') {
						// project.json file is internal to Ares
						nfiles[i].hide();
					}
					i++ ;
					break ;
			}

		}

		if (modified) {
			this.$.client.render();
		}
	},
	compareFiles: function(inFilesA, inFilesB) {
		if (inFilesA.length != inFilesB.length) {
			return false;
		}
		for (var i in inFilesA) {
			var f0 = inFilesA[i], f1 = inFilesB[i];
			if (f0.id !== f1.id) {
				return false;
			}
		}
		return true;
	},
	// Sort files by name, case-insensitively
	// TODO: I18N, and possibly platform-specific sort order
	fileNameSort: function(a, b) {
		var lowA, lowB;
		lowA=a.name.toLowerCase();
		lowB=b.name.toLowerCase();
		// compare lower-case version of name
		if (lowA < lowB) {
			return -1;
		} else if (lowB < lowA) {
			return 1;
		} else {
			// Files that differ only in case are sorted lexicographically
			if (a.name < b.name) {
				return -1;
			} else if (b.name < a.name) {
				return 1;
			} else {
				return 0;
			}
		}
	},
	getNodeFiles: function() {
		var hasPrefix = function(e){
			return (e.name.slice(0,1) === '$') ;
		} ;
		// getComponents only return the graphical items
		return this.getControls().filter( hasPrefix ).sort(this.fileNameSort) ;
	},

	/**
	 * getNodeNamed
	 * @public
	 * @param {String} name
	 * @return a ares.Node for a file or a directory named passed in parameter
	 *
	 */

	getNodeNamed: function(name) {
		var hasPrefix = function(e){
			return (e.name === '$'+ name) ;
		} ;
		return this.getControls().filter( hasPrefix )[0];
	},

	/**
	 * getNodeNamed
	 * @public
	 * @param {String} id
	 * @return a ares.Node for a file or a directory id passed in parameter
	 *
	 */

	getNodeWithId: function (id) {
		var idMatch = function(e){
			return (e.file && e.file.id === id) ;
		} ;
		return this.getControls().filter( idMatch )[0];
	},

	filesToNodes: function(inFiles) {
		var nodes = [];
		inFiles.sort(this.fileNameSort); // TODO: Other sort orders
		for (var i=0, f; f=inFiles[i]; i++) {
			nodes.push({
				file: f,
				name: '$' + f.name, // prefix avoids clobberring non-files components like icon
				content: f.name,
				expandable: f.isDir,
				icon: "$services/assets/images/" + (f.isDir ? "folder.png" : "file.png")
			});
		}
		return nodes;
	},
	nodeExpand: function(inSender, inEvent) {
		if (this.debug) this.log(inSender, "=>", inEvent);

		var subnode = inEvent.originator;
		if (this.debug) this.log("nodeExpand called while node Expanded is " + subnode.expanded) ;
		// update icon for expanded state
		if (subnode.file.isDir) {
			subnode.setIcon("$services/assets/images/" + (subnode.expanded ? "folder-open.png" : "folder.png"));
		}
		// handle lazy-load when expanding
		if (subnode.expanded) {
			subnode.updateNodes().
				response(this, function() {
					subnode.effectExpanded();
				});
			// tell the event originator that node expansion should be deferred
			inEvent.wait = true;
		}
		// handled here (don't bubble)
		return true;
	},

	// All parameters are optional.
	// - toSelectId is optional. refresh will select this entry if specified.
	//   Nothing is selected otherwise.
	// - tracker is an internal parameter used in inner refreshFileTree calls
	refreshTree: function(tracker, belowTop, toSelectId) {
		if (this.debug) this.log(this) ;
		var target = this ;

		if (this.debug) this.log('running refreshTree with ' +
					 this.controls.length + ' controls with content ' + this.content +
					 ' force select ' + toSelectId );

		tracker.inc() ; // for updadeNodes
		this.updateNodes().
			response(this, function(inSender, inFiles) {
				// expand node if it has clients (sub-nodes) and is expanded
				this.effectExpanded();

				enyo.forEach(this.getNodeFiles(), function(f) {
					var c = this.$[f.name] ; // c is a node
					if (this.debug) this.log('running INNER function of refreshTree on ' + f.name +
								 ' id ' + c.file.id);
					if ( c.file.id === toSelectId ) {
						if (this.debug) this.log('force select of ' + c.file.id);
						c.doNodeTap();
						this.doAdjustScroll() ;
						// force a "click" event when the item is selected
						this.doFolderClick({file: c.file});
					}
					c.effectExpanded() ;
					if (f.expanded) {
						tracker.inc() ; // for inner calls to refreshTree
						c.refreshTree(tracker, 1, toSelectId );
					}
				}, this);
				tracker.dec(); // end updateNodes
			}).
			error(this, function(inSender, inError) {
				var errMsg = "Error refreshing the file list (" + inError + ")";
				try {
					errMsg += ": " + JSON.parse(inSender.xhrResponse.body).message;
				} catch(e) {
				}
				this.showErrorPopup(errMsg);
			});

		if( belowTop ) {
			tracker.dec(); // run only for inner calls to refreshTree
		}
		this.debug && this.log("refreshTree done") ;
	}

});

<|endoftext|>


<commit_before>function AbstractNode() {}

exports.AbstractNode = AbstractNode;

function LiteralNode(value, type) {
  AbstractNode.call(this);
  this.value = value;
  this.type = type;
}

exports.LiteralNode = LiteralNode;
extend(AbstractNode, LiteralNode);

LiteralNode.prototype.getFreeVariables = function () {
  return [];
};

LiteralNode.prototype.getType = function () {
  return this.type;
};

LiteralNode.prototype.evaluate = function () {
  return this.value;
};

function ListLiteralNode(expressions) {
  AbstractNode.call(this);
  this.expressions = expressions;
}

exports.ListLiteralNode = ListLiteralNode;
extend(AbstractNode, ListLiteralNode);

ListLiteralNode.prototype.getFreeVariables = function () {
  return this.expressions.reduce(function (names, expression) {
    return names.union(expression.getFreeVariables());
  }, []);
};

ListLiteralNode.prototype.getType = function (context) {
  return new ListType(this.expressions.map(function (expression) {
    return expression.getType(context);
  }).reduce(function (result, type) {
    return result.merge(type);
  }, UnknownType.DEFAULT));
};

ListLiteralNode.prototype.evaluate = function (context) {
  return new ListValue(this.expressions.map(function (expression) {
    return expression.evaluate(context);
  }));
};

function VariableNode(name) {
  AbstractNode.call(this);
  this.name = name;
}

exports.VariableNode = VariableNode;
extend(AbstractNode, VariableNode);

VariableNode.prototype.getFreeVariables = function () {
  return [this.name];
};

VariableNode.prototype.getType = function (context) {
  if (context.has(this.name)) {
    return context.top(this.name);
  } else {
    return UnknownType.DEFAULT;
  }
};

VariableNode.prototype.evaluate = function (context) {
  if (context.has(this.name)) {
    return context.top(this.name);
  } else {
    return AbstractValue.unmarshal(getGlobalValue(this.name));
  }
};

function ErrorNode() {
  AbstractNode.call(this);
}

exports.ErrorNode = ErrorNode;
extend(AbstractNode, ErrorNode);

ErrorNode.prototype.getFreeVariables = function () {
  return ['error'];
};

ErrorNode.prototype.getType = function (context) {
  if (context.has('error')) {
    return context.top('error');
  } else {
    throw new LambdaTypeError();
  }
};

ErrorNode.prototype.evaluate = function (context) {
  if (context.has('error')) {
    return context.top('error');
  } else {
    throw new LambdaRuntimeError();
  }
};

function FieldAccessNode(left, name) {
  AbstractNode.call(this);
  this.left = left;
  this.name = name;
}

exports.FieldAccessNode = FieldAccessNode;
extend(AbstractNode, FieldAccessNode);

FieldAccessNode.prototype.getFreeVariables = function () {
  return this.left.getFreeVariables();
};

FieldAccessNode.prototype.getType = function (context) {
  var left = this.left.getType(context);
  if (left.context.has(this.name)) {
    return left.context.top(this.name);
  } else {
    throw new LambdaTypeError();
  }
};

FieldAccessNode.prototype.evaluate = function (context) {
  var left = this.left.evaluate(context);
  if (left.context.has(this.name)) {
    return left.context.top(this.name).bindThis(left);
  } else {
    throw new LambdaRuntimeError();
  }
};

function LambdaNode(name, type, body) {
  AbstractNode.call(this);
  this.name = name;
  this.type = type || new VariableType(name);
  this.body = body;
}

exports.LambdaNode = LambdaNode;
extend(AbstractNode, LambdaNode);

LambdaNode.prototype.getFreeVariables = function () {
  return this.body.getFreeVariables().filter(function (name) {
    return name === this.name;
  }, this);
};

LambdaNode.prototype.getType = function (context) {
  return new ClosureType(this.type, this.body.getType(context.add(this.name, this.type)));
};

LambdaNode.prototype.evaluate = function (context) {
  return new Closure(this, context);
};

function ApplicationNode(left, right) {
  AbstractNode.call(this);
  this.left = left;
  this.right = right;
}

exports.ApplicationNode = ApplicationNode;
extend(AbstractNode, ApplicationNode);

ApplicationNode.prototype.getFreeVariables = function () {
  return this.left.getFreeVariables().union(this.right.getFreeVariables());
};

ApplicationNode.prototype.getType = function (context) {
  var left = this.left.getType(context);
  var right = this.right.getType(context);
  if (left.is(ClosureType) && right.isSubTypeOf(left.left)) {
    if (left.left.is(VariableType)) {
      return left.right.instance(left.left.name, right);
    } else if (right.isSubTypeOf(left.left)) {
      return left.right;
    } else {
      throw new LambdaTypeError();
    }
  } else {
    throw new LambdaTypeError();
  }
};

ApplicationNode.prototype.evaluate = function (context) {
  var left = this.left.evaluate(context);
  var right = this.right.evaluate(context);
  if (left.is(Closure)) {
    return left.lambda.body.evaluate(left.capture.add(left.lambda.name, right));
  } else {
    throw new LambdaRuntimeError();
  }
};

function LetNode(names, expression, body) {
  AbstractNode.call(this);
  if (names.length < 1) {
    throw new LambdaInternalError();
  }
  this.names = names;
  this.expression = expression;
  this.body = body;
}

exports.LetNode = LetNode;
extend(AbstractNode, LetNode);

LetNode.prototype.getFreeVariables = function () {
  return this.body.getFreeVariables().filter(function (name) {
    return name !== this.names[0];
  }, this);
};

LetNode.prototype.getType = function (context) {
  var rootContext = context;
  return this.body.evaluate(function augment(context, index) {
    var name = this.names[index];
    if (index < this.names.length - 1) {
      if (context.has(name)) {
        var type = context.top(name);
        if (type.is(VariableType)) {
          // TODO
        } else {
          return context.add(name, type.clone(augment.call(this, type.context, index + 1)));
        }
      } else {
        return context.add(name, UndefinedType.fromContext(augment.call(this, Context.EMPTY, index + 1)));
      }
    } else {
      return context.add(name, this.expression.getType(rootContext));
    }
  }.call(this, context, 0));
};

LetNode.prototype.evaluate = function (context) {
  var rootContext = context;
  return this.body.evaluate(function augment(context, index) {
    var name = this.names[index];
    if (index < this.names.length - 1) {
      if (context.has(name)) {
        var value = context.top(name);
        return context.add(name, value.clone(augment.call(this, value.context, index + 1)));
      } else {
        return context.add(name, UndefinedValue.fromContext(augment.call(this, Context.EMPTY, index + 1)));
      }
    } else {
      return context.add(name, this.expression.evaluate(rootContext));
    }
  }.call(this, context, 0));
};

function ThrowNode(expression) {
  AbstractNode.call(this);
  this.expression = expression;
}

exports.ThrowNode = ThrowNode;
extend(AbstractNode, ThrowNode);

ThrowNode.prototype.getFreeVariables = function () {
  return this.expression.getFreeVariables();
};

ThrowNode.prototype.getType = function () {
  // TODO
};

ThrowNode.prototype.evaluate = function (context) {
  throw new LambdaUserError(this.expression.evaluate(context));
};

function TryCatchNode(tryExpression, catchExpression) {
  AbstractNode.call(this);
  this.tryExpression = tryExpression;
  this.catchExpression = catchExpression;
}

exports.TryCatchNode = TryCatchNode;
extend(AbstractNode, TryCatchNode);

TryCatchNode.prototype.getFreeVariables = function () {
  return this.tryExpression.getFreeVariables().union(
      this.catchExpression().getFreeVariables().filter(function (name) {
        return 'error' !== name;
      }));
};

TryCatchNode.prototype.getType = function () {
  // TODO
};

TryCatchNode.prototype.evaluate = function (context) {
  try {
    return this.tryExpression.evaluate(context);
  } catch (error) {
    if (error instanceof LambdaUserError) {
      return this.catchExpression.evaluate(context.add('error', error.value));
    } else {
      throw error;
    }
  }
};

function TryFinallyNode(tryExpression, finallyExpression) {
  AbstractNode.call(this);
  this.tryExpression = tryExpression;
  this.finallyExpression = finallyExpression;
}

exports.TryFinallyNode = TryFinallyNode;
extend(AbstractNode, TryFinallyNode);

TryFinallyNode.prototype.getFreeVariables = function () {
  return this.tryExpression.getFreeVariables().union(
      this.finallyExpression.getFreeVariables());
};

TryFinallyNode.prototype.getType = function () {
  // TODO
};

TryFinallyNode.prototype.evaluate = function (context) {
  try {
    return this.tryExpression.evaluate(context);
  } catch (error) {
    return UndefinedValue.DEFAULT;
  } finally {
    this.finallyExpression.evaluate(context);
  }
};

function TryCatchFinallyNode(tryExpression, catchExpression, finallyExpression) {
  AbstractValue.call(this);
  this.tryExpression = tryExpression;
  this.catchExpression = catchExpression;
  this.finallyExpression = finallyExpression;
}

exports.TryCatchFinallyNode = TryCatchFinallyNode;
extend(AbstractNode, TryCatchFinallyNode);

TryCatchFinallyNode.prototype.getFreeVariables = function () {
  return this.tryExpression.getFreeVariables()
    .union(this.catchExpression.getFreeVariables().filter(function (name) {
      return 'error' !== name;
    }))
    .union(this.finallyExpression.getFreeVariables());
};

TryCatchFinallyNode.prototype.getType = function () {
  // TODO
};

TryCatchFinallyNode.prototype.evaluate = function (context) {
  try {
    return this.tryExpression.evaluate(context);
  } catch (error) {
    if (error instanceof LambdaUserError) {
      return this.catchExpression.evaluate(context.add('error', error.value));
    } else {
      throw error;
    }
  } finally {
    this.finallyExpression.evaluate(context);
  }
};
<commit_msg>IfNode<commit_after>function AbstractNode() {}

exports.AbstractNode = AbstractNode;

function LiteralNode(value, type) {
  AbstractNode.call(this);
  this.value = value;
  this.type = type;
}

exports.LiteralNode = LiteralNode;
extend(AbstractNode, LiteralNode);

LiteralNode.prototype.getFreeVariables = function () {
  return [];
};

LiteralNode.prototype.getType = function () {
  return this.type;
};

LiteralNode.prototype.evaluate = function () {
  return this.value;
};

function ListLiteralNode(expressions) {
  AbstractNode.call(this);
  this.expressions = expressions;
}

exports.ListLiteralNode = ListLiteralNode;
extend(AbstractNode, ListLiteralNode);

ListLiteralNode.prototype.getFreeVariables = function () {
  return this.expressions.reduce(function (names, expression) {
    return names.union(expression.getFreeVariables());
  }, []);
};

ListLiteralNode.prototype.getType = function (context) {
  return new ListType(this.expressions.map(function (expression) {
    return expression.getType(context);
  }).reduce(function (result, type) {
    return result.merge(type);
  }, UnknownType.DEFAULT));
};

ListLiteralNode.prototype.evaluate = function (context) {
  return new ListValue(this.expressions.map(function (expression) {
    return expression.evaluate(context);
  }));
};

function VariableNode(name) {
  AbstractNode.call(this);
  this.name = name;
}

exports.VariableNode = VariableNode;
extend(AbstractNode, VariableNode);

VariableNode.prototype.getFreeVariables = function () {
  return [this.name];
};

VariableNode.prototype.getType = function (context) {
  if (context.has(this.name)) {
    return context.top(this.name);
  } else {
    return UnknownType.DEFAULT;
  }
};

VariableNode.prototype.evaluate = function (context) {
  if (context.has(this.name)) {
    return context.top(this.name);
  } else {
    return AbstractValue.unmarshal(getGlobalValue(this.name));
  }
};

function ErrorNode() {
  AbstractNode.call(this);
}

exports.ErrorNode = ErrorNode;
extend(AbstractNode, ErrorNode);

ErrorNode.prototype.getFreeVariables = function () {
  return ['error'];
};

ErrorNode.prototype.getType = function (context) {
  if (context.has('error')) {
    return context.top('error');
  } else {
    throw new LambdaTypeError();
  }
};

ErrorNode.prototype.evaluate = function (context) {
  if (context.has('error')) {
    return context.top('error');
  } else {
    throw new LambdaRuntimeError();
  }
};

function FieldAccessNode(left, name) {
  AbstractNode.call(this);
  this.left = left;
  this.name = name;
}

exports.FieldAccessNode = FieldAccessNode;
extend(AbstractNode, FieldAccessNode);

FieldAccessNode.prototype.getFreeVariables = function () {
  return this.left.getFreeVariables();
};

FieldAccessNode.prototype.getType = function (context) {
  var left = this.left.getType(context);
  if (left.context.has(this.name)) {
    return left.context.top(this.name);
  } else {
    throw new LambdaTypeError();
  }
};

FieldAccessNode.prototype.evaluate = function (context) {
  var left = this.left.evaluate(context);
  if (left.context.has(this.name)) {
    return left.context.top(this.name).bindThis(left);
  } else {
    throw new LambdaRuntimeError();
  }
};

function LambdaNode(name, type, body) {
  AbstractNode.call(this);
  this.name = name;
  this.type = type || new VariableType(name);
  this.body = body;
}

exports.LambdaNode = LambdaNode;
extend(AbstractNode, LambdaNode);

LambdaNode.prototype.getFreeVariables = function () {
  return this.body.getFreeVariables().filter(function (name) {
    return name === this.name;
  }, this);
};

LambdaNode.prototype.getType = function (context) {
  return new ClosureType(this.type, this.body.getType(context.add(this.name, this.type)));
};

LambdaNode.prototype.evaluate = function (context) {
  return new Closure(this, context);
};

function ApplicationNode(left, right) {
  AbstractNode.call(this);
  this.left = left;
  this.right = right;
}

exports.ApplicationNode = ApplicationNode;
extend(AbstractNode, ApplicationNode);

ApplicationNode.prototype.getFreeVariables = function () {
  return this.left.getFreeVariables().union(this.right.getFreeVariables());
};

ApplicationNode.prototype.getType = function (context) {
  var left = this.left.getType(context);
  var right = this.right.getType(context);
  if (left.is(ClosureType) && right.isSubTypeOf(left.left)) {
    if (left.left.is(VariableType)) {
      return left.right.instance(left.left.name, right);
    } else if (right.isSubTypeOf(left.left)) {
      return left.right;
    } else {
      throw new LambdaTypeError();
    }
  } else {
    throw new LambdaTypeError();
  }
};

ApplicationNode.prototype.evaluate = function (context) {
  var left = this.left.evaluate(context);
  var right = this.right.evaluate(context);
  if (left.is(Closure)) {
    return left.lambda.body.evaluate(left.capture.add(left.lambda.name, right));
  } else {
    throw new LambdaRuntimeError();
  }
};

function LetNode(names, expression, body) {
  AbstractNode.call(this);
  if (names.length < 1) {
    throw new LambdaInternalError();
  }
  this.names = names;
  this.expression = expression;
  this.body = body;
}

exports.LetNode = LetNode;
extend(AbstractNode, LetNode);

LetNode.prototype.getFreeVariables = function () {
  return this.body.getFreeVariables().filter(function (name) {
    return name !== this.names[0];
  }, this);
};

LetNode.prototype.getType = function (context) {
  var rootContext = context;
  return this.body.evaluate(function augment(context, index) {
    var name = this.names[index];
    if (index < this.names.length - 1) {
      if (context.has(name)) {
        var type = context.top(name);
        if (type.is(VariableType)) {
          // TODO
        } else {
          return context.add(name, type.clone(augment.call(this, type.context, index + 1)));
        }
      } else {
        return context.add(name, UndefinedType.fromContext(augment.call(this, Context.EMPTY, index + 1)));
      }
    } else {
      return context.add(name, this.expression.getType(rootContext));
    }
  }.call(this, context, 0));
};

LetNode.prototype.evaluate = function (context) {
  var rootContext = context;
  return this.body.evaluate(function augment(context, index) {
    var name = this.names[index];
    if (index < this.names.length - 1) {
      if (context.has(name)) {
        var value = context.top(name);
        return context.add(name, value.clone(augment.call(this, value.context, index + 1)));
      } else {
        return context.add(name, UndefinedValue.fromContext(augment.call(this, Context.EMPTY, index + 1)));
      }
    } else {
      return context.add(name, this.expression.evaluate(rootContext));
    }
  }.call(this, context, 0));
};

function IfNode(condition, thenExpression, elseExpression) {
  AbstractNode.call(this);
  this.condition = condition;
  this.thenExpression = thenExpression;
  this.elseExpression = elseExpression;
}

exports.IfNode = IfNode;
extend(AbstractNode, IfNode);

IfNode.prototype.getFreeVariables = function () {
  return this.condition.getFreeVariables()
    .union(this.thenExpression.getFreeVariables())
    .union(this.elseExpression.getFreeVariables());
};

IfNode.prototype.getType = function (context) {
  var condition = this.condition.getType(context);
  if (condition.isSubTypeOf(BooleanType.DEFAULT)) {
    return this.thenExpression.getType(context).merge(this.elseExpression.getType(context));
  } else {
    throw new LambdaTypeError();
  }
};

IfNode.prototype.evaluate = function (context) {
  var condition = this.condition.evaluate(context);
  if (condition.is(BooleanValue)) {
    if (condition.value) {
      return this.thenExpression.evaluate(context);
    } else {
      return this.elseExpression.evaluate(context);
    }
  } else {
    throw new LambdaRuntimeError();
  }
};

function ThrowNode(expression) {
  AbstractNode.call(this);
  this.expression = expression;
}

exports.ThrowNode = ThrowNode;
extend(AbstractNode, ThrowNode);

ThrowNode.prototype.getFreeVariables = function () {
  return this.expression.getFreeVariables();
};

ThrowNode.prototype.getType = function () {
  // TODO
};

ThrowNode.prototype.evaluate = function (context) {
  throw new LambdaUserError(this.expression.evaluate(context));
};

function TryCatchNode(tryExpression, catchExpression) {
  AbstractNode.call(this);
  this.tryExpression = tryExpression;
  this.catchExpression = catchExpression;
}

exports.TryCatchNode = TryCatchNode;
extend(AbstractNode, TryCatchNode);

TryCatchNode.prototype.getFreeVariables = function () {
  return this.tryExpression.getFreeVariables().union(
      this.catchExpression().getFreeVariables().filter(function (name) {
        return 'error' !== name;
      }));
};

TryCatchNode.prototype.getType = function () {
  // TODO
};

TryCatchNode.prototype.evaluate = function (context) {
  try {
    return this.tryExpression.evaluate(context);
  } catch (error) {
    if (error instanceof LambdaUserError) {
      return this.catchExpression.evaluate(context.add('error', error.value));
    } else {
      throw error;
    }
  }
};

function TryFinallyNode(tryExpression, finallyExpression) {
  AbstractNode.call(this);
  this.tryExpression = tryExpression;
  this.finallyExpression = finallyExpression;
}

exports.TryFinallyNode = TryFinallyNode;
extend(AbstractNode, TryFinallyNode);

TryFinallyNode.prototype.getFreeVariables = function () {
  return this.tryExpression.getFreeVariables().union(
      this.finallyExpression.getFreeVariables());
};

TryFinallyNode.prototype.getType = function () {
  // TODO
};

TryFinallyNode.prototype.evaluate = function (context) {
  try {
    return this.tryExpression.evaluate(context);
  } catch (error) {
    return UndefinedValue.DEFAULT;
  } finally {
    this.finallyExpression.evaluate(context);
  }
};

function TryCatchFinallyNode(tryExpression, catchExpression, finallyExpression) {
  AbstractValue.call(this);
  this.tryExpression = tryExpression;
  this.catchExpression = catchExpression;
  this.finallyExpression = finallyExpression;
}

exports.TryCatchFinallyNode = TryCatchFinallyNode;
extend(AbstractNode, TryCatchFinallyNode);

TryCatchFinallyNode.prototype.getFreeVariables = function () {
  return this.tryExpression.getFreeVariables()
    .union(this.catchExpression.getFreeVariables().filter(function (name) {
      return 'error' !== name;
    }))
    .union(this.finallyExpression.getFreeVariables());
};

TryCatchFinallyNode.prototype.getType = function () {
  // TODO
};

TryCatchFinallyNode.prototype.evaluate = function (context) {
  try {
    return this.tryExpression.evaluate(context);
  } catch (error) {
    if (error instanceof LambdaUserError) {
      return this.catchExpression.evaluate(context.add('error', error.value));
    } else {
      throw error;
    }
  } finally {
    this.finallyExpression.evaluate(context);
  }
};
<|endoftext|>


<commit_before>import React, { Component } from "react";
import { Layout, Header, Content, Spinner } from "react-mdl";
import { graphql } from "react-apollo";
import gql from 'graphql-tag';

import TodoItem from "./TodoItem";

const query = gql`
  query allTodoItems {
    allTodoItems {
      id
      name
      description
      completed
    }
  }
`;

class App extends Component {
  render() {
    console.log(this.props.data);
    const { data: { loading, allTodoItems } } = this.props;
    return (
      <Layout fixedHeader>

        <Content>
          { loading ? <Spinner /> : (

            { allTodoItems.map((item) => <TodoItem key={item.id} { ...item } />) }

          )}
        </Content>
      </Layout>
    );
  }
}

export default graphql(query)(App);
<commit_msg>Removed console.log.<commit_after>import React, { Component } from "react";
import { Layout, Header, Content, Spinner } from "react-mdl";
import { graphql } from "react-apollo";
import gql from "graphql-tag";

import TodoItem from "./TodoItem";

const query = gql`
  query allTodoItems {
    allTodoItems {
      id
      name
      description
      completed
    }
  }
`;

class App extends Component {
  render() {
    const { data: { loading, allTodoItems } } = this.props;
    return (
      <Layout fixedHeader>

        <Content>
          { loading ? <Spinner /> : (

            { allTodoItems.map((item) => <TodoItem key={item.id} { ...item } />) }

          )}
        </Content>
      </Layout>
    );
  }
}

export default graphql(query)(App);
<|endoftext|>