<commit_before>en_US = {
  day: {
    abbrev: "Sun Mon Tue Wed Thu Fri Sat".split(/\s/),
    full: "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(/\s+/)
  }
};
function die () {
  if (arguments.length) console.log.apply(console, Array.prototype.slice.call(arguments, 0));
  process.exit(1);
}

function say() {
  if (arguments.length) console.log.apply(console, Array.prototype.slice.call(arguments, 0));
}

const SECOND = 1000, MINUTE = SECOND * 60, HOUR = MINUTE * 60, DAY = HOUR * 24;

data = (function () {
  function copy(dest, source) {
    for (var key in source) if (source.hasOwnProperty(key)) dest[key] = source[key];
  }
  var file, continent, zoneFiles = require('fs').readdirSync('./timezones'), data = { zones: {}, rules: {} };
  for (var i = 0, stop = zoneFiles.length; i < stop; i++) {
    file = zoneFiles[i];
    if (file === 'index.js' || /^\./.test(file)) continue;
    continent = require('./timezones/' + file, 'utf8');
    copy(data.zones, continent.zones);
    copy(data.rules, continent.rules);
  }
  return data;
})();

var transitions = (function createTransitions() {

  function parseOffset (pattern) {
    if (typeof pattern == "number") return pattern;

    var offset = 0;

    // TODO Revert when rules becomes an offset integer.
    var match = /^(-?)(\d+)(?::(\d+))?(?::(\d+))?$/.exec(pattern)
    if (! match) return null;
    match = match.slice(1, 5);
    match[0] += '1'

    var milliseconds = [ HOUR, MINUTE, SECOND ];
    for (var i = 1, stop = match.length; i < stop; i++) {
      offset += parseInt(match[i] || '0', 10) * milliseconds[i - 1];
    }

    offset *= parseInt(match[0]);

    return offset;
  }

  function isLeapYear (year) {
    if (year % 400 == 0) return true;
    if (year % 100 == 0) return false
    if (year % 4 == 0) return true;
    return false;
  }

  var DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

  function daysInMonth (month, year) {
    var days = DAYS_IN_MONTH[month];
    if (month == 1 && isLeapYear(year)) days++;
    return days;
  }

  function parseUntil (until) {
    if (until) {
      var fields = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).000Z$/.exec(until).slice(1, 7);
      for (var i = 0, stop = fields.length; i < stop; i++) {
        fields[i] = parseInt(fields[i], 10);
      }
      --fields[1];
      return Date.UTC.apply(Date.UTC, fields);
    }
    return Number.MAX_VALUE;
  }
  function actualize (entry, rule, year, ruleIndex) {
    var time = /^(\d+):(\d+)(?::(\d+))?[us]?$/.exec(rule.time).slice(1, 4);
    for (var i = 0, stop = time.length; i < stop; i++) {
      time[i] = parseInt(time[i] || 0, 10);
    }
    var hours = time[0], minutes = time[1], seconds = time[2];
    var date = /^(?:(\d+)|last(\w+)|(\w+)>=(\d+))$/.exec(rule.day);
    var fields;
    if (date[1]) {
      fields = new Date(Date.UTC(year, rule.month, parseInt(date[1], 10), hours, minutes, seconds));
    } else if (date[2]) {
      var days = en_US.day.abbrev;
      for (var i = 0, stop = days.length; i < stop; i++)
        if (days[i] === date[2]) break;
      var day = daysInMonth(rule.month, year);
      for (;;) {
        fields = new Date(Date.UTC(year, rule.month, day, hours, minutes, seconds))
        if (fields.getUTCDay() === i) break;
        day--;
      }
    } else {
      var min = parseInt(date[4], 10);
      var days = en_US.day.abbrev;
      for (var i = 0, stop = days.length; i < stop; i++)
        if (days[i] === date[3]) break;
      day = 1;
      for (;;) {
        fields = new Date(Date.UTC(year, rule.month, day, hours, minutes, seconds))
        if (fields.getUTCDay() === i && fields.getUTCDate() >= min) break;
        day++;
      }
    }

    var save = parseOffset(rule.save || '0');

    var offset = entry.offset;

    var sortable, wallclock, clock, posix, standard;
    if (/u$/.test(rule.time)) {
      posix = fields.getTime();
      fields = new Date(fields.getTime() + offset);
      clock = "posix";
    } else if (/s$/.test(rule.time)) {
      standard = fields.getTime();
      fields = new Date(standard);
      clock = "standard";
    } else {
      wallclock = fields.getTime();
      fields = new Date(wallclock);
      clock = "wallclock";
    }

    sortable = Date.UTC(fields.getUTCFullYear(), fields.getUTCMonth(), fields.getUTCDate());

    return {
      clock: clock,
      standard: standard,
      entry: entry,
      sortable: sortable,
      rule:rule,
      wallclock: wallclock,
      year: year,
      posix: posix,
      save: save,
      ruleIndex: ruleIndex,
      offset: offset
    };
  }

  function setClocks (record, effective, clock) {
    var offset = effective.offset
      , save = effective.save;
    switch (clock || record.clock) {
    case "posix":
      record.standard = record.posix + offset;
      record.wallclock = record.posix + offset + save;
      break;
    case "wallclock":
      record.posix = record.wallclock - offset - save;
      record.standard = record.wallclock + save;
      break;
    case "standard":
      record.posix = record.standard - offset;
      record.wallclock = record.standard + save;
      break;
    }
    return record;
  }

  function ruleClock(rule) {
    if (/[ugz]$/.exec(rule.time)) return "posix";
    if (/s$/.exec(rule.time)) return "standard";
    return "wallclock";
  }

  function getYear (time) { return new Date(time).getUTCFullYear() }

  function pushRule (table, entry, actual, abbrevs) {
    var save = parseOffset(actual.rule.save || "0")
      , abbrev = abbrevs[save ? 1 : 0] || entry.format.replace(/%s/, function () { return actual.rule.letter });
    table.push({
      actualization: true,
      offset: entry.offset,
      abbrev: abbrev,
      clock: actual.clock,
      wallclock: actual.wallclock,
      posix: actual.posix,
      standard: actual.standard,
      save: parseOffset(actual.rule.save || "0")
    });
  }

  function iso8601 (date) { return new Date(date).toISOString().replace(/\..*$/, "") }

  function step (begin, end, table) {
    var match
      , actual
      , max;

    // Oink. Oink. We'll be pigs.

    var rule
      , abbrevs
      , year = getYear(new Date().getTime())
      , rules = data.rules[begin.rules].slice(0)
      , actualized = [];

    if (abbrevs = /(\w+)\/(\w+)/.exec(begin.format)) abbrevs.shift();
    else abbrevs = []

    for (var i = 0, length = rules.length; i < length; i++) {
      rules[i].clock = ruleClock(rules[i]); // TODO Temporary.
      for (var j = rules[i].from, to = Math.min(rules[i].to, year); j <= to; j++) {
        actualized.push(actualize(begin, rules[i], j, i));
      }
    }

    actualized.sort(function (a, b) { return a.sortable - b.sortable });

    i = 0, length = actualized.length

    for (; i < length; i++) {
      if (begin[actualized[i].clock] <= actualized[i][actualized[i].clock]) break;
    }

    var previous = begin;

    if (begin[actualized[i].clock] == actualized[i][actualized[i].clock]) {
      table.pop(); // A rule on the seam overrides the seam.
      previous = table[table.length - 1];
    } else {
      if (i === 0) {
        var rules = data.rules[begin.rules], offset;
        for (var j = 0; j < rules.length; j++) {
          if (!(offset = parseOffset(rules[j].save || "0"))) {
            begin.abbrev = abbrevs[0] || begin.format.replace(/%s/, function () { return rules[j].letter });
            break;
          }
        }
      } else {
        begin.save = parseOffset(actualized[i - 1].save);
        begin.abbrev = abbrevs[begin.save ? 1 : 0] || begin.format.replace(/%s/, function () { return actualized[i - 1].rule.letter });
      }
    }

    for (; i < length; i++) {
      setClocks(actualized[i], previous);
      if (actualized[i][end.clock] >= end[end.clock]) {
        break;
      }
      pushRule(table, begin, actualized[i], abbrevs);
      previous = actualized[i];
    }
  }

  function walk (begin, end, table) {
    step(begin, end, table);
    return table[table.length - 1];
  }

  function begins (zone) {
    var copy = [];
    for (var i = zone.length - 2; i >= 0; --i) {
      copy[i] = {
        rules: zone[i].rules,
        format: zone[i].format,
        offset: parseOffset(zone[i].offset),
        save: 0,
        // TODO Intermediate format is all kinds of broken.
        clock: zone[i + 1].utc ? 'posix' : (zone[i + 1].standard ? 'standard' : 'wallclock')
      };
      copy[i][copy[i].clock] = parseUntil(zone[i + 1].until);
    }

    copy.push({
      offset: parseOffset(zone[zone.length - 1].offset),
      format: zone[zone.length - 1].format,
      save: 0
    });

    copy.reverse();
    copy[0].posix = copy[0].wallclock = Number.MIN_VALUE;
    copy.forEach(function (e) { e.begins =  iso8601(e[e.clock]) + " " + e.clock });
    return copy;
  }

  return function transitions (zoneName, consumer) {
    // We `concat` because someday, we'll read right out of the database and the
    // `concat` will be our defensive copy.
    var table = []
      , zone = begins(data.zones[zoneName]).concat({ offset: "0" })
      , entry = zone.shift()
      , previous, offset, save = 0, wallclock, posix, rules;

    table.push(entry);

    for (var i = 0, length = zone.length; i < Math.min(13, length); i++) {
      previous = entry;
      entry = zone[i];

      previous.abbrev = previous.format;

      if (previous.rules) {
        if (!(previous.save = parseOffset(previous.rules))) {
          previous = walk(previous, entry, table); // previous is last rule, not last zone.
        }
      } else {
        previous.save = 0;
      }

      setClocks(entry, previous);

      table.push(entry);
    }
    return table.reverse();
  }
})();

