<commit_before>/*
 * JavaScript for audit result page
 */

var create_name = function(text) {
  // Convert text to lower case.
  var name = text.toLowerCase();

  // Remove leading and trailing spaces, and any non-alphanumeric
  // characters except for ampersands, spaces and dashes.
  name = name.replace(/^\s+|\s+$|[^a-z0-9&\s-]/g, '');

  // Replace '&' with 'and'.
  name = name.replace(/&/g, 'and');

  // Replaces spaces with dashes.
  name = name.replace(/\s/g, '-');

  // Squash any duplicate dashes.
  name = name.replace(/(-)+\1/g, "$1");

  return name;
};

var add_link = function(currentSelector, suffix) {
  // Convert the h2 element text into a value that
  // is safe to use in a name attribute.
//  var selectorText='.toggle-master-'.concat(suffix);
  var name = create_name(currentSelector.text());

  // Create a name attribute in the toggle elements
  // to act as a fragment anchor.
  $('.toggle-'.concat(suffix)).attr('name', name);
  // Replace the .toggle-master element with a link to the
  // fragment anchor.
  $(currentSelector).html(
    '' +
    $(currentSelector).html() + '');
};

var toggle_url = function(event) {
    event.preventDefault();
  // Toggle the 'expanded' class of the toggle-master
  // element, then apply the slideToggle effect
  // to toggle element to hide/display.
  $(this).toggleClass('expanded');
  $('.toggle-url').slideToggle('slow');
};

var toggle_parameters = function(event) {
    event.preventDefault();
    // Toggle the 'expanded' class of the toggle-master
    // element, then apply the slideToggle effect
    // to toggle element to hide/display.
    $(this).toggleClass('expanded');
    $('.toggle-parameters').slideToggle('slow');
};

var toggle_display_parameters = function(event) {
    event.preventDefault();
    // Toggle the 'expanded' class of the toggle-master
    // element, then apply the slideToggle effect
    // to toggle element to hide/display.
    $(this).toggleClass('expanded');
    $('.toggle-display-parameters').slideToggle('slow');
};

var remove_focus = function() {
  // Use the blur() method to remove focus.
  $(this).blur();
};

var update_class_name = function(text) {
    $('._'.concat(text)).
        removeClass('_'.concat(text)).
        addClass(text);
}

var initialize_toogle = function(text) {
    update_class_name('toggle-'.concat(text));
    update_class_name('toggle-master-'.concat(text));
    update_class_name('expanded');

    // Add a link to each toggle element.
    var selector= $('.toggle-master-'.concat(text));
    if ( selector.length ) {
        add_link(selector,text);
    }

    selector= $('.toggle-master-'.concat(text,':not(.expanded)'));
    if ( selector.length ) {
        $('.toggle-'.concat(text)).hide();
    }

    // Remove the focus from the link tag when accessed with a mouse.
    selector= $('.toggle-master-'.concat(text,' a'));
    selector.mouseup(remove_focus);
};

$(document).ready (function (){
    initialize_toogle('parameters');
    // Add a click event handler to all toggle elements.
    $('.toggle-master-parameters').click(toggle_parameters);

    initialize_toogle('url');
    // Add a click event handler to all toggle elements.
    $('.toggle-master-url').click(toggle_url);

    initialize_toogle('display-parameters');
    // Add a click event handler to all toggle elements.
    $('.toggle-master-display-parameters').click(toggle_display_parameters);
});
<commit_msg>Feature #254 : tgol-web-app : Evolution of the web-application interface to use the bootstrap UI toolkit (accelerate the toggle when display input textarea in set-up form)<commit_after>/*
 * JavaScript for audit result page
 */

var create_name = function(text) {
  // Convert text to lower case.
  var name = text.toLowerCase();

  // Remove leading and trailing spaces, and any non-alphanumeric
  // characters except for ampersands, spaces and dashes.
  name = name.replace(/^\s+|\s+$|[^a-z0-9&\s-]/g, '');

  // Replace '&' with 'and'.
  name = name.replace(/&/g, 'and');

  // Replaces spaces with dashes.
  name = name.replace(/\s/g, '-');

  // Squash any duplicate dashes.
  name = name.replace(/(-)+\1/g, "$1");

  return name;
};

var add_link = function(currentSelector, suffix) {
  // Convert the h2 element text into a value that
  // is safe to use in a name attribute.
//  var selectorText='.toggle-master-'.concat(suffix);
  var name = create_name(currentSelector.text());

  // Create a name attribute in the toggle elements
  // to act as a fragment anchor.
  $('.toggle-'.concat(suffix)).attr('name', name);
  // Replace the .toggle-master element with a link to the
  // fragment anchor.
  $(currentSelector).html(
    '' +
    $(currentSelector).html() + '');
};

var toggle_url = function(event) {
    event.preventDefault();
  // Toggle the 'expanded' class of the toggle-master
  // element, then apply the slideToggle effect
  // to toggle element to hide/display.
  $(this).toggleClass('expanded');
  $('.toggle-url').toggle('fast');
};

var toggle_parameters = function(event) {
    event.preventDefault();
    // Toggle the 'expanded' class of the toggle-master
    // element, then apply the slideToggle effect
    // to toggle element to hide/display.
    $(this).toggleClass('expanded');
    $('.toggle-parameters').toggle('fast');
};

var toggle_display_parameters = function(event) {
    event.preventDefault();
    // Toggle the 'expanded' class of the toggle-master
    // element, then apply the slideToggle effect
    // to toggle element to hide/display.
    $(this).toggleClass('expanded');
    $('.toggle-display-parameters').toggle('fast');
};

var remove_focus = function() {
  // Use the blur() method to remove focus.
  $(this).blur();
};

var update_class_name = function(text) {
    $('._'.concat(text)).
        removeClass('_'.concat(text)).
        addClass(text);
}

var initialize_toogle = function(text) {
    update_class_name('toggle-'.concat(text));
    update_class_name('toggle-master-'.concat(text));
    update_class_name('expanded');

    // Add a link to each toggle element.
    var selector= $('.toggle-master-'.concat(text));
    if ( selector.length ) {
        add_link(selector,text);
    }

    selector= $('.toggle-master-'.concat(text,':not(.expanded)'));
    if ( selector.length ) {
        $('.toggle-'.concat(text)).hide();
    }

    // Remove the focus from the link tag when accessed with a mouse.
    selector= $('.toggle-master-'.concat(text,' a'));
    selector.mouseup(remove_focus);
};

$(document).ready (function (){
    initialize_toogle('parameters');
    // Add a click event handler to all toggle elements.
    $('.toggle-master-parameters').click(toggle_parameters);

    initialize_toogle('url');
    // Add a click event handler to all toggle elements.
    $('.toggle-master-url').click(toggle_url);

    initialize_toogle('display-parameters');
    // Add a click event handler to all toggle elements.
    $('.toggle-master-display-parameters').click(toggle_display_parameters);
});
<|endoftext|>


<commit_before>/* globals performance */

document.write(
  `
    <!DOCTYPE html>
    <meta charset="utf-8">
    <style>

  body { font: 12px Arial;}

  path {
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
  }

    .axis path,
    .axis line {
      fill: none;
      stroke: grey;
      stroke-width: 1;
      shape-rendering: crispEdges;
    }

  </style>
    <body>

    <script src="bench/d3.v3.min.js"></script>

    <script>

  // Set the dimensions of the canvas / graph
  var margin = {top: 30, right: 20, bottom: 30, left: 50},
  width = 600 - margin.left - margin.right,
  height = 270 - margin.top - margin.bottom;

  // Parse the date / time
  var parseDate = d3.time.format("%d-%b-%y").parse;

  // Set the ranges
  var x = d3.time.scale().range([0, width]);
  var y = d3.scale.linear().range([height, 0]);

  // Define the axes
  var xAxis = d3.svg.axis().scale(x)
      .orient("bottom").ticks(5);

  var yAxis = d3.svg.axis().scale(y)
      .orient("left").ticks(5);

  // Define the line
  var valueline = d3.svg.line()
      .x(function(d) { return x(d.date); })
      .y(function(d) { return y(d.close); });

  var req = new XMLHttpRequest();
  req.open("GET", 'bench/test_data.json', true);
  req.onreadystatechange = function ()
  {
    if(req.readyState === 4 && (req.status === 200 || req.status == 0))
    {
      var json = JSON.parse(req.responseText)

      Object.keys(json[0].testData).map(function (testCase) {
        var header = document.createElement('h1')
        header.innerHTML = testCase

        document.body.appendChild(header)

      })

      var data = []

      for (var i = 0; i < json.length; i++) {
        data.push({
          date: new Date(json[i].timestamp*1000),
          close: json[i].testData.cube.time.mean})
      }

      // Adds the svg canvas
      var svg = d3.select("body")
          .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

      // Scale the range of the data
      x.domain(d3.extent(data, function(d) { return d.date; }));
      y.domain([0, d3.max(data, function(d) { return d.close; })]);

      // Add the valueline path.
      svg.append("path")
        .attr("class", "line")
        .attr("d", valueline(data));

      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);
    }
  }
  req.send(null);

  </script>
    </body>
    `);