(function () {
  function pad (value) { return ('00' + value).slice(-2) }
  function formatOffset (offset) {
    var increment = offset / Math.abs(offset);
    var sign = offset < 0 ? '-' : '+';
    var millis, seconds, minutes, hours;
    offset = Math.abs(offset);
    offset -= (millis = offset % 1000);
    offset /= 1000;
    offset -= (seconds = offset % 60);
    offset /= 60;
    offset -= (minutes = offset % 60);
    hours = offset / 60;
    return sign + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
  }
  function iso8601 (date) {
    return new Date(date).toISOString().replace(/\..*$/, "");
  }
  function format(entry) {
    if (! entry.abbrev) entry.abbrev = entry.format;
    return formatOffset(entry.offset + (entry.save || 0)) + '/' + entry.abbrev;
  }
  var zoneName = process.argv[2];
  var table = transitions(zoneName, function (entry, posix, wallclock) {
    entry.posix = posix;
    entry.wallclock = wallclock;
  });
  for (var i = 1, stop = table.length - 1; i < stop; i++) {
    entry = table[i];
    say("%s %s %s %s", zoneName, iso8601(entry.wallclock), iso8601(entry.posix), format(table[i + 1]), format(table[i]));
  }
})();
<commit_msg>Visit all zones going forward.<commit_after>en_US = {
  day: {
    abbrev: "Sun Mon Tue Wed Thu Fri Sat".split(/\s/),
    full: "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(/\s+/)
  }
};
function die () {
  if (arguments.length) console.log.apply(console, Array.prototype.slice.call(arguments, 0));
  process.exit(1);
}

function say() {
  if (arguments.length) console.log.apply(console, Array.prototype.slice.call(arguments, 0));
}

const SECOND = 1000, MINUTE = SECOND * 60, HOUR = MINUTE * 60, DAY = HOUR * 24;

data = (function () {
  function copy(dest, source) {
    for (var key in source) if (source.hasOwnProperty(key)) dest[key] = source[key];
  }
  var file, continent, zoneFiles = require('fs').readdirSync('./timezones'), data = { zones: {}, rules: {} };
  for (var i = 0, stop = zoneFiles.length; i < stop; i++) {
    file = zoneFiles[i];
    if (file === 'index.js' || /^\./.test(file)) continue;
    continent = require('./timezones/' + file, 'utf8');
    copy(data.zones, continent.zones);
    copy(data.rules, continent.rules);
  }
  return data;
})();

var transitions = (function createTransitions() {

  function parseOffset (pattern) {
    if (typeof pattern == "number") return pattern;

    var offset = 0;

    // TODO Revert when rules becomes an offset integer.
    var match = /^(-?)(\d+)(?::(\d+))?(?::(\d+))?$/.exec(pattern)
    if (! match) return null;
    match = match.slice(1, 5);
    match[0] += '1'

    var milliseconds = [ HOUR, MINUTE, SECOND ];
    for (var i = 1, stop = match.length; i < stop; i++) {
      offset += parseInt(match[i] || '0', 10) * milliseconds[i - 1];
    }

    offset *= parseInt(match[0]);

    return offset;
  }

  function isLeapYear (year) {
    if (year % 400 == 0) return true;
    if (year % 100 == 0) return false
    if (year % 4 == 0) return true;
    return false;
  }

  var DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

  function daysInMonth (month, year) {
    var days = DAYS_IN_MONTH[month];
    if (month == 1 && isLeapYear(year)) days++;
    return days;
  }

  function parseUntil (until) {
    if (until) {
      var fields = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).000Z$/.exec(until).slice(1, 7);
      for (var i = 0, stop = fields.length; i < stop; i++) {
        fields[i] = parseInt(fields[i], 10);
      }
      --fields[1];
      return Date.UTC.apply(Date.UTC, fields);
    }
    return Number.MAX_VALUE;
  }
  function actualize (entry, rule, year, ruleIndex) {
    var time = /^(\d+):(\d+)(?::(\d+))?[us]?$/.exec(rule.time).slice(1, 4);
    for (var i = 0, stop = time.length; i < stop; i++) {
      time[i] = parseInt(time[i] || 0, 10);
    }
    var hours = time[0], minutes = time[1], seconds = time[2];
    var date = /^(?:(\d+)|last(\w+)|(\w+)>=(\d+))$/.exec(rule.day);
    var fields;
    if (date[1]) {
      fields = new Date(Date.UTC(year, rule.month, parseInt(date[1], 10), hours, minutes, seconds));
    } else if (date[2]) {
      var days = en_US.day.abbrev;
      for (var i = 0, stop = days.length; i < stop; i++)
        if (days[i] === date[2]) break;
      var day = daysInMonth(rule.month, year);
      for (;;) {
        fields = new Date(Date.UTC(year, rule.month, day, hours, minutes, seconds))
        if (fields.getUTCDay() === i) break;
        day--;
      }
    } else {
      var min = parseInt(date[4], 10);
      var days = en_US.day.abbrev;
      for (var i = 0, stop = days.length; i < stop; i++)
        if (days[i] === date[3]) break;
      day = 1;
      for (;;) {
        fields = new Date(Date.UTC(year, rule.month, day, hours, minutes, seconds))
        if (fields.getUTCDay() === i && fields.getUTCDate() >= min) break;
        day++;
      }
    }

    var save = parseOffset(rule.save || '0');

    var offset = entry.offset;

    var sortable, wallclock, clock, posix, standard;
    if (/u$/.test(rule.time)) {
      posix = fields.getTime();
      fields = new Date(fields.getTime() + offset);
      clock = "posix";
    } else if (/s$/.test(rule.time)) {
      standard = fields.getTime();
      fields = new Date(standard);
      clock = "standard";
    } else {
      wallclock = fields.getTime();
      fields = new Date(wallclock);
      clock = "wallclock";
    }

    sortable = Date.UTC(fields.getUTCFullYear(), fields.getUTCMonth(), fields.getUTCDate());

    return {
      clock: clock,
      standard: standard,
      entry: entry,
      sortable: sortable,
      rule:rule,
      wallclock: wallclock,
      year: year,
      posix: posix,
      save: save,
      ruleIndex: ruleIndex,
      offset: offset
    };
  }

  function setClocks (record, effective, clock) {
    var offset = effective.offset
      , save = effective.save;
    switch (clock || record.clock) {
    case "posix":
      record.standard = record.posix + offset;
      record.wallclock = record.posix + offset + save;
      break;
    case "wallclock":
      record.posix = record.wallclock - offset - save;
      record.standard = record.wallclock + save;
      break;
    case "standard":
      record.posix = record.standard - offset;
      record.wallclock = record.standard + save;
      break;
    }
    return record;
  }

  function ruleClock(rule) {
    if (/[ugz]$/.exec(rule.time)) return "posix";
    if (/s$/.exec(rule.time)) return "standard";
    return "wallclock";
  }

  function getYear (time) { return new Date(time).getUTCFullYear() }

  function pushRule (table, entry, actual, abbrevs) {
    var save = parseOffset(actual.rule.save || "0")
      , abbrev = abbrevs[save ? 1 : 0] || entry.format.replace(/%s/, function () { return actual.rule.letter });
    table.push({
      actualization: true,
      offset: entry.offset,
      abbrev: abbrev,
      clock: actual.clock,
      wallclock: actual.wallclock,
      posix: actual.posix,
      standard: actual.standard,
      save: parseOffset(actual.rule.save || "0")
    });
  }

  function iso8601 (date) { return new Date(date).toISOString().replace(/\..*$/, "") }

  function step (begin, end, table) {
    var match
      , actual
      , max;

    // Oink. Oink. We'll be pigs.

    var rule
      , abbrevs
      , year = getYear(new Date().getTime())
      , rules = data.rules[begin.rules].slice(0)
      , actualized = [];

    if (abbrevs = /(\w+)\/(\w+)/.exec(begin.format)) abbrevs.shift();
    else abbrevs = []

    for (var i = 0, length = rules.length; i < length; i++) {
      rules[i].clock = ruleClock(rules[i]); // TODO Temporary.
      for (var j = rules[i].from, to = Math.min(rules[i].to, year); j <= to; j++) {
        actualized.push(actualize(begin, rules[i], j, i));
      }
    }

    actualized.sort(function (a, b) { return a.sortable - b.sortable });

    i = 0, length = actualized.length

    for (; i < length; i++) {
      if (begin[actualized[i].clock] <= actualized[i][actualized[i].clock]) break;
    }

    var previous = begin;

    if (begin[actualized[i].clock] == actualized[i][actualized[i].clock]) {
      table.pop(); // A rule on the seam overrides the seam.
      previous = table[table.length - 1];
    } else {
      if (i === 0) {
        var rules = data.rules[begin.rules], offset;
        for (var j = 0; j < rules.length; j++) {
          if (!(offset = parseOffset(rules[j].save || "0"))) {
            begin.abbrev = abbrevs[0] || begin.format.replace(/%s/, function () { return rules[j].letter });
            break;
          }
        }
      } else {
        begin.save = parseOffset(actualized[i - 1].save);
        begin.abbrev = abbrevs[begin.save ? 1 : 0] || begin.format.replace(/%s/, function () { return actualized[i - 1].rule.letter });
      }
    }

    for (; i < length; i++) {
      setClocks(actualized[i], previous);
      if (actualized[i][end.clock] >= end[end.clock]) {
        break;
      }
      pushRule(table, begin, actualized[i], abbrevs);
      previous = actualized[i];
    }
  }

  function walk (begin, end, table) {
    step(begin, end, table);
    return table[table.length - 1];
  }

  function begins (zone) {
    var copy = [];
    for (var i = zone.length - 2; i >= 0; --i) {
      copy[i] = {
        rules: zone[i].rules,
        format: zone[i].format,
        offset: parseOffset(zone[i].offset),
        save: 0,
        // TODO Intermediate format is all kinds of broken.
        clock: zone[i + 1].utc ? 'posix' : (zone[i + 1].standard ? 'standard' : 'wallclock')
      };
      copy[i][copy[i].clock] = parseUntil(zone[i + 1].until);
    }

    copy.push({
      offset: parseOffset(zone[zone.length - 1].offset),
      format: zone[zone.length - 1].format,
      save: 0
    });

    copy.reverse();
    copy[0].posix = copy[0].wallclock = Number.MIN_VALUE;
    copy.forEach(function (e) { e.begins =  iso8601(e[e.clock]) + " " + e.clock });
    return copy;
  }

  return function transitions (zoneName, consumer) {
    // We `concat` because someday, we'll read right out of the database and the
    // `concat` will be our defensive copy.
    var table = []
      , zone = begins(data.zones[zoneName]).concat({ offset: "0" })
      , entry = zone.shift()
      , previous, offset, save = 0, wallclock, posix, rules;

    table.push(entry);

    for (var i = 0, length = zone.length; i < Math.min(13, length); i++) {
      previous = entry;
      entry = zone[i];

      previous.abbrev = previous.format;

      if (previous.rules) {
        if (!(previous.save = parseOffset(previous.rules))) {
          previous = walk(previous, entry, table); // previous is last rule, not last zone.
        }
      } else {
        previous.save = 0;
      }

      setClocks(entry, previous);

      table.push(entry);
    }
    return table.reverse();
  }
})();

(function () {
  function pad (value) { return ('00' + value).slice(-2) }
  function formatOffset (offset) {
    var increment = offset / Math.abs(offset);
    var sign = offset < 0 ? '-' : '+';
    var millis, seconds, minutes, hours;
    offset = Math.abs(offset);
    offset -= (millis = offset % 1000);
    offset /= 1000;
    offset -= (seconds = offset % 60);
    offset /= 60;
    offset -= (minutes = offset % 60);
    hours = offset / 60;
    return sign + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
  }
  function iso8601 (date) {
    return new Date(date).toISOString().replace(/\..*$/, "");
  }
  function format(entry) {
    if (! entry.abbrev) entry.abbrev = entry.format;
    return formatOffset(entry.offset + (entry.save || 0)) + '/' + entry.abbrev;
  }
  var set = process.argv[2] ? [ process.argv[2] ] : Object.keys(data.zones).filter(function (e) { return /^A/.test(e) });
  for (var i = 0, length = set.length; i < length; i++) {
    try {
      var table = transitions(set[i], function (entry, posix, wallclock) {
        entry.posix = posix;
        entry.wallclock = wallclock;
      });
      for (var j = 1, stop = table.length - 1; j < stop; j++) {
        entry = table[j];
        say("%s %s %s %s", set[i], iso8601(entry.wallclock), iso8601(entry.posix), format(table[j + 1]), format(table[j]));
      }
    } catch (e) {
      say("Failed on " + set[i] + ".");
      throw e;
    }
  }
})();
<|endoftext|>


<commit_before>module.exports = grammar({
  name: 'ruby',

  extras: $ => [
    $.comment,
	$._line_break,
	/[ \t\r]/
  ]

  rules: {
    program: $ => $._compound_statement,

	_compound_statement: $ => seq($._statement, rep(seq($._terminator, $._expression)), optional($._terminator)),

	_statement: $ => choice($._expression),
	_expression: $ => choice($._argument),

	_argument: $ => choice($._primary),

	_primary: $ => choice($._variable),

	_variable: $ => choice($.identifier , 'nil', 'self'),

	identifier: $ => seq(rep(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/),

	comment: $ => seq('#', /.*/),

    _line_break: $ => '\n',
	_terminator: $ => choice($._line_break, ';'),
  }
});
<commit_msg>Comma!<commit_after>module.exports = grammar({
  name: 'ruby',

  extras: $ => [
    $.comment,
	$._line_break,
	/[ \t\r]/
  ],

  rules: {
    program: $ => $._compound_statement,

	_compound_statement: $ => seq($._statement, rep(seq($._terminator, $._expression)), optional($._terminator)),

	_statement: $ => choice($._expression),
	_expression: $ => choice($._argument),

	_argument: $ => choice($._primary),

	_primary: $ => choice($._variable),

	_variable: $ => choice($.identifier , 'nil', 'self'),

	identifier: $ => seq(rep(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/),

	comment: $ => seq('#', /.*/),

    _line_break: $ => '\n',
	_terminator: $ => choice($._line_break, ';'),
  }
});
<|endoftext|>


<commit_before>
/*********************************************************************************************************************
*
* Side-loaded page stuff.
*
*********************************************************************************************************************/

const ajax = require( 'util/ajax' );
const lazyload = require( 'util/lazyload' );
const awaitTransition = require( 'util/awaitTransition' );

const DEFAULT_NAVIGATION = {
  append: true,
  query:  null,
  method: 'GET',
  url:    ''
};

function Page( elRoot )
{
  let elNav = null;
  let elTitle = null;
  let elContent = null;

  /**
  * Updates the page with the content returned from an AJAX call.
  *
  * @param {Object} oData - the new page data.
  */
  function updateContent( oData )
  {
    // fade all the content out, then…
    elContent.classList.add( '-out' );
    awaitTransition( elContent ).then( () =>
    {
      // 1. update the title
      elTitle.textContent = oData.title;

      // 2. remove all content + insert new
      while ( elContent.firstChild !== null )
      {
        elContent.firstChild.remove();
      }
      elContent.insertAdjacentHTML( 'afterbegin', oData.content );

      // 3. retrigger our behaviours, lazyload, and rebind all links
      bindLinks( elContent ); // eslint-disable-line no-use-before-define
      lazyload( elContent );

      // 4. update the nav state
      elNav.querySelectorAll( 'a' ).forEach( el =>
      {
        if (( el.pathname === oData.path ) ||
        ( el.hasAttribute( 'data-wildcard' ) && oData.path.startsWith( el.pathname )))
        {
          el.classList.add( '-current' );
        }
        else
        {
          el.classList.remove( '-current' );
        }
      });

      // 4. finally, remove any active elements, scroll up, and remove the load state(s)
      document.activeElement.blur();
      window.scrollTo( 0, 0 );
      elRoot.dispatchEvent( new CustomEvent( 'navigatedTo', { detail: { url: oData.path }}))

    }).then( () =>
    {
      elContent.classList.remove( '-out' );
      awaitTransition( elContent ).then(() => elContent.classList.remove( '-loading' ));
    });

    // container classes
    elRoot.classList.add( '-js-loaded' );
    elRoot.classList.remove( '-js-loading' );
    setTimeout( () => elRoot.classList.remove( '-js-loaded' ), 500 );
  }

  /**
  * Loads a given URL.
  *
  * @param {Object} oConf - any additional parameters that should be handled.
  * @return {boolean} whether or not the navigation will be successful.
  */
  function navigateTo( oConf )
  {
    // 0. default some stuff
    const { url, method, query, append } = Object.assign( {}, DEFAULT_NAVIGATION, oConf );

    // 1. work out our request URL + some parameters
    const sRequestUrl = ( url === '/' )
      ? 'home.jhtml'
      : ( url.indexOf( '?' ) === -1 ? url + '.jhtml' : url.replace( '?', '.jhtml?' ));

    // 1. request
    ajax( sRequestUrl, query, method )
      .then( updateContent )
      .then(() => ( append && window.history.pushState( {}, elTitle.textContent, url )))
      .catch( () => document.location.href = url );

    // 2. classes
    elContent.classList.add( '-loading' );
    elRoot.classList.remove( '-js-loaded' );
    elRoot.classList.add( '-js-loading' );
    return true;
  }

  /**
  * Binds links within the given DOM node.
  *
  * @param {HTMLElement} elNode - the node to search within.
  */
  function bindLinks( elNode )
  {
    // eslint-disable-next-line
    elNode.querySelectorAll( 'a:not([href^="http:"]):not([href^="https:"]):not([href^="mailto:"]):not([href^="/m"]):not(.no-ajax)').forEach( elLink =>
    {
      elLink.addEventListener( 'click', ev => ( navigateTo({ url: elLink.pathname + elLink.search }) && ev.preventDefault()));
    });
  }

  /**
  * Handles online/offline events.
  */
  function handleConnectionChange()
  {
    if ( navigator.onLine )
    {
      document.body.classList.add( 'is-online' );
      document.body.classList.remove( 'is-offline' );
    }
    else
    {
      document.body.classList.add( 'is-offline' );
      document.body.classList.remove( 'is-online' );
    }

    document.body.dispatchEvent( new CustomEvent( 'connection-change', { detail: { linkState: navigator.onLine }}));
  }

  /* Constructor */
  return (function init()
  {
    // 0. don’t even bother if we can’t fetch
    if ( window.fetch === undefined )
    {
      return;
    }

    // 1. acquire DOM nodes
    elNav = elRoot.querySelector( '[data-page-nav]' );
    elContent = elRoot.querySelector( '[data-page-content]' );
    elTitle = document.querySelector( 'head title' );
    if (( elNav === null ) || ( elContent === null ) || ( elTitle === null ))
    {
      return;
    }

    // 2. bind links + popstate
    bindLinks( elRoot );
    window.addEventListener( 'popstate', () => navigateTo({ url: document.location.pathname, append: false }));
    elRoot.addEventListener( 'navigateTo', ev => navigateTo( ev.detail ));

    // 3. add class
    elContent.classList.add( 'js-page' );

    // 4. handle online/offline stuff
    window.addEventListener( 'online', handleConnectionChange );
    window.addEventListener( 'offline', handleConnectionChange );
    handleConnectionChange();

    return {};
  }());
}

module.exports = {
  name: 'page',
  init: Page
};
<commit_msg>Fixing bug with JS navigation<commit_after>
/*********************************************************************************************************************
*
* Side-loaded page stuff.
*
*********************************************************************************************************************/

const ajax = require( 'util/ajax' );
const lazyload = require( 'util/lazyload' );
const awaitTransition = require( 'util/awaitTransition' );

const DEFAULT_NAVIGATION = {
  append: true,
  query:  null,
  method: 'GET',
  url:    ''
};

function Page( elRoot )
{
  let elNav = null;
  let elTitle = null;
  let elContent = null;

  /**
  * Updates the page with the content returned from an AJAX call.
  *
  * @param {Object} oData - the new page data.
  */
  function updateContent( oData )
  {
    // fade all the content out, then…
    elContent.classList.add( '-out' );
    awaitTransition( elContent ).then( () =>
    {
      // 1. update the title
      elTitle.textContent = oData.title;

      // 2. remove all content + insert new
      while ( elContent.firstChild !== null )
      {
        elContent.firstChild.remove();
      }
      elContent.insertAdjacentHTML( 'afterbegin', oData.content );

      // 3. retrigger our behaviours, lazyload, and rebind all links
      bindLinks( elContent ); // eslint-disable-line no-use-before-define
      lazyload( elContent );

      // 4. update the nav state
      elNav.querySelectorAll( 'a' ).forEach( el =>
      {
        if (( el.pathname === oData.path.replace( /\.jhtml$/, '' ) ) ||
        ( el.hasAttribute( 'data-wildcard' ) && oData.path.startsWith( el.pathname )))
        {
          el.classList.add( '-current' );
        }
        else
        {
          el.classList.remove( '-current' );
        }
      });

      // 4. finally, remove any active elements, scroll up, and remove the load state(s)
      document.activeElement.blur();
      window.scrollTo( 0, 0 );
      elRoot.dispatchEvent( new CustomEvent( 'navigatedTo', { detail: { url: oData.path }}))

    }).then( () =>
    {
      elContent.classList.remove( '-out' );
      awaitTransition( elContent ).then(() => elContent.classList.remove( '-loading' ));
    });

    // container classes
    elRoot.classList.add( '-js-loaded' );
    elRoot.classList.remove( '-js-loading' );
    setTimeout( () => elRoot.classList.remove( '-js-loaded' ), 500 );
  }

  /**
  * Loads a given URL.
  *
  * @param {Object} oConf - any additional parameters that should be handled.
  * @return {boolean} whether or not the navigation will be successful.
  */
  function navigateTo( oConf )
  {
    // 0. default some stuff
    const { url, method, query, append } = Object.assign( {}, DEFAULT_NAVIGATION, oConf );

    // 1. work out our request URL + some parameters
    const sRequestUrl = ( url === '/' )
      ? 'home.jhtml'
      : ( url.indexOf( '?' ) === -1 ? url + '.jhtml' : url.replace( '?', '.jhtml?' ));

    // 1. request
    ajax( sRequestUrl, query, method )
      .then( updateContent )
      .then(() => ( append && window.history.pushState( {}, elTitle.textContent, url )))
      .catch( () => document.location.href = url );

    // 2. classes
    elContent.classList.add( '-loading' );
    elRoot.classList.remove( '-js-loaded' );
    elRoot.classList.add( '-js-loading' );
    return true;
  }

  /**
  * Binds links within the given DOM node.
  *
  * @param {HTMLElement} elNode - the node to search within.
  */
  function bindLinks( elNode )
  {
    // eslint-disable-next-line
    elNode.querySelectorAll( 'a:not([href^="http:"]):not([href^="https:"]):not([href^="mailto:"]):not([href^="/m"]):not(.no-ajax)').forEach( elLink =>
    {
      elLink.addEventListener( 'click', ev => ( navigateTo({ url: elLink.pathname + elLink.search }) && ev.preventDefault()));
    });
  }

  /**
  * Handles online/offline events.
  */
  function handleConnectionChange()
  {
    if ( navigator.onLine )
    {
      document.body.classList.add( 'is-online' );
      document.body.classList.remove( 'is-offline' );
    }
    else
    {
      document.body.classList.add( 'is-offline' );
      document.body.classList.remove( 'is-online' );
    }

    document.body.dispatchEvent( new CustomEvent( 'connection-change', { detail: { linkState: navigator.onLine }}));
  }

  /* Constructor */
  return (function init()
  {
    // 0. don’t even bother if we can’t fetch
    if ( window.fetch === undefined )
    {
      return;
    }

    // 1. acquire DOM nodes
    elNav = elRoot.querySelector( '[data-page-nav]' );
    elContent = elRoot.querySelector( '[data-page-content]' );
    elTitle = document.querySelector( 'head title' );
    if (( elNav === null ) || ( elContent === null ) || ( elTitle === null ))
    {
      return;
    }

    // 2. bind links + popstate
    bindLinks( elRoot );
    window.addEventListener( 'popstate', () => navigateTo({ url: document.location.pathname, append: false }));
    elRoot.addEventListener( 'navigateTo', ev => navigateTo( ev.detail ));

    // 3. add class
    elContent.classList.add( 'js-page' );

    // 4. handle online/offline stuff
    window.addEventListener( 'online', handleConnectionChange );
    window.addEventListener( 'offline', handleConnectionChange );
    handleConnectionChange();

    return {};
  }());
}

module.exports = {
  name: 'page',
  init: Page
};
<|endoftext|>


<commit_before>'use strict';

angular.module('classBrowserUHApp.department', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/department', {
        templateUrl: 'views/department/department.html',
        controller: 'DepartmentCtrl'
    });
}])