<commit_msg>Added a tooltip, that appears when hovering over a datapoint.<commit_after>/* globals performance */

document.write(
  `
    <!DOCTYPE html>
    <meta charset="utf-8">
    <style>

  path {
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
  }

    .axis path,
    .axis line {
      fill: none;
      stroke: grey;
      stroke-width: 1;
      shape-rendering: crispEdges;
    }

  div.tooltip {
    position: absolute;
    text-align: center;
    width: 60px;
    height: 28px;
    padding: 2px;
    font: 12px sans-serif;
    background: lightsteelblue;
    border: 0px;
    border-radius: 8px;
    pointer-events: none;
}

  </style>
    <body>

    <script src="bench/d3.v3.min.js"></script>

    <script>

  // Set the dimensions of the canvas / graph
  var margin = {top: 30, right: 20, bottom: 30, left: 50},
  width = 600 - margin.left - margin.right,
  height = 270 - margin.top - margin.bottom;

  // Parse the date / time
  var parseDate = d3.time.format("%d-%b-%y").parse;

  // Set the ranges
  var x = d3.time.scale().range([0, width]);
  var y = d3.scale.linear().range([height, 0]);

  // Define the axes
  var xAxis = d3.svg.axis().scale(x)
      .orient("bottom").ticks(5);

  var yAxis = d3.svg.axis().scale(y)
      .orient("left").ticks(5);

  // Define the line
  var valueline = d3.svg.line()
      .x(function(d) { return x(d.date); })
      .y(function(d) { return y(d.testData.time.mean); });

// Define the div for the tooltip
var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

  var req = new XMLHttpRequest();
  req.open("GET", 'bench/test_data.json', true);
  req.onreadystatechange = function ()
  {
    if(req.readyState === 4 && (req.status === 200 || req.status == 0))
    {
      var json = JSON.parse(req.responseText)

      Object.keys(json[0].testData).map(function (testCase) {
        //               console.log('testCase: ', testCase)

        var header = document.createElement('h1')
        header.innerHTML = testCase

        document.body.appendChild(header)

      })

      var data = []

      for (var i = 0; i < json.length; i++) {
        data.push({
          date: new Date(json[i].timestamp*1000),
          close: json[i].testData.cube.time.mean,
          testData: json[i].testData.cube
        })

        console.log("d, ", json[i].testData.cube.time.mean)

      }

      // Adds the svg canvas
      var svg = d3.select("body")
          .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

      // Scale the range of the data
      x.domain(d3.extent(data, function(d) { return d.date; }));
      y.domain([0, d3.max(data, function(d) { return d.testData.time.mean; })]);

      // Add the valueline path.
      svg.append("path")
        .attr("class", "line")
        .attr("d", valueline(data));

      svg.selectAll("dot")
	.data(data)
	.enter().append("circle")
	.attr("r", 2)
	.attr("cx", function(d) { return x(d.date); })
	.attr("cy", function(d) { return y(d.testData.time.mean); })
        .on("mouseover", function(d) {
            div.transition()
                .duration(200)
                .style("opacity", .9);
            div	.html("loltime" + "<br/>"  + d.testData.time.mean )
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY - 28) + "px");
            })

      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);
    }
  }
  req.send(null);

  </script>
    </body>
    `);
<|endoftext|>


<commit_before>'use strict';