.controller('DepartmentCtrl', function($scope, $http) {
    var url = $scope.apiUrl + '/department';

    $scope.resultSet = [];
    $scope.numberOfRows = 0;

    $scope.populateDepartments = function() {
        console.log("Populating departments...");

        $http.get(url)
            .success(function(data) {
                console.log("Retrieved " + data.numberOfRows + " departments.");
                console.log(data);
                $scope.resultSet = data.result;
                $scope.showDiv = true;
                $scope.numberOfRows = data.numberOfRows;
            })
            .error(function(data) {
                alert("Unable to retrieve the data.");
            });
    }
});<commit_msg>Added scope variable, isDataLoading, that dictates when the loading icon shows up.<commit_after>'use strict';

angular.module('classBrowserUHApp.department', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/department', {
        templateUrl: 'views/department/department.html',
        controller: 'DepartmentCtrl'
    });
}])

.controller('DepartmentCtrl', function($scope, $http) {
    var url = $scope.apiUrl + '/department';
    $scope.resultSet = [];
    $scope.numberOfRows = 0;

    $scope.populateDepartments = function() {
        $scope.isDataLoading = true;
        $http.get(url)
            .success(function(data) {
                console.log("Retrieved " + data.numberOfRows + " departments.");
                console.log(data);
                $scope.resultSet = data.result;
                $scope.showDiv = true;
                $scope.numberOfRows = data.numberOfRows;
            })
            .error(function(data) {
                alert("Unable to retrieve the data.");
            })
            .finally(function() {
                $scope.isDataLoading = false;
            });
    }
});<|endoftext|>


<commit_before>(function () {
    "use strict";

    Mapbender.Digitizer.Menu = function (schema) {

        var menu = this;
        menu.schema = schema;

        var frame = $("
").addClass('frame');

        frame.append('
');

        menu.appendResultTableControlButtons_(frame);

        menu.appendCurrentExtentSwitch_(frame);

        menu.generateResultTable_(frame);

        frame.hide();

        menu.currentExtentSearch = schema.currentExtentSearch;
    };

    Mapbender.Digitizer.Menu.prototype.appendResultTableControlButtons_ = function (frame) {
        var menu = this;
        var schema = menu.schema;

        var buttons = {};

        if (schema.showVisibilityNavigation && schema.allowChangeVisibility) {

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-eyeOff eyeOff");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.hideAll'));
            $button.click(function (event) {
                schema.layer.getSource().getFeatures().forEach(function (feature) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: true});
                });
            });
            buttons['hideAll'] = $button;

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-eyeOn eyeOn");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.showAll'));
            $button.click(function (event) {
                schema.layer.getSource().getFeatures().forEach(function (feature) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: false});
                });
            });
            buttons['showAll'] = $button;
        }
        if (schema.allowSaveAll) {

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-save save");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.saveAll'));
            $button.attr("disabled", "disabled");
            $button.click(function () {
                schema.layer.getSource().getFeatures().filter(function (feature) {
                    return (["isNew", "isChanged", "isCopy"].includes(feature.get("modificationState")));
                }).forEach(function (feature) {
                    schema.saveFeature(feature);
                });
            });
            buttons['allowSaveAll'] = $button;

        }

        var $div = $("
");
        $div.addClass("resultTableControlButtons");
        $.each(buttons, function (name, $button) {
            $div.append($button);
        });
        frame.append($div);
    };

    Mapbender.Digitizer.Menu.prototype.appendCurrentExtentSwitch_ = function (frame) {
        var menu = this;
        var schema = menu.schema;
        if (schema.showExtendSearchSwitch) {
            var $checkbox = $("<input type='checkbox' />");
            var title = Mapbender.trans('mb.digitizer.toolset.current-extent');
            $checkbox.attr('title', title);
            if (schema.currentExtentSearch) {
                $checkbox.attr("checked", "checked");
            }
            $checkbox.change(function (e) {
                var currentExtentSearch = !!$(e.originalEvent.target).prop("checked");
                menu.changeCurrentExtentSearch_(currentExtentSearch)
            });
            frame.append("
");
            var $div = $("
");
            $div.addClass("form-group checkbox onlyExtent");
            var $label = $("");
            $label.append($checkbox);
            $label.append(title);
            $div.append($label);
            frame.append($div);
        }
    };

    Mapbender.Digitizer.Menu.prototype.changeCurrentExtentSearch_ = function(currentExtentSearch) {
        var widget = this.widget;
        this.currentExtentSearch = !!currentExtentSearch;
        if (this.resultTable) {
            var features = this.schema.layer.getSource().getFeatures();
            if (this.currentExtentSearch) {
                features = features.filter(function(feature) {
                    return widget.isInExtent(feature);
                });
            }
            this.resultTable.redraw(features);
        }
    };

    Mapbender.Digitizer.Menu.prototype.registerResultTableEvents = function (resultTable, frame) {
        var menu = this;
        var schema = menu.schema;
        var widget = schema.widget;
        var map = widget.map;
        menu.resultTable = resultTable;

        $(schema).on("Digitizer.FeaturesLoaded", function (event) {
            var features = event.features;
            resultTable.redraw(features);
        });

        $(schema).on("Digitizer.FeatureAddedManually", function (event) {
            var feature = event.feature;
            resultTable.addRow(feature);
        });

        map.on(ol.MapEventType.MOVEEND, function (event) {

            var resolution = map.getView().getResolution();

            if (resolution > schema.layer.getMaxResolution() || resolution < schema.layer.getMinResolution()) {

                resultTable.clear();

            } else {

                if (resultTable.currentExtentSearch) {
                    var features = schema.layer.getSource().getFeatures().filter(function (feature) {
                        return widget.isInExtent(feature);
                    });
                    resultTable.redraw(features);
                } else {
                    resultTable.redraw(schema.layer.getSource().getFeatures());
                }

            }

        });

        resultTable.element.delegate("tbody > tr", 'click', function () {
            var tr = this;
            var row = resultTable.getApi().row(tr);
            var feature = row.data();

            if (feature) {

                if (schema.zoomOnResultTableClick) {
                    schema.zoomToFeature(feature);
                }
                if (schema.openDialogOnResultTableClick) {
                    schema.openFeatureEditDialog(feature);
                }
            } else {
                console.warn("No Feature in row", row);
            }

        });

        schema.layer.getSource().on(ol.source.VectorEventType.ADDFEATURE, function (event) {
            var feature = event.feature;

            if (resultTable.currentExtentSearch && !widget.isInExtent(feature)) {
                return;
            }

            feature.on('Digitizer.HoverFeature', function (event) {

                resultTable.hoverInResultTable(feature, true);

            });

            feature.on('Digitizer.UnhoverFeature', function (event) {

                resultTable.hoverInResultTable(feature, false);

            });

            feature.on('Digitizer.ModifyFeature', function (event) {

                var $button = resultTable.getButtonByFeature('.save', feature);
                if ($button) {
                    $button.removeAttr("disabled");
                }

                frame.find(".resultTableControlButtons .save").removeAttr("disabled");

            });

            feature.on('Digitizer.UnmodifyFeature', function (event) {

                var $button = resultTable.getButtonByFeature('.save', feature);
                if ($button) {
                    $button.attr("disabled", "disabled");
                }

                var length = schema.layer.getSource().getFeatures().filter(function (feature) {
                    return ["isNew", "isChanged", "isCopy"].includes(feature.get("modificationState"));
                }).length;

                if (length === 0) {
                    frame.find(".resultTableControlButtons .save").attr("disabled", "disabled");
                }

            });

            feature.on('Digitizer.toggleVisibility', function (event) {
                var $button = resultTable.getButtonByFeature('.visibility', feature);
                if (!$button) {
                    return;
                }
                if (event.hide) {
                    $button.addClass('icon-eyeOn').removeClass('icon-eyeOff');
                    $button.attr('title', Mapbender.trans('mb.digitizer.feature.visibility.toggleon'));
                } else {
                    $button.addClass('icon-eyeOff').removeClass('icon-eyeOn');
                    $button.attr('title', Mapbender.trans('mb.digitizer.feature.visibility.toggleoff'));
                }
            });

        });

        schema.layer.getSource().on(ol.source.VectorEventType.REMOVEFEATURE, function (event) {
            resultTable.deleteRow(event.feature);
        });

    };

    Mapbender.Digitizer.Menu.prototype.generateResultDataTableButtons = function () {
        var menu = this;
        var schema = menu.schema;

        var buttons = {};

        if (schema.allowLocate) {
            buttons['locate'] = {
                title: Mapbender.trans('mb.digitizer.feature.zoomTo'),
                className: 'zoom',
                onClick: function (feature, ui) {
                    schema.zoomToFeature(feature);
                }
            };
        }

        if (schema.allowEditData && schema.allowSaveInResultTable) {
            buttons['save'] = {
                title: Mapbender.trans('mb.digitizer.feature.save.title'),
                className: 'save',
                disabled: true,
                onClick: function (feature, $button) {
                    schema.saveFeature(feature);
                }
            };
        }

        if (schema.allowEditData) {
            buttons['edit'] = {
                title: Mapbender.trans('mb.digitizer.feature.edit'),
                className: 'edit',
                onClick: function (feature, ui) {
                    schema.openFeatureEditDialog(feature);
                }
            };
        }
        if (schema.copy && schema.copy.enable) {
            buttons['copy'] = {
                title: Mapbender.trans('mb.digitizer.feature.clone.title'),
                className: 'copy',
                onClick: function (feature, ui) {
                    schema.copyFeature(feature);
                }
            };
        }
        if (schema.allowCustomStyle) {
            buttons['style'] = {
                title: Mapbender.trans('mb.digitizer.feature.style.change'),
                className: 'style',
                onClick: function (feature, ui) {
                    schema.openChangeStyleDialog(feature);
                }
            };
        }

        if (schema.allowChangeVisibility) {
            buttons['toggleVisibility'] = {
                title: Mapbender.trans('mb.digitizer.feature.visibility.toggleoff'),
                className: 'visibility',
                cssClass: 'icon-eyeOff',
                onClick: function (feature, $button) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: !feature.get("hidden")});
                }
            };
        }

        if (schema.allowDelete) {

            buttons['delete'] = {
                title: Mapbender.trans("mb.digitizer.feature.remove.title"),
                className: 'remove',
                cssClass: 'critical',
                onClick: function (feature, ui) {
                    if (schema.allowDelete) {
                        schema.removeFeature(feature);
                    } else {
                        $.notify("Deletion is not allowed");
                    }
                }
            };
        }

        return buttons;

    };

    Object.assign(Mapbender.Digitizer.Menu.prototype, {
        generateResultTable_: function (frame) {
            var menu = this;
            var schema = menu.schema;
            var widget = schema.widget;

            var resultTable;

            var generateResultDataTableColumns = function () {

                var columns = [];

                var createResultTableDataFunction = function (columnId, fieldSettings) {

                    return function (feature, type, val, meta) {

                        var escapeHtml = function (str) {

                            return str.replace(/["&'\/<>]/g, function (a) {
                                return {
                                    '"': '"',
                                    '&': '&',
                                    "'": ''',
                                    '/': '/',
                                    '<': '<',
                                    '>': '>'
                                }[a];
                            });
                        };

                        var data = feature.get('data') && feature.get('data').get(columnId);
                        if (typeof (data) == 'string') {
                            data = escapeHtml(data);
                        }
                        return data || '';
                    };
                };

                $.each(schema.tableFields, function (columnId, fieldSettings) {
                    fieldSettings.title = fieldSettings.label;
                    fieldSettings.data = fieldSettings.data || createResultTableDataFunction(columnId, fieldSettings);
                    columns.push(fieldSettings);
                });

                return columns;

            };

            var buttons = menu.generateResultDataTableButtons();

            var resultTableSettings = {
                lengthChange: false,
                pageLength: schema.pageLength,
                searching: schema.inlineSearch,
                info: true,
                processing: false,
                ordering: true,
                paging: true,
                selectable: false,
                autoWidth: false,
                columns: generateResultDataTableColumns(),
                buttons: buttons,
                oLanguage: widget.options.tableTranslation
            };

            if (schema.view && schema.view.settings) {
                resultTableSettings = Object.assign({},resultTableSettings,schema.view.settings);
            }

            var $div = $("
");
            var $table = $div.resultTable(resultTableSettings);

            resultTable = $table.resultTable("instance");

            // ??? function does not exist
            // resultTable.initializeColumnTitles();

            resultTable.element.delegate("tbody > tr", 'mouseenter', function () {
                var tr = this;
                var row = resultTable.getApi().row(tr);
                var feature = row.data();
                if (feature) {
                    feature.dispatchEvent({type: widget.TYPE + '.HoverFeature'});
                }

            });

            resultTable.element.delegate("tbody > tr", 'mouseleave', function () {
                var tr = this;
                var row = resultTable.getApi().row(tr);
                var feature = row.data();
                if (feature) {
                    feature.dispatchEvent({type: widget.TYPE + '.UnhoverFeature'});
                }
            });

            // menu.registerResultTableEvents(resultTable, frame);

            frame.append($table);
        }
    });

})();
<commit_msg>There is no "view" attribute in schema configs (no random javascript widget options in application configs)<commit_after>(function () {
    "use strict";

    Mapbender.Digitizer.Menu = function (schema) {

        var menu = this;
        menu.schema = schema;

        var frame = $("
").addClass('frame');

        frame.append('
');

        menu.appendResultTableControlButtons_(frame);

        menu.appendCurrentExtentSwitch_(frame);

        menu.generateResultTable_(frame);

        frame.hide();

        menu.currentExtentSearch = schema.currentExtentSearch;
    };

    Mapbender.Digitizer.Menu.prototype.appendResultTableControlButtons_ = function (frame) {
        var menu = this;
        var schema = menu.schema;

        var buttons = {};

        if (schema.showVisibilityNavigation && schema.allowChangeVisibility) {

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-eyeOff eyeOff");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.hideAll'));
            $button.click(function (event) {
                schema.layer.getSource().getFeatures().forEach(function (feature) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: true});
                });
            });
            buttons['hideAll'] = $button;

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-eyeOn eyeOn");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.showAll'));
            $button.click(function (event) {
                schema.layer.getSource().getFeatures().forEach(function (feature) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: false});
                });
            });
            buttons['showAll'] = $button;
        }
        if (schema.allowSaveAll) {

            var $button = $("<button class='button' type='button'/>");
            $button.addClass("icon-save save");
            $button.attr("title", Mapbender.trans('mb.digitizer.toolset.saveAll'));
            $button.attr("disabled", "disabled");
            $button.click(function () {
                schema.layer.getSource().getFeatures().filter(function (feature) {
                    return (["isNew", "isChanged", "isCopy"].includes(feature.get("modificationState")));
                }).forEach(function (feature) {
                    schema.saveFeature(feature);
                });
            });
            buttons['allowSaveAll'] = $button;

        }

        var $div = $("
");
        $div.addClass("resultTableControlButtons");
        $.each(buttons, function (name, $button) {
            $div.append($button);
        });
        frame.append($div);
    };

    Mapbender.Digitizer.Menu.prototype.appendCurrentExtentSwitch_ = function (frame) {
        var menu = this;
        var schema = menu.schema;
        if (schema.showExtendSearchSwitch) {
            var $checkbox = $("<input type='checkbox' />");
            var title = Mapbender.trans('mb.digitizer.toolset.current-extent');
            $checkbox.attr('title', title);
            if (schema.currentExtentSearch) {
                $checkbox.attr("checked", "checked");
            }
            $checkbox.change(function (e) {
                var currentExtentSearch = !!$(e.originalEvent.target).prop("checked");
                menu.changeCurrentExtentSearch_(currentExtentSearch)
            });
            frame.append("
");
            var $div = $("
");
            $div.addClass("form-group checkbox onlyExtent");
            var $label = $("");
            $label.append($checkbox);
            $label.append(title);
            $div.append($label);
            frame.append($div);
        }
    };

    Mapbender.Digitizer.Menu.prototype.changeCurrentExtentSearch_ = function(currentExtentSearch) {
        var widget = this.widget;
        this.currentExtentSearch = !!currentExtentSearch;
        if (this.resultTable) {
            var features = this.schema.layer.getSource().getFeatures();
            if (this.currentExtentSearch) {
                features = features.filter(function(feature) {
                    return widget.isInExtent(feature);
                });
            }
            this.resultTable.redraw(features);
        }
    };

    Mapbender.Digitizer.Menu.prototype.registerResultTableEvents = function (resultTable, frame) {
        var menu = this;
        var schema = menu.schema;
        var widget = schema.widget;
        var map = widget.map;
        menu.resultTable = resultTable;

        $(schema).on("Digitizer.FeaturesLoaded", function (event) {
            var features = event.features;
            resultTable.redraw(features);
        });

        $(schema).on("Digitizer.FeatureAddedManually", function (event) {
            var feature = event.feature;
            resultTable.addRow(feature);
        });

        map.on(ol.MapEventType.MOVEEND, function (event) {

            var resolution = map.getView().getResolution();

            if (resolution > schema.layer.getMaxResolution() || resolution < schema.layer.getMinResolution()) {

                resultTable.clear();

            } else {

                if (resultTable.currentExtentSearch) {
                    var features = schema.layer.getSource().getFeatures().filter(function (feature) {
                        return widget.isInExtent(feature);
                    });
                    resultTable.redraw(features);
                } else {
                    resultTable.redraw(schema.layer.getSource().getFeatures());
                }

            }

        });

        resultTable.element.delegate("tbody > tr", 'click', function () {
            var tr = this;
            var row = resultTable.getApi().row(tr);
            var feature = row.data();

            if (feature) {

                if (schema.zoomOnResultTableClick) {
                    schema.zoomToFeature(feature);
                }
                if (schema.openDialogOnResultTableClick) {
                    schema.openFeatureEditDialog(feature);
                }
            } else {
                console.warn("No Feature in row", row);
            }

        });

        schema.layer.getSource().on(ol.source.VectorEventType.ADDFEATURE, function (event) {
            var feature = event.feature;

            if (resultTable.currentExtentSearch && !widget.isInExtent(feature)) {
                return;
            }

            feature.on('Digitizer.HoverFeature', function (event) {

                resultTable.hoverInResultTable(feature, true);

            });

            feature.on('Digitizer.UnhoverFeature', function (event) {

                resultTable.hoverInResultTable(feature, false);

            });

            feature.on('Digitizer.ModifyFeature', function (event) {

                var $button = resultTable.getButtonByFeature('.save', feature);
                if ($button) {
                    $button.removeAttr("disabled");
                }

                frame.find(".resultTableControlButtons .save").removeAttr("disabled");

            });

            feature.on('Digitizer.UnmodifyFeature', function (event) {

                var $button = resultTable.getButtonByFeature('.save', feature);
                if ($button) {
                    $button.attr("disabled", "disabled");
                }

                var length = schema.layer.getSource().getFeatures().filter(function (feature) {
                    return ["isNew", "isChanged", "isCopy"].includes(feature.get("modificationState"));
                }).length;

                if (length === 0) {
                    frame.find(".resultTableControlButtons .save").attr("disabled", "disabled");
                }

            });

            feature.on('Digitizer.toggleVisibility', function (event) {
                var $button = resultTable.getButtonByFeature('.visibility', feature);
                if (!$button) {
                    return;
                }
                if (event.hide) {
                    $button.addClass('icon-eyeOn').removeClass('icon-eyeOff');
                    $button.attr('title', Mapbender.trans('mb.digitizer.feature.visibility.toggleon'));
                } else {
                    $button.addClass('icon-eyeOff').removeClass('icon-eyeOn');
                    $button.attr('title', Mapbender.trans('mb.digitizer.feature.visibility.toggleoff'));
                }
            });

        });

        schema.layer.getSource().on(ol.source.VectorEventType.REMOVEFEATURE, function (event) {
            resultTable.deleteRow(event.feature);
        });

    };

    Mapbender.Digitizer.Menu.prototype.generateResultDataTableButtons = function () {
        var menu = this;
        var schema = menu.schema;

        var buttons = {};

        if (schema.allowLocate) {
            buttons['locate'] = {
                title: Mapbender.trans('mb.digitizer.feature.zoomTo'),
                className: 'zoom',
                onClick: function (feature, ui) {
                    schema.zoomToFeature(feature);
                }
            };
        }

        if (schema.allowEditData && schema.allowSaveInResultTable) {
            buttons['save'] = {
                title: Mapbender.trans('mb.digitizer.feature.save.title'),
                className: 'save',
                disabled: true,
                onClick: function (feature, $button) {
                    schema.saveFeature(feature);
                }
            };
        }

        if (schema.allowEditData) {
            buttons['edit'] = {
                title: Mapbender.trans('mb.digitizer.feature.edit'),
                className: 'edit',
                onClick: function (feature, ui) {
                    schema.openFeatureEditDialog(feature);
                }
            };
        }
        if (schema.copy && schema.copy.enable) {
            buttons['copy'] = {
                title: Mapbender.trans('mb.digitizer.feature.clone.title'),
                className: 'copy',
                onClick: function (feature, ui) {
                    schema.copyFeature(feature);
                }
            };
        }
        if (schema.allowCustomStyle) {
            buttons['style'] = {
                title: Mapbender.trans('mb.digitizer.feature.style.change'),
                className: 'style',
                onClick: function (feature, ui) {
                    schema.openChangeStyleDialog(feature);
                }
            };
        }

        if (schema.allowChangeVisibility) {
            buttons['toggleVisibility'] = {
                title: Mapbender.trans('mb.digitizer.feature.visibility.toggleoff'),
                className: 'visibility',
                cssClass: 'icon-eyeOff',
                onClick: function (feature, $button) {
                    feature.dispatchEvent({type: 'Digitizer.toggleVisibility', hide: !feature.get("hidden")});
                }
            };
        }

        if (schema.allowDelete) {

            buttons['delete'] = {
                title: Mapbender.trans("mb.digitizer.feature.remove.title"),
                className: 'remove',
                cssClass: 'critical',
                onClick: function (feature, ui) {
                    if (schema.allowDelete) {
                        schema.removeFeature(feature);
                    } else {
                        $.notify("Deletion is not allowed");
                    }
                }
            };
        }

        return buttons;

    };

    Object.assign(Mapbender.Digitizer.Menu.prototype, {
        generateResultTable_: function (frame) {
            var menu = this;
            var schema = menu.schema;
            var widget = schema.widget;

            var resultTable;

            var generateResultDataTableColumns = function () {

                var columns = [];

                var createResultTableDataFunction = function (columnId, fieldSettings) {

                    return function (feature, type, val, meta) {

                        var escapeHtml = function (str) {

                            return str.replace(/["&'\/<>]/g, function (a) {
                                return {
                                    '"': '"',
                                    '&': '&',
                                    "'": ''',
                                    '/': '/',
                                    '<': '<',
                                    '>': '>'
                                }[a];
                            });
                        };

                        var data = feature.get('data') && feature.get('data').get(columnId);
                        if (typeof (data) == 'string') {
                            data = escapeHtml(data);
                        }
                        return data || '';
                    };
                };

                $.each(schema.tableFields, function (columnId, fieldSettings) {
                    fieldSettings.title = fieldSettings.label;
                    fieldSettings.data = fieldSettings.data || createResultTableDataFunction(columnId, fieldSettings);
                    columns.push(fieldSettings);
                });

                return columns;

            };

            var buttons = menu.generateResultDataTableButtons();

            var resultTableSettings = {
                lengthChange: false,
                pageLength: schema.pageLength,
                searching: schema.inlineSearch,
                info: true,
                processing: false,
                ordering: true,
                paging: true,
                selectable: false,
                autoWidth: false,
                columns: generateResultDataTableColumns(),
                buttons: buttons,
                oLanguage: widget.options.tableTranslation
            };

            var $div = $("
");
            var $table = $div.resultTable(resultTableSettings);

            resultTable = $table.resultTable("instance");

            // ??? function does not exist
            // resultTable.initializeColumnTitles();

            resultTable.element.delegate("tbody > tr", 'mouseenter', function () {
                var tr = this;
                var row = resultTable.getApi().row(tr);
                var feature = row.data();
                if (feature) {
                    feature.dispatchEvent({type: widget.TYPE + '.HoverFeature'});
                }

            });

            resultTable.element.delegate("tbody > tr", 'mouseleave', function () {
                var tr = this;
                var row = resultTable.getApi().row(tr);
                var feature = row.data();
                if (feature) {
                    feature.dispatchEvent({type: widget.TYPE + '.UnhoverFeature'});
                }
            });

            // menu.registerResultTableEvents(resultTable, frame);

            frame.append($table);
        }
    });

})();
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../../../../src/utils/Class');
var ComponentsAlpha = require('../../../../src/gameobjects/components/Alpha');
var ComponentsBlendMode = require('../../../../src/gameobjects/components/BlendMode');
var ComponentsDepth = require('../../../../src/gameobjects/components/Depth');
var ComponentsScrollFactor = require('../../../../src/gameobjects/components/ScrollFactor');
var ComponentsTransform = require('../../../../src/gameobjects/components/Transform');
var ComponentsVisible = require('../../../../src/gameobjects/components/Visible');
var GameObject = require('../../../../src/gameobjects/GameObject');
var SpineGameObjectRender = require('./SpineGameObjectRender');
var Matrix4 = require('../../../../src/math/Matrix4');