$(document).ready(function() {
  var acOutput = $('#results-ac-output'),
      qHistory = $('#query-history'),
      q = $('#q'),
      body = $('body'),
      search = $('.search'),
      status = $('.status'),
      layoutToggle = $('.layout-toggle'),
      lastPushState = null,
      pushQueryState = function(query) {
        var state = {q: query};

        // Avoid duplicate states, ex. user clicks a history link and then
        // a search result associated with the same query.
        if (JSON.stringify(lastPushState) == JSON.stringify(state)) {
          return;
        }

        lastPushState = $.extend({}, state);
        history.pushState(lastPushState, '', '?q=' + encodeURIComponent(query));
      },
      reDownloadMsg = 'Will download in next cycle.';

  q.autocomplete({
    delay: 100,
    create: function(event, ui) {
      // Allow 'q?=keyword' URI to trigger initial search.
      var uriQuery = q.val();
      if (uriQuery) {
        // Avoid duplicate states, ex. user goes directory to 'q?=css' and then
        // a search result associated with the same query.
        lastPushState = {q: uriQuery};

        q.autocomplete('search', uriQuery);
      }
    },
    source: function(request, response) {
      $.ajax({
        url: '/q.php',
        dataType: 'jsonp',
        data: {
          q: request.term
        },
        success: function(data) {
          acOutput.empty();
          response(data);
        }
      });
    }
  })
  .data('autocomplete')._renderItem = function(ul, item) {
    item.tags = item.tags ? '(' + item.tags + ')' : '';
    var a = $(''),
        ft = $('

'),
        li = $('

'),
        dlBtnMsg = item.downloaded ? 'Download Again' : reDownloadMsg;

    ft.append('
' + item.excerpt + '
');

    if (!/nosave/.test(item.tags)) {
      ft.append(
        $('
')
        .append('View Saved Copy')
        .append('' + dlBtnMsg + '')
      );
    }

    a.attr('href', item.uri);
    a.appendTo(li);
    a.data('item.autocomplete', item)
      .append('
' + item.title + '
')
      .append('
' + item.domain + ' ' + item.tags + '
')
      .append(ft);

    li.appendTo(acOutput);
  };

  // Open a new tab with the marked URI.
  acOutput.delegate('.link-wrap', 'click', function(e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    var a = $(this),
        openUri = function() {
          pushQueryState(q.val());
          window.location = a.attr('href');
        };

    $.ajax({
      url: 'add_history.php',
      dataType: 'jsonp',
      data: { q: q.val() },
      success: openUri,
      error: openUri
    });
  });

  // Reveal 'View Saved Copy' links when hovering over a result.
  acOutput.on(
    'hover',
    'a',
    function(e) {
      $('.viewer-toggle-on', acOutput).removeClass('viewer-toggle-on');
      $('.viewer-toggle', this).addClass('viewer-toggle-on');
    }
  );

  // Display the saved copy content below the 'View Saved Copy' link.
  acOutput.on('click', '.viewer-view-copy', function(e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    var viewerToggle = $(this),
        a = viewerToggle.closest('.link-wrap'),
        ft = viewerToggle.closest('.ft'),
        markId = ft.data('id'),
        iframeId = 'viewer-' + markId,
        iframe = $('#' + iframeId),
        scrollResultIntoView = function() {
          // Scroll to position the search result at the top.
          a.get(0).scrollIntoView(true);
        };

    // Hide/show the iframe if it's already in the DOM.
    if (iframe.length) {
      iframe.toggle();
      scrollResultIntoView();
      return;
    }

    var src = 'view.php?markId=' + markId;

    // Remove previously opened saved copy.
    $('iframe', acOutput).remove();

    // Add the new saved copy.
    ft.append('');

    scrollResultIntoView();
  });

  // Flag a mark for re-download.
  acOutput.on('click', '.viewer-dl-again', function(e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    var reDownloadBtn = $(this),
        ft = reDownloadBtn.closest('.ft'),
        markId = ft.data('id');

    $.ajax({
      url: 'redownload.php',
      dataType: 'jsonp',
      data: {
        markId: markId
      },
      success: function(data) {
        if (data.scheduled) {
          reDownloadBtn.text(reDownloadMsg);
        } else {
          reDownloadBtn.text('Could not schedule download.');
        }
      },
      error: function() {
        reDownloadBtn.text('Could not contact server.');
      }
    });
  });

  // Populate and submit the search box with a prior query.
  $('#query-history').on('click', '.past-query', function(event) {
    event.preventDefault();

    var query = $(this),
        qText = query.text();
    q.val(qText);
    q.autocomplete('search', qText);
    pushQueryState(qText);
  });

  // Swap search/status elements.
  layoutToggle.on('click', function(event) {
    event.preventDefault();
    status.toggle();
    search.toggle();
  });

  // Swap search/status elements.
  body.on('click', '.add-mark-open', function(event) {
    event.preventDefault();
    $('#add-mark-modal').modal();
    $('#add-mark-modal input:first').focus();
  });

  body.on('submit', '.add-mark-form', function(event) {
    event.preventDefault();
    $.ajax({
      url: '/add_mark.php',
      type: 'POST',
      dataType: 'jsonp',
      data: $(this).serialize()
    });
  });

  // Populate history.
  $.ajax({
    url: 'get_history.php',
    dataType: 'jsonp',
    success: function(data) {
      if (data.length) {
        $.each(data, function(pos, item) {
          qHistory.append('' + item.query + '');
        });
      }
    }
  });

  // Populate error log.
  $.ajax({
    url: 'get_error_log.php',
    dataType: 'jsonp',
    success: function(data) {
      var ul = $('#error-log');

      if (!data.length) {
        ul.append('
No errors.
');
        return;
      }

      $.each(data, function(pos, item) {
        var matches = item.last_err.match(/^([^\{]+)(.*)$/),
          message = matches[1].replace(/: $/, ''),
          detail = JSON.parse(matches[2]),
          li = $('
');

          message = message || 'HTTP code: ' + detail.http_code;

          li.append(
            $('
')
            .append('retry')
            .append('' + item.title + '')
          );
          li.append('
' + item.uri + '
')
          li.append('
' + message + '
')
          ul.append(li);
      });
    }
  });

  // Remove an mark's error state.
  $('#error-log').on('click', '.retry', function(event) {
    event.preventDefault();

    var markId = $(this).data('id'),
        logItem = $('#error-log-' + markId),
        logBtn = $('.mark-action-btn', logItem);

    $.ajax({
      url: '/retry.php',
      dataType: 'jsonp',
      data: {
        markId: markId
      },
      success: function(data) {
        if (data.removed) {
          logBtn.remove();
          logItem.addClass('invalid');
        } else {
          logBtn.text('Could not schedule retry.');
        }
      },
      error: function() {
        logBtn.text('Could not contact server.');
      }
    });
  });

  // Respond to back-navigation by applying the saved (search query) state.
  window.onpopstate = function(e) {
    if (e.state && e.state.q) {
      q.val(e.state.q);
      q.autocomplete('search', e.state.q);
    }
  };

  q.focus();
});
<commit_msg>ADD auto-focus after modal closure, ADD ctrl-{s,a} shortcuts.<commit_after>'use strict';

$(document).ready(function() {
  var acOutput = $('#results-ac-output'),
      qHistory = $('#query-history'),
      q = $('#q'),
      body = $('body'),
      search = $('.search'),
      status = $('.status'),
      layoutToggle = $('.layout-toggle'),
      lastPushState = null,
      pushQueryState = function(query) {
        var state = {q: query};

        // Avoid duplicate states, ex. user clicks a history link and then
        // a search result associated with the same query.
        if (JSON.stringify(lastPushState) == JSON.stringify(state)) {
          return;
        }

        lastPushState = $.extend({}, state);
        history.pushState(lastPushState, '', '?q=' + encodeURIComponent(query));
      },
      reDownloadMsg = 'Will download in next cycle.';

  q.autocomplete({
    delay: 100,
    create: function(event, ui) {
      // Allow 'q?=keyword' URI to trigger initial search.
      var uriQuery = q.val();
      if (uriQuery) {
        // Avoid duplicate states, ex. user goes directory to 'q?=css' and then
        // a search result associated with the same query.
        lastPushState = {q: uriQuery};

        q.autocomplete('search', uriQuery);
      }
    },
    source: function(request, response) {
      $.ajax({
        url: '/q.php',
        dataType: 'jsonp',
        data: {
          q: request.term
        },
        success: function(data) {
          acOutput.empty();
          response(data);
        }
      });
    }
  })
  .data('autocomplete')._renderItem = function(ul, item) {
    item.tags = item.tags ? '(' + item.tags + ')' : '';
    var a = $(''),
        ft = $('

'),
        li = $('

'),
        dlBtnMsg = item.downloaded ? 'Download Again' : reDownloadMsg;

    ft.append('
' + item.excerpt + '
');

    if (!/nosave/.test(item.tags)) {
      ft.append(
        $('
')
        .append('View Saved Copy')
        .append('' + dlBtnMsg + '')
      );
    }

    a.attr('href', item.uri);
    a.appendTo(li);
    a.data('item.autocomplete', item)
      .append('
' + item.title + '
')
      .append('
' + item.domain + ' ' + item.tags + '
')
      .append(ft);

    li.appendTo(acOutput);
  };

  // Open a new tab with the marked URI.
  acOutput.delegate('.link-wrap', 'click', function(e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    var a = $(this),
        openUri = function() {
          pushQueryState(q.val());
          window.location = a.attr('href');
        };

    $.ajax({
      url: 'add_history.php',
      dataType: 'jsonp',
      data: { q: q.val() },
      success: openUri,
      error: openUri
    });
  });

  // Reveal 'View Saved Copy' links when hovering over a result.
  acOutput.on(
    'hover',
    'a',
    function(e) {
      $('.viewer-toggle-on', acOutput).removeClass('viewer-toggle-on');
      $('.viewer-toggle', this).addClass('viewer-toggle-on');
    }
  );

  // Display the saved copy content below the 'View Saved Copy' link.
  acOutput.on('click', '.viewer-view-copy', function(e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    var viewerToggle = $(this),
        a = viewerToggle.closest('.link-wrap'),
        ft = viewerToggle.closest('.ft'),
        markId = ft.data('id'),
        iframeId = 'viewer-' + markId,
        iframe = $('#' + iframeId),
        scrollResultIntoView = function() {
          // Scroll to position the search result at the top.
          a.get(0).scrollIntoView(true);
        };

    // Hide/show the iframe if it's already in the DOM.
    if (iframe.length) {
      iframe.toggle();
      scrollResultIntoView();
      return;
    }

    var src = 'view.php?markId=' + markId;

    // Remove previously opened saved copy.
    $('iframe', acOutput).remove();

    // Add the new saved copy.
    ft.append('');

    scrollResultIntoView();
  });

  // Flag a mark for re-download.
  acOutput.on('click', '.viewer-dl-again', function(e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    var reDownloadBtn = $(this),
        ft = reDownloadBtn.closest('.ft'),
        markId = ft.data('id');

    $.ajax({
      url: 'redownload.php',
      dataType: 'jsonp',
      data: {
        markId: markId
      },
      success: function(data) {
        if (data.scheduled) {
          reDownloadBtn.text(reDownloadMsg);
        } else {
          reDownloadBtn.text('Could not schedule download.');
        }
      },
      error: function() {
        reDownloadBtn.text('Could not contact server.');
      }
    });
  });

  // Populate and submit the search box with a prior query.
  $('#query-history').on('click', '.past-query', function(event) {
    event.preventDefault();

    var query = $(this),
        qText = query.text();
    q.val(qText);
    q.autocomplete('search', qText);
    pushQueryState(qText);
  });

  // Swap search/status elements.
  layoutToggle.on('click', function(event) {
    event.preventDefault();
    status.toggle();
    search.toggle();
  });

  var openAddMarkModal = function() {
    $('#add-mark-modal').modal();
    $('#add-mark-modal input:first').focus();
  };

  var focusSearch = function() {
    q.focus();
  };

  // Swap search/status elements.
  body.on('click', '.add-mark-open', function(event) {
    event.preventDefault();
    openAddMarkModal();
  });

  body.on('submit', '.add-mark-form', function(event) {
    event.preventDefault();
    $.ajax({
      url: '/add_mark.php',
      type: 'POST',
      dataType: 'jsonp',
      data: $(this).serialize(),
      success: function() {
        $('#add-mark-modal').modal('hide');
        focusSearch();
      }
    });
  });

  body.on('keydown', function(e) {
    if (e.ctrlKey) {
      if (65 === e.keyCode) { // ctrl-a
        openAddMarkModal();
      } else if (83 === e.keyCode) { // ctrl-s
        focusSearch();
      }
    }
  });

  $('#add-mark-modal').on('hidden', function() {
    focusSearch();
  });

  // Populate history.
  $.ajax({
    url: 'get_history.php',
    dataType: 'jsonp',
    success: function(data) {
      if (data.length) {
        $.each(data, function(pos, item) {
          qHistory.append('' + item.query + '');
        });
      }
    }
  });

  // Populate error log.
  $.ajax({
    url: 'get_error_log.php',
    dataType: 'jsonp',
    success: function(data) {
      var ul = $('#error-log');

      if (!data.length) {
        ul.append('
No errors.
');
        return;
      }

      $.each(data, function(pos, item) {
        var matches = item.last_err.match(/^([^\{]+)(.*)$/),
          message = matches[1].replace(/: $/, ''),
          detail = JSON.parse(matches[2]),
          li = $('
');

          message = message || 'HTTP code: ' + detail.http_code;

          li.append(
            $('
')
            .append('retry')
            .append('' + item.title + '')
          );
          li.append('
' + item.uri + '
')
          li.append('
' + message + '
')
          ul.append(li);
      });
    }
  });

  // Remove an mark's error state.
  $('#error-log').on('click', '.retry', function(event) {
    event.preventDefault();

    var markId = $(this).data('id'),
        logItem = $('#error-log-' + markId),
        logBtn = $('.mark-action-btn', logItem);

    $.ajax({
      url: '/retry.php',
      dataType: 'jsonp',
      data: {
        markId: markId
      },
      success: function(data) {
        if (data.removed) {
          logBtn.remove();
          logItem.addClass('invalid');
        } else {
          logBtn.text('Could not schedule retry.');
        }
      },
      error: function() {
        logBtn.text('Could not contact server.');
      }
    });
  });

  // Respond to back-navigation by applying the saved (search query) state.
  window.onpopstate = function(e) {
    if (e.state && e.state.q) {
      q.val(e.state.q);
      q.autocomplete('search', e.state.q);
    }
  };

  focusSearch();
});
<|endoftext|>


<commit_before>// Eval Template Modify JS for Utilities
// @author lovemore.nalube@uct.ac.za

var evalTemplateUtils = (function() {

    //Configurable private variables
    var canDebug = true,
            canDebugLevels = "info,debug,warn,error", //Comma delimitated set of the debug levels to show. Select from info,debug,warn,error
            entityTemplateItemURL = "/direct/eval-templateitem/:ID:.xml",
            messgeBundlePath = "/direct/eval-resources/message-bundle.json",

    // Dont configure these vars
            templateId = 0,
            pagesLoadedByFBwithJs = [],
            messageBundle = {},
            closedGroups = [];     // keep track of groups a user closes: EVALSYS-825

    function resizeFrame(updown, height) {
        try {
            var thisHeight = typeof height === "undefined" ? 280 : Number(height) + 40,
                frame = parent.document.getElementById(window.name),
                clientH = "";

            if (frame) {
                if (updown === -1) {
                    clientH = document.body.clientHeight;
                }
                else {
                    clientH = document.body.clientHeight + thisHeight; //increasing the height
                }
                $(frame).height(clientH);
            }
        } catch(e) {
            evalTemplateUtils.debug.error("Frame resize did not work. Error: %o", e, e);
        }
    }

    // Format bundle path for user locale
    var loadMessageBundle = function(){
        $.ajax({
            url: messgeBundlePath,
            global: false,
            cache: true,
            dataType : "json",
            success: function(messageBundleJSON){
                messageBundle = messageBundleJSON.data;
            }
        });
    };

    //public data
    return {
        entity:{
            getTemplateItemURL: function(id) {
                return entityTemplateItemURL.replace(":ID:", id);
            }
        },
        //keep frame size before grow
        frameSize: 0,
        //keep iframe scroll height
        frameScrollHeight: 0,
        frameGrow: function(height) {
            resizeFrame(1, height);
        },
        frameShrink: function(height) {
            resizeFrame(-1, height);
        },
        debug: {
            info : function() {
            },
            debug : function() {
            },
            warn : function() {
            },
            error : function() {
            },
            group : function() {
            },
            groupEnd : function() {
            },
            time : function() {
            },
            timeEnd : function() {
            }
        },
        vars: {
            groupableItems : [],
            isIE : false
        },
        init: function() {
            // Debugging. Acts on Firebug console methods described at http://getfirebug.com/console.html
            if (canDebug && typeof console !== "undefined") {
                if (typeof console.info !== "undefined" && canDebugLevels.search(/info/i) !== -1) {
                    evalTemplateUtils.debug.info = console.info;
                }
                if (typeof console.debug !== "undefined" && canDebugLevels.search(/debug/i) !== -1) {
                    evalTemplateUtils.debug.debug = console.debug;
                }
                if (typeof console.warn !== "undefined" && canDebugLevels.search(/warn/i) !== -1) {
                    evalTemplateUtils.debug.warn = console.warn;
                }
                if (typeof console.error !== "undefined" && canDebugLevels.search(/error/i) !== -1) {
                    evalTemplateUtils.debug.error = console.error;
                }
                if (typeof console.group !== "undefined") {
                    evalTemplateUtils.debug.group = console.group;
                }
                if (typeof console.groupEnd !== "undefined") {
                    evalTemplateUtils.debug.groupEnd = console.groupEnd;
                }
                if (typeof console.time !== "undefined") {
                    evalTemplateUtils.debug.time = console.time;
                }
                if (typeof console.timeEnd !== "undefined") {
                    evalTemplateUtils.debug.timeEnd = console.timeEnd;
                }
            }
            //browser check
            evalTemplateUtils.vars.isIE = $.browser.msie;

            // Message Locale bundle loader
            loadMessageBundle();

            templateId = $('input[name=templateId]:hidden').val();
        },
        pages: {
                modify_item_page: "modify_item",
                modify_template_page: "modify_template",
                modify_block_page: "modify_block",
                choose_existing_page: "choose_existing_items",
                choose_expert_page: "choose_expert_category",
                eb_save_order: "/direct/eval-templateitem/template-items-reorder",
                eb_block_edit: "/direct/eval-templateitem/modify-block-items",
                preview_item_page: "preview_item"
            },
        getPageType: function(url){
            evalTemplateUtils.debug.group("Getting the page type/name");
            var pageType = undefined,
                    i = 0,
                    regExp = null;
            pagesLoadedByFBwithJs = [ evalTemplateUtils.pages.modify_item_page, evalTemplateUtils.pages.choose_expert_page,
                evalTemplateUtils.pages.modify_template_page, evalTemplateUtils.pages.modify_block_page,
                evalTemplateUtils.pages.choose_existing_page, evalTemplateUtils.pages.preview_item_page];
            evalTemplateUtils.debug.debug("Pages supported are %s", pagesLoadedByFBwithJs.toString());
            for ( i in pagesLoadedByFBwithJs){
                if ( typeof pageType == "undefined" ){
                    regExp = new RegExp(pagesLoadedByFBwithJs[i]);
                    evalTemplateUtils.debug.debug("Checking url against page filter %s and regExp %o", pagesLoadedByFBwithJs[i], regExp);
                    pageType =  ( url.search(regExp) !== -1 ) ? pagesLoadedByFBwithJs[i] : undefined ;
                    evalTemplateUtils.debug.debug("Page type is %s", pageType);
                }
            }
            evalTemplateUtils.debug.info("Page type found as: %s", pageType);
            evalTemplateUtils.debug.groupEnd();
            return pageType;
        },
        //retrieve the message strings for key
        messageLocator: function(key, params){
            return fluid.messageLocator( messageBundle )([key], params);
        },

        // Remember the groups a user closes: EVALSYS-825
        closedGroup : {
            add : function(groupId){
                if( groupId ){
                    if ( $.inArray(groupId, closedGroups) === -1){
                        closedGroups.push(groupId);
                        evalTemplateUtils.debug.info("Closed %s", groupId);
                    }
                }
                evalTemplateUtils.debug.warn("closedGroups %o", closedGroups);
            },
            remove : function(groupId){
                if( groupId && $.inArray(groupId, closedGroups) > -1){
                    var index;
                    for ( var i in closedGroups){
                        if ( closedGroups[i] === groupId ){
                            index = i;
                        }
                    }
                    closedGroups.splice(index, 1);
                    evalTemplateUtils.debug.info("Opened %s", groupId);
                }
                evalTemplateUtils.debug.warn("closedGroups %o", closedGroups);
            },
            get : closedGroups
        },

        // DOM values retrieval functions
        getTemplateId:  function(){return templateId;},
        getTemplateItemId: function(that){
            return that.parents('.itemRow').find('input[name=template-item-id]:hidden').val();
        },
        getItemClassification: function(that){
            return that.parents('.itemRow').find('input[name=item-classification]:hidden').val();
        }

        };

})($);

//init evalUtils
evalTemplateUtils.init();<commit_msg>debug mode off<commit_after>// Eval Template Modify JS for Utilities
// @author lovemore.nalube@uct.ac.za

var evalTemplateUtils = (function() {

    //Configurable private variables
    var canDebug = false,
            canDebugLevels = "info,debug,warn,error", //Comma delimitated set of the debug levels to show. Select from info,debug,warn,error
            entityTemplateItemURL = "/direct/eval-templateitem/:ID:.xml",
            messgeBundlePath = "/direct/eval-resources/message-bundle.json",

    // Dont configure these vars
            templateId = 0,
            pagesLoadedByFBwithJs = [],
            messageBundle = {},
            closedGroups = [];     // keep track of groups a user closes: EVALSYS-825

    function resizeFrame(updown, height) {
        try {
            var thisHeight = typeof height === "undefined" ? 280 : Number(height) + 40,
                frame = parent.document.getElementById(window.name),
                clientH = "";

            if (frame) {
                if (updown === -1) {
                    clientH = document.body.clientHeight;
                }
                else {
                    clientH = document.body.clientHeight + thisHeight; //increasing the height
                }
                $(frame).height(clientH);
            }
        } catch(e) {
            evalTemplateUtils.debug.error("Frame resize did not work. Error: %o", e, e);
        }
    }

    // Format bundle path for user locale
    var loadMessageBundle = function(){
        $.ajax({
            url: messgeBundlePath,
            global: false,
            cache: true,
            dataType : "json",
            success: function(messageBundleJSON){
                messageBundle = messageBundleJSON.data;
            }
        });
    };

    //public data
    return {
        entity:{
            getTemplateItemURL: function(id) {
                return entityTemplateItemURL.replace(":ID:", id);
            }
        },
        //keep frame size before grow
        frameSize: 0,
        //keep iframe scroll height
        frameScrollHeight: 0,
        frameGrow: function(height) {
            resizeFrame(1, height);
        },
        frameShrink: function(height) {
            resizeFrame(-1, height);
        },
        debug: {
            info : function() {
            },
            debug : function() {
            },
            warn : function() {
            },
            error : function() {
            },
            group : function() {
            },
            groupEnd : function() {
            },
            time : function() {
            },
            timeEnd : function() {
            }
        },
        vars: {
            groupableItems : [],
            isIE : false
        },
        init: function() {
            // Debugging. Acts on Firebug console methods described at http://getfirebug.com/console.html
            if (canDebug && typeof console !== "undefined") {
                if (typeof console.info !== "undefined" && canDebugLevels.search(/info/i) !== -1) {
                    evalTemplateUtils.debug.info = console.info;
                }
                if (typeof console.debug !== "undefined" && canDebugLevels.search(/debug/i) !== -1) {
                    evalTemplateUtils.debug.debug = console.debug;
                }
                if (typeof console.warn !== "undefined" && canDebugLevels.search(/warn/i) !== -1) {
                    evalTemplateUtils.debug.warn = console.warn;
                }
                if (typeof console.error !== "undefined" && canDebugLevels.search(/error/i) !== -1) {
                    evalTemplateUtils.debug.error = console.error;
                }
                if (typeof console.group !== "undefined") {
                    evalTemplateUtils.debug.group = console.group;
                }
                if (typeof console.groupEnd !== "undefined") {
                    evalTemplateUtils.debug.groupEnd = console.groupEnd;
                }
                if (typeof console.time !== "undefined") {
                    evalTemplateUtils.debug.time = console.time;
                }
                if (typeof console.timeEnd !== "undefined") {
                    evalTemplateUtils.debug.timeEnd = console.timeEnd;
                }
            }
            //browser check
            evalTemplateUtils.vars.isIE = $.browser.msie;

            // Message Locale bundle loader
            loadMessageBundle();

            templateId = $('input[name=templateId]:hidden').val();
        },
        pages: {
                modify_item_page: "modify_item",
                modify_template_page: "modify_template",
                modify_block_page: "modify_block",
                choose_existing_page: "choose_existing_items",
                choose_expert_page: "choose_expert_category",
                eb_save_order: "/direct/eval-templateitem/template-items-reorder",
                eb_block_edit: "/direct/eval-templateitem/modify-block-items",
                preview_item_page: "preview_item"
            },
        getPageType: function(url){
            evalTemplateUtils.debug.group("Getting the page type/name");
            var pageType = undefined,
                    i = 0,
                    regExp = null;
            pagesLoadedByFBwithJs = [ evalTemplateUtils.pages.modify_item_page, evalTemplateUtils.pages.choose_expert_page,
                evalTemplateUtils.pages.modify_template_page, evalTemplateUtils.pages.modify_block_page,
                evalTemplateUtils.pages.choose_existing_page, evalTemplateUtils.pages.preview_item_page];
            evalTemplateUtils.debug.debug("Pages supported are %s", pagesLoadedByFBwithJs.toString());
            for ( i in pagesLoadedByFBwithJs){
                if ( typeof pageType == "undefined" ){
                    regExp = new RegExp(pagesLoadedByFBwithJs[i]);
                    evalTemplateUtils.debug.debug("Checking url against page filter %s and regExp %o", pagesLoadedByFBwithJs[i], regExp);
                    pageType =  ( url.search(regExp) !== -1 ) ? pagesLoadedByFBwithJs[i] : undefined ;
                    evalTemplateUtils.debug.debug("Page type is %s", pageType);
                }
            }
            evalTemplateUtils.debug.info("Page type found as: %s", pageType);
            evalTemplateUtils.debug.groupEnd();
            return pageType;
        },
        //retrieve the message strings for key
        messageLocator: function(key, params){
            return fluid.messageLocator( messageBundle )([key], params);
        },

        // Remember the groups a user closes: EVALSYS-825
        closedGroup : {
            add : function(groupId){
                if( groupId ){
                    if ( $.inArray(groupId, closedGroups) === -1){
                        closedGroups.push(groupId);
                        evalTemplateUtils.debug.info("Closed %s", groupId);
                    }
                }
                evalTemplateUtils.debug.warn("closedGroups %o", closedGroups);
            },
            remove : function(groupId){
                if( groupId && $.inArray(groupId, closedGroups) > -1){
                    var index;
                    for ( var i in closedGroups){
                        if ( closedGroups[i] === groupId ){
                            index = i;
                        }
                    }
                    closedGroups.splice(index, 1);
                    evalTemplateUtils.debug.info("Opened %s", groupId);
                }
                evalTemplateUtils.debug.warn("closedGroups %o", closedGroups);
            },
            get : closedGroups
        },

        // DOM values retrieval functions
        getTemplateId:  function(){return templateId;},
        getTemplateItemId: function(that){
            return that.parents('.itemRow').find('input[name=template-item-id]:hidden').val();
        },
        getItemClassification: function(that){
            return that.parents('.itemRow').find('input[name=item-classification]:hidden').val();
        }

        };

})($);

//init evalUtils
evalTemplateUtils.init();<|endoftext|>


<commit_before>'use strict';

var multi_profile = require('multi-profile');
var node_path = require('path');
var node_url = require('url');
var fs = require('fs-sync');

var cortex_root = multi_profile.resolvePath('~/.cortex');

var TYPES = {
    path: {
        setter: function (v, key, attr) {

            // will resolve '~' in the path
            return profile.resolvePath(v);
        }
    },

    url: {
        setter: function (v, key, attr) {
            v = url.parse(String(v));

            if (!v.host){
                attr.error('invalid url');
            }

            return v.href;
        }
    }
};

var profile = module.exports = multi_profile({
    path: '~/.cortex',

    // configuration schema and default values
    schema: {
        cortex_root     : {
            value       : cortex_root,
            type        : TYPES.path
        },

        module_root     : {
            value       : node_path.join(cortex_root, 'modules'),
            type        : TYPES.path
        },

        built_root      : {
            value       : node_path.join(cortex_root, 'built_modules'),
            type        : TYPES.path
        },

        built_temp      : {

            // could be relative path
            value       : node_path.join('.cortex', 'built')
        },

        temp_root       : {
            value       : node_path.join(cortex_root, 'tmp'),

            // temp_root will not be saved into profile file
            readOnly    : true,
            type        : {

                // It's only a getter, and everytime it returns a different directory
                getter  : function (v) {
                    return node_path.join(v, Date.now());
                }
            }
        },

        registry        : {
            value       : 'http://registry.npmjs.org',
            type        : TYPES.url
        },

        registry_port   : {
            value       : 80,
            type        : {
                validator : function (v) {
                    return typeof v === 'string'
                }
            }
        },

        server_path     : {
            value       : '/mod',
            type        : {

                // 'mod' -> '/mod'
                getter  : function (v) {
                    return '/' + v.replace(/^\/+|\/+$/, '');
                }
            }
        },

        language        : {
            value       : 'en'
        }
    }
});

<commit_msg>improve stability of read and write<commit_after>'use strict';

var multi_profile = require('multi-profile');
var node_path = require('path');
var node_url = require('url');
var fs = require('fs-sync');

// 1. Make sure all values saved by cortex profile is exactly correct
// 2. Make sure all values read from the config file will be examined (user may change that).

var TYPES = {
    path: {
        getter: function (v) {
            // will resolve '~' in the path
            v = multi_profile.resolveHomePath(v);

            if(!fs.isPathAbsolute(v)){

                // convert to absolute path relative to the root directory of the current profile
                v = node_path.join(profile.currentDir(), v);
            }

            return v;
        }
    },

    url: {
        setter: function (v, key, attr) {
            v = node_url.parse(String(v));

            // must be an invalid url
            if (!v.host){
                attr.error('invalid url');
            }

            return v.href;
        }
    }
};

var profile = module.exports = multi_profile({
    path: '~/.cortex',

    // configuration schema and default values
    schema: {
        // cortex_root     : {
        //     value       : cortex_root,
        //     type        : TYPES.path
        // },

        module_root     : {
            value       : 'modules',
            type        : TYPES.path
        },

        built_root      : {
            value       : 'built_modules',
            type        : TYPES.path
        },

        built_temp      : {

            // could be relative path
            value       : 'built'
        },

        temp_root       : {
            value       : 'tmp',

            // temp_root will not be saved into profile file
            readOnly    : true,
            type        : {
                getter  : function (v) {
                    // will resolve '~' in the path
                    v = multi_profile.resolveHomePath(v);

                    if(!fs.isPathAbsolute(v)){

                        // convert to absolute path relative to the root directory of the current profile
                        v = node_path.join(profile.currentDir(), v);
                    }

                    // Everytime it returns a different directory
                    return node_path.join(
                        v,
                        // must be string
                        String(Date.now())
                    );
                }
            }
        },

        registry        : {
            value       : 'http://registry.npmjs.org',
            type        : TYPES.url
        },

        registry_port   : {
            value       : 80,
            type        : {
                validator : function (v) {
                    return typeof v === 'string'
                }
            }
        },

        server_path     : {
            value       : '/mod',
            type        : {

                // 'mod' -> '/mod'
                getter  : function (v) {
                    return '/' + v.replace(/^\/+|\/+$/, '');
                }
            }
        },

        language        : {
            value       : 'en'
        }
    }
});

<|endoftext|>


<commit_before>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * This file provides the @defines for JRE configuration options. See
 * https://github.com/google/j2cl/blob/master/docs/best-practices.md#jre-configuration
 * for documentation.
 */

goog.provide('jre');

/** @define {string} */
jre.classMetadata = goog.define('jre.classMetadata', 'SIMPLE');
/** @define {string} */
jre.checkedMode =
    goog.define('jre.checkedMode', goog.DEBUG ? 'ENABLED' : 'DISABLED');

goog.provide('jre.checks');

/** @define {string} */
jre.checks.checkLevel = goog.define('jre.checks.checkLevel', 'NORMAL');
/** @define {string} */
jre.checks.bounds = goog.define('jre.checks.bounds', 'AUTO');
/** @define {string} */
jre.checks.api = goog.define('jre.checks.api', 'AUTO');
/** @define {string} */
jre.checks.numeric = goog.define('jre.checks.numeric', 'AUTO');
/** @define {string} */
jre.checks.type = goog.define('jre.checks.type', 'AUTO');
/** @define {string} */
jre.checks.critical = goog.define('jre.checks.critical', 'AUTO');

goog.provide('jre.logging');

/** @define {string} */
jre.logging.logLevel =
    goog.define('jre.logging.logLevel', goog.DEBUG ? 'ALL' : 'SEVERE');
/** @define {string} */
jre.logging.simpleConsoleHandler =
    goog.define('jre.logging.simpleConsoleHandler', 'ENABLED');

// Provide a stub for field preserver to make things work without full
// compilation.
if (!COMPILED || goog.DEBUG) {
  goog.global.$J2CL_PRESERVE$ = function(/** ...* */ e) {};
}
<commit_msg>Use globalThis in jre.js to be consistent.<commit_after>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * This file provides the @defines for JRE configuration options. See
 * https://github.com/google/j2cl/blob/master/docs/best-practices.md#jre-configuration
 * for documentation.
 */

goog.provide('jre');

/** @define {string} */
jre.classMetadata = goog.define('jre.classMetadata', 'SIMPLE');
/** @define {string} */
jre.checkedMode =
    goog.define('jre.checkedMode', goog.DEBUG ? 'ENABLED' : 'DISABLED');

goog.provide('jre.checks');

/** @define {string} */
jre.checks.checkLevel = goog.define('jre.checks.checkLevel', 'NORMAL');
/** @define {string} */
jre.checks.bounds = goog.define('jre.checks.bounds', 'AUTO');
/** @define {string} */
jre.checks.api = goog.define('jre.checks.api', 'AUTO');
/** @define {string} */
jre.checks.numeric = goog.define('jre.checks.numeric', 'AUTO');
/** @define {string} */
jre.checks.type = goog.define('jre.checks.type', 'AUTO');
/** @define {string} */
jre.checks.critical = goog.define('jre.checks.critical', 'AUTO');

goog.provide('jre.logging');

/** @define {string} */
jre.logging.logLevel =
    goog.define('jre.logging.logLevel', goog.DEBUG ? 'ALL' : 'SEVERE');
/** @define {string} */
jre.logging.simpleConsoleHandler =
    goog.define('jre.logging.simpleConsoleHandler', 'ENABLED');

// Provide a stub for field preserver to make things work without full
// compilation.
if (!COMPILED || goog.DEBUG) {
  globalThis.$J2CL_PRESERVE$ = function(/** ...* */ e) {};
}
<|endoftext|>


<commit_before>// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var MetastoreViewModel = (function () {

  /**
   * @param {Object} options
   * @param {string} options.user
   * @constructor
   */
  function MetastoreViewModel(options) {
    var self = this;

    self.partitionsLimit = options.partitionsLimit;
    self.assistAvailable = ko.observable(true);
    self.apiHelper = window.apiHelper;
    self.isLeftPanelVisible = ko.observable();
    self.apiHelper.withTotalStorage('assist', 'assist_panel_visible', self.isLeftPanelVisible, true);
    self.optimizerEnabled = ko.observable(options.optimizerEnabled || false);
    self.navigatorEnabled = ko.observable(options.navigatorEnabled || false);
    self.appConfig = ko.observable();

    self.source = ko.observable();
    self.sources = ko.observableArray();

    self.source.subscribe(function (newValue) {
      newValue.loadNamespaces().done(function () {
        if (newValue.namespace()) {
          newValue.namespace().loadDatabases().done(function () {
            self.loadUrl();
          });
        }
      });
    });

    // When manually changed through dropdown
    self.sourceChanged = function () {
      huePubSub.publish('metastore.url.change')
    };

    self.loading = ko.pureComputed(function () {
      if (!self.source()) {
        return true;
      }
      if (self.source().loading()) {
        return true;
      }
      return false;
    });

    huePubSub.publish('cluster.config.get.config', function (clusterConfig) {
      var initialSourceType = options.sourceType || 'hive';
      if (clusterConfig && clusterConfig.app_config && (
          (clusterConfig.app_config.editor && clusterConfig.app_config.editor.interpreters) || clusterConfig.app_config.catalogs)) {
        var sources = [];
        clusterConfig.app_config.editor.interpreters.forEach(function (interpreter) {
          if (interpreter.is_sql) {
            sources.push(new MetastoreSource({
              metastoreViewModel: self,
              name: interpreter.name,
              type: interpreter.type
            }))
          }
        });
        if (clusterConfig.app_config.catalogs) {
          clusterConfig.app_config.catalogs.forEach(function (interpreter) {
            sources.push(new MetastoreSource({
              metastoreViewModel: self,
              name: interpreter.name,
              type: interpreter.type
            }))
          });
        }
        if (!sources.length) {
          sources.push(new MetastoreSource({
            metastoreViewModel: self,
            name: initialSourceType,
            type: initialSourceType
          }));
        }
        self.sources(sources);
        var found = sources.some(function (source) {
          if (source.type === initialSourceType) {
            self.source(source);
            return true;
          }
        });
        if (!found) {
          self.source(sources[0]);
        }
      }
    });

    self.navigatorEnabled.subscribe(function (newValue) {
      huePubSub.publish('meta.navigator.enabled', newValue);
    });

    self.optimizerUrl = ko.observable(options.optimizerUrl);
    self.navigatorUrl = ko.observable(options.navigatorUrl);

    self.currentTab = ko.observable('');

    huePubSub.subscribe('assist.database.selected', function (databaseDef) {
      if (self.source().type !== databaseDef.sourceType) {
        var found = self.sources().some(function (source) {
          if (source.type === databaseDef.sourceType) {
            self.source(source);
            return true;
          }
        });
        if (!found) {
          return;
        }
      }

      if (self.source().namespace().id !== databaseDef.namespace.id) {
        var found = self.source().namespaces().some(function (namespace) {
          if (namespace.id === databaseDef.namespace.id) {
            self.source().namespace(namespace);
            return true;
          }
        });
        if (!found) {
          return;
        }
      }
      if (self.source().namespace().database()) {
        self.source().namespace().database().table(null);
      }
      self.source().namespace().setDatabaseByName(databaseDef.name, function () {
        huePubSub.publish('metastore.url.change')
      });
    });

    huePubSub.subscribe("assist.table.selected", function (tableDef) {
      self.loadTableDef(tableDef, function () {
        huePubSub.publish('metastore.url.change')
      });
    });

    huePubSub.subscribe('metastore.url.change', function () {
      var prefix = '/hue/metastore/';
      if (self.source() && self.source().namespace()) {
        var params = {
          source: self.source().type
        };
        if (window.HAS_MULTI_CLUSTER) {
          params.namespace = self.source().namespace().id
        }
        if (self.source().namespace().database() && self.source().namespace().database().table()) {
          hueUtils.changeURL(prefix + 'table/' + self.source().namespace().database().table().catalogEntry.path.join('/'), params);
        } else if (self.source().namespace().database()) {
          hueUtils.changeURL(prefix + 'tables/' + self.source().namespace().database().catalogEntry.name, params);
        } else {
          hueUtils.changeURL(prefix + 'databases', params);
        }
      }
    });

    window.onpopstate = function () {
      if (window.location.pathname.indexOf('/metastore') > -1) {
        self.loadUrl();
      }
    };

    self.databasesBreadcrumb = function () {
      if (self.source().namespace().database()) {
        self.source().namespace().database().table(null);
      }
      self.source().namespace().database(null);
      huePubSub.publish('metastore.url.change');
    };

    self.tablesBreadcrumb = function () {
      self.source().namespace().database().table(null);
      huePubSub.publish('metastore.url.change')
    }
  }

  MetastoreViewModel.prototype.loadTableDef = function (tableDef, callback) {
    var self = this;
    if (self.source().type !== tableDef.sourceType) {
      var found = self.sources().some(function (source) {
        if (source.type === tableDef.sourceType) {
          self.source(source);
          return true;
        }
      });
      if (!found) {
        return;
      }
    }
    if (self.source().namespace().id !== tableDef.namespace.id) {
      var found = self.source().namespaces().some(function (namespace) {
        if (namespace.id === tableDef.namespace.id) {
          self.source().namespace(namespace);
          return true;
        }
      });
      if (!found) {
        return;
      }
    }
    self.source().namespace().setDatabaseByName(tableDef.database, function () {
      if (self.source().namespace().database()) {
        if (self.source().namespace().database().table() && self.source().namespace().database().table().catalogEntry.name === tableDef.name) {
          if (callback) {
            callback();
          }
          return;
        }

        var setTableAfterLoad = function (clearDbCacheOnMissing) {
          var foundTables = self.source().namespace().database().tables().filter(function (table) {
            return table.catalogEntry.name === tableDef.name;
          });
          if (foundTables.length === 1) {
            self.source().namespace().database().setTable(foundTables[0], callback);
          } else if (clearDbCacheOnMissing) {
            self.source().namespace().database().catalogEntry.clearCache({ invalidate: 'invalidate', silenceErrors: true }).then(function () {
              self.source().namespace().database().load(function () {
                setTableAfterLoad(false);
              });
            });
          }
        };

        if (!self.source().namespace().database().loaded()) {
          var doOnce = self.source().namespace().database().loaded.subscribe(function () {
            setTableAfterLoad(true);
            doOnce.dispose();
          });
        } else {
          setTableAfterLoad(true);
        }
      }
    });
  };

  MetastoreViewModel.prototype.loadUrl = function () {
    var self = this;

    var path = window.location.pathname.substr(4);
    if (!path) {
      path = '/metastore/tables';
    }
    path = path.split('/');
    if (path[0] === '') {
      path.shift();
    }
    if (path[0] === 'metastore') {
      path.shift();
    }
    var loadedDeferred = $.Deferred();

    if (!self.loading()) {
      loadedDeferred.resolve();
    } else {
      var loadSub = self.loading.subscribe(function () {
        loadSub.dispose();
        loadedDeferred.resolve();
      })
    }

    var sourceAndNamespaceDeferred = $.Deferred();

    loadedDeferred.done(function () {
      var search = location.search;
      var namespaceId;
      var sourceType;
      if (search) {
        search = search.replace('?', '');
        search.split('&').forEach(function (param) {
          if (param.indexOf('namespace=') === 0) {
            namespaceId = param.replace('namespace=', '');
          }
          if (param.indexOf('source=') === 0) {
            sourceType = param.replace('source=', '');
          }
        });
      }

      if (sourceType && sourceType !== self.source().type) {
        var found = self.sources().some(function (source) {
          if (source.type === sourceType) {
            self.source(source);
            return true;
          }
        });
        if (!found) {
          sourceAndNamespaceDeferred.reject();
          return;
        }
      }

      if (!namespaceId && window.apiHelper.getFromTotalStorage('contextSelector', 'lastSelectedNamespace')) {
        namespaceId = window.apiHelper.getFromTotalStorage('contextSelector', 'lastSelectedNamespace').id;
      }

      self.source().lastLoadNamespacesDeferred.done(function () {
        if (namespaceId && namespaceId !== self.source().namespace().id) {
          var found = self.source().namespaces().some(function (namespace) {
            if (namespace.id === namespaceId) {
              self.source().namespace(namespace);
              return true;
            }
          });
          if (!found) {
            sourceAndNamespaceDeferred.reject();
            return;
          } else {
            sourceAndNamespaceDeferred.resolve();
          }
        } else {
          sourceAndNamespaceDeferred.resolve();
        }
      });
    });

    sourceAndNamespaceDeferred.done(function () {
      var namespace = self.source().namespace();
      switch (path[0]) {
        case 'databases':
          if (namespace.database()) {
            namespace.database().table(null);
            namespace.database(null);
          }
          break;
        case 'tables':
          if (namespace.database()) {
            namespace.database().table(null);
          }
          namespace.setDatabaseByName(path[1]);
          break;
        case 'table':
          huePubSub.subscribe('metastore.loaded.table', function() {
            self.currentTab('overview');
          }, 'metastore');
          self.loadTableDef({
            name: path[2],
            database: path[1],
            sourceType: self.source().type,
            namespace: namespace
          }, function(){
            if (path.length > 3 && path[3] === 'partitions'){
              huePubSub.subscribe('metastore.loaded.partitions', function() {
                self.currentTab('partitions');
              }, 'metastore');
            }
          });
      }
    })
  };

  return MetastoreViewModel;
})();
<commit_msg>HUE-8840 [catalog] Fix URL param when switching between source_type<commit_after>// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var MetastoreViewModel = (function () {

  /**
   * @param {Object} options
   * @param {string} options.user
   * @constructor
   */
  function MetastoreViewModel(options) {
    var self = this;

    self.partitionsLimit = options.partitionsLimit;
    self.assistAvailable = ko.observable(true);
    self.apiHelper = window.apiHelper;
    self.isLeftPanelVisible = ko.observable();
    self.apiHelper.withTotalStorage('assist', 'assist_panel_visible', self.isLeftPanelVisible, true);
    self.optimizerEnabled = ko.observable(options.optimizerEnabled || false);
    self.navigatorEnabled = ko.observable(options.navigatorEnabled || false);
    self.appConfig = ko.observable();

    self.source = ko.observable();
    self.sources = ko.observableArray();

    self.source.subscribe(function (newValue) {
      newValue.loadNamespaces().done(function () {
        if (newValue.namespace()) {
          newValue.namespace().loadDatabases().done(function () {
            self.loadUrl();
          });
        }
      });
    });

    // When manually changed through dropdown
    self.sourceChanged = function () {
      huePubSub.publish('metastore.url.change')
    };

    self.loading = ko.pureComputed(function () {
      if (!self.source()) {
        return true;
      }
      if (self.source().loading()) {
        return true;
      }
      return false;
    });

    huePubSub.publish('cluster.config.get.config', function (clusterConfig) {
      var initialSourceType = options.sourceType || 'hive';
      if (clusterConfig && clusterConfig.app_config && (
          (clusterConfig.app_config.editor && clusterConfig.app_config.editor.interpreters) || clusterConfig.app_config.catalogs)) {
        var sources = [];
        clusterConfig.app_config.editor.interpreters.forEach(function (interpreter) {
          if (interpreter.is_sql) {
            sources.push(new MetastoreSource({
              metastoreViewModel: self,
              name: interpreter.name,
              type: interpreter.type
            }))
          }
        });
        if (clusterConfig.app_config.catalogs) {
          clusterConfig.app_config.catalogs.forEach(function (interpreter) {
            sources.push(new MetastoreSource({
              metastoreViewModel: self,
              name: interpreter.name,
              type: interpreter.type
            }))
          });
        }
        if (!sources.length) {
          sources.push(new MetastoreSource({
            metastoreViewModel: self,
            name: initialSourceType,
            type: initialSourceType
          }));
        }
        self.sources(sources);
        var found = sources.some(function (source) {
          if (source.type === initialSourceType) {
            self.source(source);
            return true;
          }
        });
        if (!found) {
          self.source(sources[0]);
        }
      }
    });

    self.navigatorEnabled.subscribe(function (newValue) {
      huePubSub.publish('meta.navigator.enabled', newValue);
    });

    self.optimizerUrl = ko.observable(options.optimizerUrl);
    self.navigatorUrl = ko.observable(options.navigatorUrl);

    self.currentTab = ko.observable('');

    huePubSub.subscribe('assist.database.selected', function (databaseDef) {
      if (self.source().type !== databaseDef.sourceType) {
        var found = self.sources().some(function (source) {
          if (source.type === databaseDef.sourceType) {
            self.source(source);
            return true;
          }
        });
        if (!found) {
          return;
        }
      }

      if (self.source().namespace().id !== databaseDef.namespace.id) {
        var found = self.source().namespaces().some(function (namespace) {
          if (namespace.id === databaseDef.namespace.id) {
            self.source().namespace(namespace);
            return true;
          }
        });
        if (!found) {
          return;
        }
      }
      if (self.source().namespace().database()) {
        self.source().namespace().database().table(null);
      }
      self.source().namespace().setDatabaseByName(databaseDef.name, function () {
        huePubSub.publish('metastore.url.change')
      });
    });

    huePubSub.subscribe("assist.table.selected", function (tableDef) {
      self.loadTableDef(tableDef, function () {
        huePubSub.publish('metastore.url.change')
      });
    });

    huePubSub.subscribe('metastore.url.change', function () {
      var prefix = '/hue/metastore/';
      if (self.source() && self.source().namespace()) {
        var params = {
          source_type: self.source().type
        };
        if (window.HAS_MULTI_CLUSTER) {
          params.namespace = self.source().namespace().id
        }
        if (self.source().namespace().database() && self.source().namespace().database().table()) {
          hueUtils.changeURL(prefix + 'table/' + self.source().namespace().database().table().catalogEntry.path.join('/'), params);
        } else if (self.source().namespace().database()) {
          hueUtils.changeURL(prefix + 'tables/' + self.source().namespace().database().catalogEntry.name, params);
        } else {
          hueUtils.changeURL(prefix + 'databases', params);
        }
      }
    });

    window.onpopstate = function () {
      if (window.location.pathname.indexOf('/metastore') > -1) {
        self.loadUrl();
      }
    };

    self.databasesBreadcrumb = function () {
      if (self.source().namespace().database()) {
        self.source().namespace().database().table(null);
      }
      self.source().namespace().database(null);
      huePubSub.publish('metastore.url.change');
    };

    self.tablesBreadcrumb = function () {
      self.source().namespace().database().table(null);
      huePubSub.publish('metastore.url.change')
    }
  }

  MetastoreViewModel.prototype.loadTableDef = function (tableDef, callback) {
    var self = this;
    if (self.source().type !== tableDef.sourceType) {
      var found = self.sources().some(function (source) {
        if (source.type === tableDef.sourceType) {
          self.source(source);
          return true;
        }
      });
      if (!found) {
        return;
      }
    }
    if (self.source().namespace().id !== tableDef.namespace.id) {
      var found = self.source().namespaces().some(function (namespace) {
        if (namespace.id === tableDef.namespace.id) {
          self.source().namespace(namespace);
          return true;
        }
      });
      if (!found) {
        return;
      }
    }
    self.source().namespace().setDatabaseByName(tableDef.database, function () {
      if (self.source().namespace().database()) {
        if (self.source().namespace().database().table() && self.source().namespace().database().table().catalogEntry.name === tableDef.name) {
          if (callback) {
            callback();
          }
          return;
        }

        var setTableAfterLoad = function (clearDbCacheOnMissing) {
          var foundTables = self.source().namespace().database().tables().filter(function (table) {
            return table.catalogEntry.name === tableDef.name;
          });
          if (foundTables.length === 1) {
            self.source().namespace().database().setTable(foundTables[0], callback);
          } else if (clearDbCacheOnMissing) {
            self.source().namespace().database().catalogEntry.clearCache({ invalidate: 'invalidate', silenceErrors: true }).then(function () {
              self.source().namespace().database().load(function () {
                setTableAfterLoad(false);
              });
            });
          }
        };

        if (!self.source().namespace().database().loaded()) {
          var doOnce = self.source().namespace().database().loaded.subscribe(function () {
            setTableAfterLoad(true);
            doOnce.dispose();
          });
        } else {
          setTableAfterLoad(true);
        }
      }
    });
  };

  MetastoreViewModel.prototype.loadUrl = function () {
    var self = this;

    var path = window.location.pathname.substr(4);
    if (!path) {
      path = '/metastore/tables';
    }
    path = path.split('/');
    if (path[0] === '') {
      path.shift();
    }
    if (path[0] === 'metastore') {
      path.shift();
    }
    var loadedDeferred = $.Deferred();

    if (!self.loading()) {
      loadedDeferred.resolve();
    } else {
      var loadSub = self.loading.subscribe(function () {
        loadSub.dispose();
        loadedDeferred.resolve();
      })
    }

    var sourceAndNamespaceDeferred = $.Deferred();

    loadedDeferred.done(function () {
      var search = location.search;
      var namespaceId;
      var sourceType;
      if (search) {
        search = search.replace('?', '');
        search.split('&').forEach(function (param) {
          if (param.indexOf('namespace=') === 0) {
            namespaceId = param.replace('namespace=', '');
          }
          if (param.indexOf('source_type=') === 0) {
            sourceType = param.replace('source_type=', '');
          }
        });
      }

      if (sourceType && sourceType !== self.source().type) {
        var found = self.sources().some(function (source) {
          if (source.type === sourceType) {
            self.source(source);
            return true;
          }
        });
        if (!found) {
          sourceAndNamespaceDeferred.reject();
          return;
        }
      }

      if (!namespaceId && window.apiHelper.getFromTotalStorage('contextSelector', 'lastSelectedNamespace')) {
        namespaceId = window.apiHelper.getFromTotalStorage('contextSelector', 'lastSelectedNamespace').id;
      }

      self.source().lastLoadNamespacesDeferred.done(function () {
        if (namespaceId && namespaceId !== self.source().namespace().id) {
          var found = self.source().namespaces().some(function (namespace) {
            if (namespace.id === namespaceId) {
              self.source().namespace(namespace);
              return true;
            }
          });
          if (!found) {
            sourceAndNamespaceDeferred.reject();
            return;
          } else {
            sourceAndNamespaceDeferred.resolve();
          }
        } else {
          sourceAndNamespaceDeferred.resolve();
        }
      });
    });

    sourceAndNamespaceDeferred.done(function () {
      var namespace = self.source().namespace();
      switch (path[0]) {
        case 'databases':
          if (namespace.database()) {
            namespace.database().table(null);
            namespace.database(null);
          }
          break;
        case 'tables':
          if (namespace.database()) {
            namespace.database().table(null);
          }
          namespace.setDatabaseByName(path[1]);
          break;
        case 'table':
          huePubSub.subscribe('metastore.loaded.table', function() {
            self.currentTab('overview');
          }, 'metastore');
          self.loadTableDef({
            name: path[2],
            database: path[1],
            sourceType: self.source().type,
            namespace: namespace
          }, function(){
            if (path.length > 3 && path[3] === 'partitions'){
              huePubSub.subscribe('metastore.loaded.partitions', function() {
                self.currentTab('partitions');
              }, 'metastore');
            }
          });
      }
    })
  };

  return MetastoreViewModel;
})();
<|endoftext|>