/**
 * @classdesc
 * TODO
 *
 * @class SpineGameObject
 * @constructor
 * @since 3.16.0
 *
 * @param {Phaser.Scene} scene - A reference to the Scene that has installed this plugin.
 * @param {Phaser.Plugins.PluginManager} pluginManager - A reference to the Phaser Plugin Manager.
 */
var SpineGameObject = new Class({

    Extends: GameObject,

    Mixins: [
        ComponentsAlpha,
        ComponentsBlendMode,
        ComponentsDepth,
        ComponentsScrollFactor,
        ComponentsTransform,
        ComponentsVisible,
        SpineGameObjectRender
    ],

    initialize:

    function SpineGameObject (scene, plugin, x, y, key, animationName, loop)
    {
        this.plugin = plugin;

        this.runtime = plugin.getRuntime();

        this.mvp = new Matrix4();

        GameObject.call(this, scene, 'Spine');

        var data = this.plugin.createSkeleton(key);

        this.skeletonData = data.skeletonData;

        var skeleton = data.skeleton;

        skeleton.flipY = (scene.sys.game.config.renderType === 1);

        skeleton.setToSetupPose();

        skeleton.updateWorldTransform();

        skeleton.setSkinByName('default');

        this.skeleton = skeleton;

        //  AnimationState
        data = this.plugin.createAnimationState(skeleton);

        this.state = data.state;

        this.stateData = data.stateData;

        var _this = this;

        this.state.addListener({
            event: function (trackIndex, event)
            {
                //  Event on a Track
                _this.emit('spine.event', trackIndex, event);
            },
            complete: function (trackIndex, loopCount)
            {
                //  Animation on Track x completed, loop count
                _this.emit('spine.complete', trackIndex, loopCount);
            },
            start: function (trackIndex)
            {
                //  Animation on Track x started
                _this.emit('spine.start', trackIndex);
            },
            end: function (trackIndex)
            {
                //  Animation on Track x ended
                _this.emit('spine.end', trackIndex);
            }
        });

        this.renderDebug = false;

        if (animationName)
        {
            this.setAnimation(0, animationName, loop);
        }

        this.setPosition(x, y);
    },

    // http://esotericsoftware.com/spine-runtimes-guide

    setAnimation: function (trackIndex, animationName, loop)
    {
        // if (loop === undefined)
        // {
        //     loop = false;
        // }

        this.state.setAnimation(trackIndex, animationName, loop);

        return this;
    },

    addAnimation: function (trackIndex, animationName, loop, delay)
    {
        return this.state.addAnimation(trackIndex, animationName, loop, delay);
    },

    setEmptyAnimation: function (trackIndex, mixDuration)
    {
        this.state.setEmptyAnimation(trackIndex, mixDuration);

        return this;
    },

    clearTrack: function (trackIndex)
    {
        this.state.clearTrack(trackIndex);

        return this;
    },

    clearTracks: function ()
    {
        this.state.clearTracks();

        return this;
    },

    setSkin: function (newSkin)
    {
        var skeleton = this.skeleton;

        skeleton.setSkin(newSkin);

        skeleton.setSlotsToSetupPose();

        this.state.apply(skeleton);

        return this;
    },

    setMix: function (fromName, toName, duration)
    {
        this.stateData.setMix(fromName, toName, duration);

        return this;
    },

    findBone: function (boneName)
    {
        return this.skeleton.findBone(boneName);
    },

    getBounds: function ()
    {
        return this.plugin.getBounds(this.skeleton);

        // this.skeleton.getBounds(this.offset, this.size, []);
    },

    preUpdate: function (time, delta)
    {
        this.state.update(delta / 1000);

        this.state.apply(this.skeleton);

        this.emit('spine.update', this.skeleton);
    },

    /**
     * Internal destroy handler, called as part of the destroy process.
     *
     * @method Phaser.GameObjects.RenderTexture#preDestroy
     * @protected
     * @since 3.16.0
     */
    preDestroy: function ()
    {
        this.state.clearListeners();
        this.state.clearListenerNotifications();

        this.plugin = null;
        this.runtime = null;
        this.skeleton = null;
        this.skeletonData = null;
        this.state = null;
        this.stateData = null;
    }

});

module.exports = SpineGameObject;
<commit_msg>Removed mvp as the plugin can use a single instance<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../../../../src/utils/Class');
var ComponentsAlpha = require('../../../../src/gameobjects/components/Alpha');
var ComponentsBlendMode = require('../../../../src/gameobjects/components/BlendMode');
var ComponentsDepth = require('../../../../src/gameobjects/components/Depth');
var ComponentsScrollFactor = require('../../../../src/gameobjects/components/ScrollFactor');
var ComponentsTransform = require('../../../../src/gameobjects/components/Transform');
var ComponentsVisible = require('../../../../src/gameobjects/components/Visible');
var GameObject = require('../../../../src/gameobjects/GameObject');
var SpineGameObjectRender = require('./SpineGameObjectRender');

/**
 * @classdesc
 * TODO
 *
 * @class SpineGameObject
 * @constructor
 * @since 3.16.0
 *
 * @param {Phaser.Scene} scene - A reference to the Scene that has installed this plugin.
 * @param {Phaser.Plugins.PluginManager} pluginManager - A reference to the Phaser Plugin Manager.
 */
var SpineGameObject = new Class({

    Extends: GameObject,

    Mixins: [
        ComponentsAlpha,
        ComponentsBlendMode,
        ComponentsDepth,
        ComponentsScrollFactor,
        ComponentsTransform,
        ComponentsVisible,
        SpineGameObjectRender
    ],

    initialize:

    function SpineGameObject (scene, plugin, x, y, key, animationName, loop)
    {
        this.plugin = plugin;

        this.runtime = plugin.getRuntime();

        GameObject.call(this, scene, 'Spine');

        this.drawDebug = false;

        var data = this.plugin.createSkeleton(key);

        this.skeletonData = data.skeletonData;

        var skeleton = data.skeleton;

        skeleton.flipY = (scene.sys.game.config.renderType === 1);

        skeleton.setToSetupPose();

        skeleton.updateWorldTransform();

        skeleton.setSkinByName('default');

        this.skeleton = skeleton;

        //  AnimationState
        data = this.plugin.createAnimationState(skeleton);

        this.state = data.state;

        this.stateData = data.stateData;

        var _this = this;

        this.state.addListener({
            event: function (trackIndex, event)
            {
                //  Event on a Track
                _this.emit('spine.event', trackIndex, event);
            },
            complete: function (trackIndex, loopCount)
            {
                //  Animation on Track x completed, loop count
                _this.emit('spine.complete', trackIndex, loopCount);
            },
            start: function (trackIndex)
            {
                //  Animation on Track x started
                _this.emit('spine.start', trackIndex);
            },
            end: function (trackIndex)
            {
                //  Animation on Track x ended
                _this.emit('spine.end', trackIndex);
            }
        });

        this.renderDebug = false;

        if (animationName)
        {
            this.setAnimation(0, animationName, loop);
        }

        this.setPosition(x, y);
    },

    // http://esotericsoftware.com/spine-runtimes-guide

    setAnimation: function (trackIndex, animationName, loop)
    {
        // if (loop === undefined)
        // {
        //     loop = false;
        // }

        this.state.setAnimation(trackIndex, animationName, loop);

        return this;
    },

    addAnimation: function (trackIndex, animationName, loop, delay)
    {
        return this.state.addAnimation(trackIndex, animationName, loop, delay);
    },

    setEmptyAnimation: function (trackIndex, mixDuration)
    {
        this.state.setEmptyAnimation(trackIndex, mixDuration);

        return this;
    },

    clearTrack: function (trackIndex)
    {
        this.state.clearTrack(trackIndex);

        return this;
    },

    clearTracks: function ()
    {
        this.state.clearTracks();

        return this;
    },

    setSkin: function (newSkin)
    {
        var skeleton = this.skeleton;

        skeleton.setSkin(newSkin);

        skeleton.setSlotsToSetupPose();

        this.state.apply(skeleton);

        return this;
    },

    setMix: function (fromName, toName, duration)
    {
        this.stateData.setMix(fromName, toName, duration);

        return this;
    },

    findBone: function (boneName)
    {
        return this.skeleton.findBone(boneName);
    },

    getBounds: function ()
    {
        return this.plugin.getBounds(this.skeleton);

        // this.skeleton.getBounds(this.offset, this.size, []);
    },

    preUpdate: function (time, delta)
    {
        this.state.update(delta / 1000);

        this.state.apply(this.skeleton);

        this.emit('spine.update', this.skeleton);
    },

    /**
     * Internal destroy handler, called as part of the destroy process.
     *
     * @method Phaser.GameObjects.RenderTexture#preDestroy
     * @protected
     * @since 3.16.0
     */
    preDestroy: function ()
    {
        this.state.clearListeners();
        this.state.clearListenerNotifications();

        this.plugin = null;
        this.runtime = null;
        this.skeleton = null;
        this.skeletonData = null;
        this.state = null;
        this.stateData = null;
    }

});

module.exports = SpineGameObject;
<|endoftext|>


<commit_before>foam.CLASS({
  package: 'foam.u2',
  name: 'DeleteModal',
  extends: 'foam.u2.View',

  documentation: 'View for deleting any object',

  imports: [
    'notify'
  ],

  css: `
    ^ {
      width: 25vw;
    }
    ^main {
      padding: 1vh 2vw 1.5vh 2vw;
    }
    ^ .buttons {
      background: /*%GREY5%*/ #fafafa;
      padding: 2vh;
      box-sizing: border-box;
      display: flex;
      justify-content: flex-end;
    }
    ^ .foam-u2-ActionView-delete,
    ^ .foam-u2-ActionView-delete:hover {
      border-radius: 4px;
      box-shadow: 0 1px 0 0 /*%GREY4%*/ rgba(22, 29, 37, 0.05);
      background: /*%DESTRUCTIVE2%*/ #f91c1c;
      color: white;
      vertical-align: middle;
    }
    ^ .foam-u2-ActionView-delete:hover {
      opacity: 0.9;
    }
    ^ .foam-u2-ActionView-cancel,
    ^ .foam-u2-ActionView-cancel:hover {
      background: none;
      color: /*%GREY1%*/ #525455;
      border: none;
      box-shadow: none;
    }
  `,

  messages: [
    { name: 'TITLE', message: 'Delete ' },
    { name: 'CONFIRM_DELETE_1', message: 'Are you sure you want to delete' },
    { name: 'SUCCESS_MSG', message: 'Successfully deleted' },
    { name: 'FAIL_MSG', message: 'Failed to delete' }
  ],

  properties: [
    'dao', 'onDelete', 'data'
  ],

  methods: [
    function initE() {
      this.SUPER();
      this
        .addClass(this.myClass())
        .start()
          .addClass(this.myClass('main'))
          .start('h2')
            .add(this.TITLE).add(this.data.cls_.name).add('?')
          .end()
          .start('p')
            .add(`${this.CONFIRM_DELETE_1} ${this.data.toSummary()}?`)
          .end()
        .end()
        .start()
          .addClass('buttons')
          .startContext({ data: this })
            .add(this.CANCEL)
            .add(this.DELETE)
          .endContext()
        .end();
    }
  ],

  actions: [
    {
      name: 'delete',
      label: 'Delete',
      code: function(X) {
        this.dao.remove(this.data).then((_) => {
          this.onDelete();
          this.notify(this.SUCCESS_MSG);
        }).catch((err) => {
          this.notify(err.message || this.FAIL_MSG, 'error');
        });
        X.closeDialog();
      }
    },
    {
      name: 'cancel',
      label: 'Cancel',
      code: function(X) {
        X.closeDialog();
      }
    }
  ]
});
<commit_msg>giving props types and ensuring user gets notified<commit_after>foam.CLASS({
  package: 'foam.u2',
  name: 'DeleteModal',
  extends: 'foam.u2.View',

  documentation: 'View for deleting any object',

  imports: [
    'notify'
  ],

  css: `
    ^ {
      width: 25vw;
    }
    ^main {
      padding: 1vh 2vw 1.5vh 2vw;
    }
    ^ .buttons {
      background: /*%GREY5%*/ #fafafa;
      padding: 2vh;
      box-sizing: border-box;
      display: flex;
      justify-content: flex-end;
    }
    ^ .foam-u2-ActionView-delete,
    ^ .foam-u2-ActionView-delete:hover {
      border-radius: 4px;
      box-shadow: 0 1px 0 0 /*%GREY4%*/ rgba(22, 29, 37, 0.05);
      background: /*%DESTRUCTIVE2%*/ #f91c1c;
      color: white;
      vertical-align: middle;
    }
    ^ .foam-u2-ActionView-delete:hover {
      opacity: 0.9;
    }
    ^ .foam-u2-ActionView-cancel,
    ^ .foam-u2-ActionView-cancel:hover {
      background: none;
      color: /*%GREY1%*/ #525455;
      border: none;
      box-shadow: none;
    }
  `,

  messages: [
    { name: 'TITLE', message: 'Delete ' },
    { name: 'CONFIRM_DELETE_1', message: 'Are you sure you want to delete' },
    { name: 'SUCCESS_MSG', message: 'Successfully deleted' },
    { name: 'FAIL_MSG', message: 'Failed to delete' }
  ],

  properties: [
    {
      class: 'foam.dao.DAOProperty',
      name: 'dao'
    },
    {
      class: 'Function',
      name: 'onDelete',
      value: () => {}
    },
    {
      class: 'FObject',
      name: 'data'
    }
  ],

  methods: [
    function initE() {
      this.SUPER();
      this
        .addClass(this.myClass())
        .start()
          .addClass(this.myClass('main'))
          .start('h2')
            .add(this.TITLE).add(this.data.cls_.name).add('?')
          .end()
          .start('p')
            .add(`${this.CONFIRM_DELETE_1} ${this.data.toSummary()}?`)
          .end()
        .end()
        .start()
          .addClass('buttons')
          .startContext({ data: this })
            .add(this.CANCEL)
            .add(this.DELETE)
          .endContext()
        .end();
    }
  ],

  actions: [
    {
      name: 'delete',
      label: 'Delete',
      code: function(X) {
        this.dao.remove(this.data).then((_) => {
          this.notify(this.SUCCESS_MSG);
          this.onDelete();
        }).catch((err) => {
          this.notify(err.message || this.FAIL_MSG, 'error');
        });
        X.closeDialog();
      }
    },
    {
      name: 'cancel',
      label: 'Cancel',
      code: function(X) {
        X.closeDialog();
      }
    }
  ]
});
<|endoftext|>


<commit_before>var assert = require("assert");
var path = require("path");
var promisify = require("promisify-node");
var Promise = require("nodegit-promise");
var fse = promisify(require("fs-extra"));
var local = path.join.bind(path, __dirname);

describe("Repository", function() {
  var NodeGit = require("../../");
  var Repository = NodeGit.Repository;
  var Index = NodeGit.Index;
  var Signature = NodeGit.Signature;

  var reposPath = local("../repos/workdir");
  var newRepo = local("../repos/newrepo");

  beforeEach(function() {
    var test = this;

    return Repository.open(reposPath)
      .then(function(repository) {
        test.repository = repository;
      });
  });

  it("can open a valid repository", function() {
    assert.ok(this.repository instanceof Repository);
  });

  it("cannot open an invalid repository", function() {
    return Repository.open("repos/nonrepo")
      .then(null, function(err) {
        assert.ok(err instanceof Error);
      });
  });

  it("does not try to open paths that don't exist", function() {
    var missingPath = "/surely/this/directory/does/not/exist/on/this/machine";

    return Repository.open(missingPath)
      .then(null, function(err) {
        assert.ok(err instanceof Error);
      });
  });

  it("can initialize a repository into a folder", function() {
    return Repository.init(newRepo, 1)
      .then(function(path, isBare) {
        return Repository.open(newRepo);
      });
  });

  it("can utilize repository init options", function() {
    return fse.remove(newRepo)
      .then(function() {
        return Repository.initExt(newRepo, {
          flags: Repository.INIT_FLAG.MKPATH
        });
      });
  });

  it("can read the index", function() {
    return this.repository.index()
      .then(function(index) {
        assert.ok(index instanceof Index);
      });
  });

  it("can list remotes", function() {
    return this.repository.getRemotes()
      .then(function(remotes) {
        assert.equal(remotes.length, 1);
        assert.equal(remotes[0], "origin");
      });
  });

  it("can get the current branch", function() {
    return this.repository.getCurrentBranch()
      .then(function(branch) {
        assert.equal(branch.shorthand(), "master");
      });
  });

  it("can get the default signature", function() {
    var sig = this.repository.defaultSignature();

    assert(sig instanceof Signature);
  });

  it("gets statuses with StatusFile", function() {
    var fileName = "my-new-file-that-shouldnt-exist.file";
    var fileContent = "new file from repository test";
    var repo = this.repository;
    var filePath = path.join(repo.workdir(), fileName);

    return fse.writeFile(filePath, fileContent)
      .then(function() {
        return repo.getStatus().then(function(statuses) {
          assert.equal(statuses.length, 1);
          assert.equal(statuses[0].path(), fileName);
          assert.ok(statuses[0].isNew());
        });
      })
      .then(function() {
        return fse.remove(filePath);
      })
      .catch(function (e) {
        return fse.remove(filePath)
          .then(function() {
            return Promise.reject(e);
          });
      });
  });

  it("gets extended statuses", function() {
    var fileName = "my-new-file-that-shouldnt-exist.file";
    var fileContent = "new file from repository test";
    var repo = this.repository;
    var filePath = path.join(repo.workdir(), fileName);

    return fse.writeFile(filePath, fileContent)
      .then(function() {
        var statuses = repo.getStatusExt();

        assert.equal(statuses.length, 1);
        assert.equal(statuses[0].path(), fileName);
        assert.equal(statuses[0].indexToWorkdir().newFile().path(), fileName);
        assert.ok(statuses[0].isNew());
      })
      .then(function() {
        return fse.remove(filePath);
      })
      .catch(function (e) {
        return fse.remove(filePath)
          .then(function() {
            return Promise.reject(e);
          });
      });
  });

  it("gets fetch-heads", function() {
    var repo = this.repository;
    var foundMaster;

    return repo.fetch("origin", {
      credentials: function(url, userName) {
        return NodeGit.Cred.sshKeyFromAgent(userName);
      },
      certificateCheck: function() {
        return 1;
      }
    })
    .then(function() {
      return repo.fetchheadForeach(function(refname, remoteUrl, oid, isMerge) {
        if (refname == "refs/heads/master") {
          foundMaster = true;
          assert.equal(refname, "refs/heads/master");
          assert.equal(remoteUrl, "https://github.com/nodegit/test");
          assert.equal(
            oid.toString(),
            "32789a79e71fbc9e04d3eff7425e1771eb595150");
          assert.equal(isMerge, 1);
        }
      });
    })
    .then(function() {
      if (!foundMaster) {
        throw new Error("Couldn't find master in iteration of fetch heads");
      }
    });
  });

  it("can discover if a path is part of a repository", function() {
    var testPath = path.join(reposPath, "lib", "util", "normalize_oid.js");
    var expectedPath = path.join(reposPath, ".git");
    return NodeGit.Repository.discover(testPath, 0, "")
      .then(function(foundPath) {
        assert.equal(expectedPath, foundPath);
      });
  });

  it("can create a repo using initExt", function() {
    var initFlags = NodeGit.Repository.INIT_FLAG.NO_REINIT |
      NodeGit.Repository.INIT_FLAG.MKPATH |
      NodeGit.Repository.INIT_FLAG.MKDIR;
    return NodeGit.Repository.initExt(newRepo, { flags: initFlags })
      .then(function() {
        return NodeGit.Repository.open(newRepo);
      });
  });
});
<commit_msg>Fixed newest repository test<commit_after>var assert = require("assert");
var path = require("path");
var promisify = require("promisify-node");
var Promise = require("nodegit-promise");
var fse = promisify(require("fs-extra"));
var local = path.join.bind(path, __dirname);

describe("Repository", function() {
  var NodeGit = require("../../");
  var Repository = NodeGit.Repository;
  var Index = NodeGit.Index;
  var Signature = NodeGit.Signature;

  var reposPath = local("../repos/workdir");
  var newRepo = local("../repos/newrepo");

  beforeEach(function() {
    var test = this;

    return Repository.open(reposPath)
      .then(function(repository) {
        test.repository = repository;
      });
  });

  it("can open a valid repository", function() {
    assert.ok(this.repository instanceof Repository);
  });

  it("cannot open an invalid repository", function() {
    return Repository.open("repos/nonrepo")
      .then(null, function(err) {
        assert.ok(err instanceof Error);
      });
  });

  it("does not try to open paths that don't exist", function() {
    var missingPath = "/surely/this/directory/does/not/exist/on/this/machine";

    return Repository.open(missingPath)
      .then(null, function(err) {
        assert.ok(err instanceof Error);
      });
  });

  it("can initialize a repository into a folder", function() {
    return Repository.init(newRepo, 1)
      .then(function(path, isBare) {
        return Repository.open(newRepo);
      });
  });

  it("can utilize repository init options", function() {
    return fse.remove(newRepo)
      .then(function() {
        return Repository.initExt(newRepo, {
          flags: Repository.INIT_FLAG.MKPATH
        });
      });
  });

  it("can read the index", function() {
    return this.repository.index()
      .then(function(index) {
        assert.ok(index instanceof Index);
      });
  });

  it("can list remotes", function() {
    return this.repository.getRemotes()
      .then(function(remotes) {
        assert.equal(remotes.length, 1);
        assert.equal(remotes[0], "origin");
      });
  });

  it("can get the current branch", function() {
    return this.repository.getCurrentBranch()
      .then(function(branch) {
        assert.equal(branch.shorthand(), "master");
      });
  });

  it("can get the default signature", function() {
    var sig = this.repository.defaultSignature();

    assert(sig instanceof Signature);
  });

  it("gets statuses with StatusFile", function() {
    var fileName = "my-new-file-that-shouldnt-exist.file";
    var fileContent = "new file from repository test";
    var repo = this.repository;
    var filePath = path.join(repo.workdir(), fileName);

    return fse.writeFile(filePath, fileContent)
      .then(function() {
        return repo.getStatus().then(function(statuses) {
          assert.equal(statuses.length, 1);
          assert.equal(statuses[0].path(), fileName);
          assert.ok(statuses[0].isNew());
        });
      })
      .then(function() {
        return fse.remove(filePath);
      })
      .catch(function (e) {
        return fse.remove(filePath)
          .then(function() {
            return Promise.reject(e);
          });
      });
  });

  it("gets extended statuses", function() {
    var fileName = "my-new-file-that-shouldnt-exist.file";
    var fileContent = "new file from repository test";
    var repo = this.repository;
    var filePath = path.join(repo.workdir(), fileName);

    return fse.writeFile(filePath, fileContent)
      .then(function() {
        var statuses = repo.getStatusExt();

        assert.equal(statuses.length, 1);
        assert.equal(statuses[0].path(), fileName);
        assert.equal(statuses[0].indexToWorkdir().newFile().path(), fileName);
        assert.ok(statuses[0].isNew());
      })
      .then(function() {
        return fse.remove(filePath);
      })
      .catch(function (e) {
        return fse.remove(filePath)
          .then(function() {
            return Promise.reject(e);
          });
      });
  });

  it("gets fetch-heads", function() {
    var repo = this.repository;
    var foundMaster;

    return repo.fetch("origin", {
      credentials: function(url, userName) {
        return NodeGit.Cred.sshKeyFromAgent(userName);
      },
      certificateCheck: function() {
        return 1;
      }
    })
    .then(function() {
      return repo.fetchheadForeach(function(refname, remoteUrl, oid, isMerge) {
        if (refname == "refs/heads/master") {
          foundMaster = true;
          assert.equal(refname, "refs/heads/master");
          assert.equal(remoteUrl, "https://github.com/nodegit/test");
          assert.equal(
            oid.toString(),
            "32789a79e71fbc9e04d3eff7425e1771eb595150");
          assert.equal(isMerge, 1);
        }
      });
    })
    .then(function() {
      if (!foundMaster) {
        throw new Error("Couldn't find master in iteration of fetch heads");
      }
    });
  });

  it("can discover if a path is part of a repository", function() {
    var testPath = path.join(reposPath, "lib", "util", "normalize_oid.js");
    var expectedPath = path.join(reposPath, ".git");
    return NodeGit.Repository.discover(testPath, 0, "")
      .then(function(foundPath) {
        assert.equal(expectedPath, foundPath);
      });
  });

  it("can create a repo using initExt", function() {
    var initFlags = NodeGit.Repository.INIT_FLAG.NO_REINIT |
      NodeGit.Repository.INIT_FLAG.MKPATH |
      NodeGit.Repository.INIT_FLAG.MKDIR;
    return fse.remove(newRepo)
      .then(function() {
        return NodeGit.Repository.initExt(newRepo, { flags: initFlags });
      })
      .then(function() {
        return NodeGit.Repository.open(newRepo);
      });
  });
});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try<commit_msg>Five bullets or six?<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try <|endoftext|>