<commit_before>goog.provide('atd.json');

/**
 * Produce a JSON diff between two javascript objects that conforms to the
 * RFC9602 specification.
 *
 * @param {*} orig The data in its original state.
 * @param {*} update The data in its modified state.
 * @param {string=} opt_parentPath The parent path, used for recursive calls.
 *
 * @return {Array.<Object>}
 */
atd.json.diff = function(orig, update, opt_parentPath) {
  var parentPath = opt_parentPath ? opt_parentPath : '';
  var patch = new Array();

  var patchEntry = {};

  if (Array.isArray(orig) && Array.isArray(update)) {
    patch = patch.concat(atd.json.diffArray_(orig, update,
      parentPath));
  } else if (orig !== null && typeof orig === 'object' &&
    update !== null && typeof update === 'object') {

    patch = patch.concat(atd.json.diffObject_(orig, update, parentPath));

  } else {
    if (orig === update) {
      return patch;
    } else if (orig == null || !atd.isDef(orig)) {

      patchEntry['op'] = 'add';
      patchEntry['path'] = parentPath;
      patchEntry['value'] = update;
      patch.push(patchEntry);

    } else if (update == null || !atd.isDef(update)) {
      patchEntry['op'] = 'remove';
      patchEntry['path'] = parentPath;
      patch.push(patchEntry);
    } else {
      // var origType = typeof orig;
      // var updType = typeof update;
      // if (origType !== updType && (
      //     (origType === 'object' || Array.isArray(orig)) ||
      //     (updType === 'object' || Array.isArray(update)))) {
      //   patch = patch.concat(atd.json.diff(orig, null, parentPath));
      //   patch = patch.concat(atd.json.diff(null, update, parentPath));
      // } else {
        patchEntry['op'] = 'replace';
        patchEntry['path'] = parentPath;
        patchEntry['value'] = update;
        patch.push(patchEntry);
      // }
    }
  }

  return patch;
};

/**
 * Perform a diff on an Object.
 *
 * @param {Object} orig The Object in its original state.
 * @param {Object} update The Object in its updated state.
 * @param {string=} opt_parentPath The parent path, used for recursive calls.
 *
 * @return {Array.<Object>}
 * @private
 */
atd.json.diffObject_ = function(orig, update, opt_parentPath) {
  var patch = new Array();
  if (update) {
    for (k in update) {

        if (!update.hasOwnProperty(k)) {
          continue;
        }
        var ov = orig ? orig[k] : null;
        var uv = update[k];

        patch = patch.concat(atd.json.diff(ov, uv,
          opt_parentPath + '/' + k));
    }
  }
  if (orig) {
    for (k in orig) {
      if (!orig.hasOwnProperty(k) || update[k]) {
        continue;
      }
      var ov = orig[k];
      patch = patch.concat(atd.json.diff(ov, null,
        opt_parentPath + '/' + k));
    }
  }
  return patch;
};

/**
 * Perform a diff on an array. The performance of this method is likely
 * to be less than optimal.
 *
 * @param {Array} origArray The Array in its original state.
 * @param {Array} updateArray The Array in its updated state.
 * @param {string=} opt_parentPath The parent path, used for recursive calls.
 *
 * @return {Array.<Object>}
 * @private
 */
atd.json.diffArray_ = function(origArray, updateArray, opt_parentPath) {
  var patch = new Array();
  var origLength = origArray.length;
  var updateLength = updateArray.length;

  var origLocLookup = new Array();
  var newLocLookup = new Array();
  for (var i = 0; i < origLength; i++) {
    var newIdx = atd.json.findInArray_(origArray[i], updateArray);
    if (newIdx !== -1) {
      origLocLookup[newIdx] = i;
      newLocLookup[i] = newIdx;
    }
  }

  var currState = new Array();
  for (var i = 0; i < origArray.length; i++) {
    currState[i] = i;
  }
  currState.getCurrLoc = function(origLoc) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === origLoc) {
        return i;
      }
    }
    return -1;
  };

  var delCount = 0;
  for (var i = 0; i < origLength; i++) {
    var newLoc = newLocLookup[i];
    if (!atd.isDef(newLoc)) {
      if (!(atd.isDef(updateArray[i]) && !atd.isDef(origLocLookup[i]))) {
        //remove the element
        patch = patch.concat(atd.json.diff(origArray[i], null,
            opt_parentPath + '/' + i));
        currState.splice(i - delCount, 1);
      }
    }
  }

  for (var i = 0; i < updateLength; i++) {
    var origLoc = origLocLookup[i];
    var newLoc = newLocLookup[origLoc];
    if (atd.isDef(origLoc)) {
      var currLoc = currState.getCurrLoc(origLoc);
      if (currLoc == i) {
        continue;
      }
      var patchEntry = {};
      patchEntry['op'] = 'move';
      patchEntry['from'] = opt_parentPath + '/' + currLoc;
      patchEntry['to'] = opt_parentPath + '/' + i;
      patch.push(patchEntry);

      currState.splice(currLoc, 1);
      currState.splice(i, 0, origLoc);
    } else {
      if (origArray[i] && !atd.isDef(newLocLookup[i])) {
        continue;
      } else {
        //add the element
        patch = patch.concat(atd.json.diff(null, updateArray[i],
            opt_parentPath + '/' + i));
        currState.splice(i, 0, 'added');
      }
    }
  }

  for (var i = 0; i < origLength; i++) {
    var newLoc = newLocLookup[i];
    if (!atd.isDef(newLoc)) {
      if (atd.isDef(updateArray[i]) && !atd.isDef(origLocLookup[i])) {
        // there's an element at the same index in the updated arr
        // and the updated element is not an element that was moved.
        // Update the element at i
        patch = patch.concat(atd.json.diff(origArray[i], updateArray[i],
            opt_parentPath + '/' + i));
      }
    }
  }

  return patch;
};

/**
 * get the index of a value in an array
 *
 * @param {*} val the value to search for.
 * @param {Array} array the array to search in.
 * @param {number=} opt_start the index to start at
 *
 * @return {number}
 * @private
 */
atd.json.findInArray_ = function(val, array, opt_start) {
  var start = opt_start ? opt_start : 0;
  for (var i = start; i < array.length; i++) {
    if (atd.json.subtreesEqual_(val, array[i])) {
      return i;
    }
  }
  return -1;
};

/**
 * Compare two subtrees.
 * @param {*} valOne First value.
 * @param {*} valTwo Second Value.
 * @return {boolean}
 * @private
 */
atd.json.subtreesEqual_ = function(valOne, valTwo) {
  if (valOne !== null && typeof valOne === 'object' &&
    valTwo !== null && typeof valTwo === 'object') {
    var keysone = Object.keys(valOne);
    var keystwo = Object.keys(valTwo);
    if (keysone.length !== keystwo.length) {
      return false;
    }
    for (var i = 0; i < keysone.length; i++) {
      var k = keysone[i];
      if (!atd.json.subtreesEqual_(valOne[k], valTwo[k])) {
        return false;
      }
    }
    return true;
  } else if (Array.isArray(valOne) && Array.isArray(valTwo)) {
    if (valOne.length !== valTwo.length) {
      return false;
    }
    for (var i = 0; i < valOne.length; i++) {
      if (!atd.json.subtreesEqual_(valOne[i], valTwo[i])) {
        return false;
      }
    }
    return true;
  }
  return valOne === valTwo;
};

/**
 * Copied from the closure library.  goog.isDef.  Copyright the closure authors.
 *
 * Returns true if the specified value is not undefined.
 * WARNING: Do not use this to test if an object has a property. Use the in
 * operator instead.
 *
 * @param {?} val Variable to test.
 * @return {boolean} Whether variable is defined.
 */
atd.isDef = function(val) {
  // void 0 always evaluates to undefined and hence we do not need to depend on
  // the definition of the global variable named 'undefined'.
  return val !== void 0;
};
<commit_msg>removed commented out code<commit_after>goog.provide('atd.json');

/**
 * Produce a JSON diff between two javascript objects that conforms to the
 * RFC9602 specification.
 *
 * @param {*} orig The data in its original state.
 * @param {*} update The data in its modified state.
 * @param {string=} opt_parentPath The parent path, used for recursive calls.
 *
 * @return {Array.<Object>}
 */
atd.json.diff = function(orig, update, opt_parentPath) {
  var parentPath = opt_parentPath ? opt_parentPath : '';
  var patch = new Array();

  var patchEntry = {};

  if (Array.isArray(orig) && Array.isArray(update)) {
    patch = patch.concat(atd.json.diffArray_(orig, update,
      parentPath));
  } else if (orig !== null && typeof orig === 'object' &&
    update !== null && typeof update === 'object') {

    patch = patch.concat(atd.json.diffObject_(orig, update, parentPath));

  } else {
    if (orig === update) {
      return patch;
    } else if (orig == null || !atd.isDef(orig)) {

      patchEntry['op'] = 'add';
      patchEntry['path'] = parentPath;
      patchEntry['value'] = update;
      patch.push(patchEntry);

    } else if (update == null || !atd.isDef(update)) {
      patchEntry['op'] = 'remove';
      patchEntry['path'] = parentPath;
      patch.push(patchEntry);
    } else {
      patchEntry['op'] = 'replace';
      patchEntry['path'] = parentPath;
      patchEntry['value'] = update;
      patch.push(patchEntry);
    }
  }

  return patch;
};

/**
 * Perform a diff on an Object.
 *
 * @param {Object} orig The Object in its original state.
 * @param {Object} update The Object in its updated state.
 * @param {string=} opt_parentPath The parent path, used for recursive calls.
 *
 * @return {Array.<Object>}
 * @private
 */
atd.json.diffObject_ = function(orig, update, opt_parentPath) {
  var patch = new Array();
  if (update) {
    for (k in update) {

        if (!update.hasOwnProperty(k)) {
          continue;
        }
        var ov = orig ? orig[k] : null;
        var uv = update[k];

        patch = patch.concat(atd.json.diff(ov, uv,
          opt_parentPath + '/' + k));
    }
  }
  if (orig) {
    for (k in orig) {
      if (!orig.hasOwnProperty(k) || update[k]) {
        continue;
      }
      var ov = orig[k];
      patch = patch.concat(atd.json.diff(ov, null,
        opt_parentPath + '/' + k));
    }
  }
  return patch;
};

/**
 * Perform a diff on an array. The performance of this method is likely
 * to be less than optimal.
 *
 * @param {Array} origArray The Array in its original state.
 * @param {Array} updateArray The Array in its updated state.
 * @param {string=} opt_parentPath The parent path, used for recursive calls.
 *
 * @return {Array.<Object>}
 * @private
 */
atd.json.diffArray_ = function(origArray, updateArray, opt_parentPath) {
  var patch = new Array();
  var origLength = origArray.length;
  var updateLength = updateArray.length;

  var origLocLookup = new Array();
  var newLocLookup = new Array();
  for (var i = 0; i < origLength; i++) {
    var newIdx = atd.json.findInArray_(origArray[i], updateArray);
    if (newIdx !== -1) {
      origLocLookup[newIdx] = i;
      newLocLookup[i] = newIdx;
    }
  }

  var currState = new Array();
  for (var i = 0; i < origArray.length; i++) {
    currState[i] = i;
  }
  currState.getCurrLoc = function(origLoc) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === origLoc) {
        return i;
      }
    }
    return -1;
  };

  var delCount = 0;
  for (var i = 0; i < origLength; i++) {
    var newLoc = newLocLookup[i];
    if (!atd.isDef(newLoc)) {
      if (!(atd.isDef(updateArray[i]) && !atd.isDef(origLocLookup[i]))) {
        //remove the element
        patch = patch.concat(atd.json.diff(origArray[i], null,
            opt_parentPath + '/' + i));
        currState.splice(i - delCount, 1);
      }
    }
  }

  for (var i = 0; i < updateLength; i++) {
    var origLoc = origLocLookup[i];
    var newLoc = newLocLookup[origLoc];
    if (atd.isDef(origLoc)) {
      var currLoc = currState.getCurrLoc(origLoc);
      if (currLoc == i) {
        continue;
      }
      var patchEntry = {};
      patchEntry['op'] = 'move';
      patchEntry['from'] = opt_parentPath + '/' + currLoc;
      patchEntry['to'] = opt_parentPath + '/' + i;
      patch.push(patchEntry);

      currState.splice(currLoc, 1);
      currState.splice(i, 0, origLoc);
    } else {
      if (origArray[i] && !atd.isDef(newLocLookup[i])) {
        continue;
      } else {
        //add the element
        patch = patch.concat(atd.json.diff(null, updateArray[i],
            opt_parentPath + '/' + i));
        currState.splice(i, 0, 'added');
      }
    }
  }

  for (var i = 0; i < origLength; i++) {
    var newLoc = newLocLookup[i];
    if (!atd.isDef(newLoc)) {
      if (atd.isDef(updateArray[i]) && !atd.isDef(origLocLookup[i])) {
        // there's an element at the same index in the updated arr
        // and the updated element is not an element that was moved.
        // Update the element at i
        patch = patch.concat(atd.json.diff(origArray[i], updateArray[i],
            opt_parentPath + '/' + i));
      }
    }
  }

  return patch;
};

/**
 * get the index of a value in an array
 *
 * @param {*} val the value to search for.
 * @param {Array} array the array to search in.
 * @param {number=} opt_start the index to start at
 *
 * @return {number}
 * @private
 */
atd.json.findInArray_ = function(val, array, opt_start) {
  var start = opt_start ? opt_start : 0;
  for (var i = start; i < array.length; i++) {
    if (atd.json.subtreesEqual_(val, array[i])) {
      return i;
    }
  }
  return -1;
};

/**
 * Compare two subtrees.
 * @param {*} valOne First value.
 * @param {*} valTwo Second Value.
 * @return {boolean}
 * @private
 */
atd.json.subtreesEqual_ = function(valOne, valTwo) {
  if (valOne !== null && typeof valOne === 'object' &&
    valTwo !== null && typeof valTwo === 'object') {
    var keysone = Object.keys(valOne);
    var keystwo = Object.keys(valTwo);
    if (keysone.length !== keystwo.length) {
      return false;
    }
    for (var i = 0; i < keysone.length; i++) {
      var k = keysone[i];
      if (!atd.json.subtreesEqual_(valOne[k], valTwo[k])) {
        return false;
      }
    }
    return true;
  } else if (Array.isArray(valOne) && Array.isArray(valTwo)) {
    if (valOne.length !== valTwo.length) {
      return false;
    }
    for (var i = 0; i < valOne.length; i++) {
      if (!atd.json.subtreesEqual_(valOne[i], valTwo[i])) {
        return false;
      }
    }
    return true;
  }

  return valOne === valTwo;
};

/**
 * Copied from the closure library.  goog.isDef.  Copyright the closure authors.
 *
 * Returns true if the specified value is not undefined.
 * WARNING: Do not use this to test if an object has a property. Use the in
 * operator instead.
 *
 * @param {?} val Variable to test.
 * @return {boolean} Whether variable is defined.
 */
atd.isDef = function(val) {
  // void 0 always evaluates to undefined and hence we do not need to depend on
  // the definition of the global variable named 'undefined'.
  return val !== void 0;
};
<|endoftext|>


<commit_before>window.onload = function () {
  "use strict";

  var group = window.location.hash.slice(1);
  var container;
  //var BASEURL = "http://192.168.178.75:8080";
  var BASEURL = "..";

  function eid(id) {
    return document.getElementById(id);
  }

  function ajax(url, data, cb) {
    var xhr = new window.XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onload = function () { cb(JSON.parse(this.responseText)); };
    xhr.send(JSON.stringify(data));
  }

  function upload(postUrl, fieldName, file, cb) {
    var formData = new FormData();
    formData.append(fieldName, file);

    var req = new XMLHttpRequest();
    req.open("POST", postUrl);
    req.onload = function() { cb(JSON.parse(this.responseText)); };
    req.send(formData);
  }

  function html(e, t) {
    e.innerHTML = t;
    return e;
  }

  function activate (e) {
    var contents = document.getElementsByClassName("content");
    for (var i = 0; i < contents.length; ++i) {
      contents[i].style.display = "none";
    }
    e.style.display = "flex";
  }

  function ask(code) {
    ajax(BASEURL + "/q/" + group, code, function (q) {
      if (q.status === "ok") {
        if (q.done) {
          challangePageDone.set();
          challangePageDone.text(q);
        } else {
          challangePage.set();
          challangePage.text(q);
        }
      } else {
        queryPage.set();
      }
    });
  }

  function solve(file, code) {
    var url = [BASEURL, "q", group, code, "file"].join('/');
    upload(url, "file", file, function (q) {
      challangePageDone.set();
      challangePageDone.text(q);
    });
  }

  var queryPage = (function () {
    var div = eid("query");
    var input = eid("qcode");
    var button = eid("qbutton");
    button.onclick = function () { ask({code: input.value}); };
    return {
      set: function () { activate(div); }
    };
  })();

  var challangePage = (function () {
    var div = eid("challange");
    var description = eid("cdesc");
    var file = eid("cfile");
    var button = eid("cbutton");
    var back = eid("cback");
    back.onclick = function () {
      queryPage.set();
    };

    function init (level) {
      html(description, level.desc);
      var code = level.code;
      button.onclick = function () {
        solve(file.files[0], code);
      }
    }
    return {
      text:  function (q) { init(q); }
      , set: function () { activate(div); }
    };
  })();

  var challangePageDone = (function () {
    var div = eid("challangeDone");
    var description = eid("ddesc");
    var next = eid("dnext");
    var back = eid("dback");
    back.onclick = function () {
      queryPage.set();
    };

    function init (level) {
      html(description, level.desc);
      html(next, level.next);
    }
    return {
      text:  function (q) { init(q); }
      , set: function () { activate(div); }
    };
  })();

  queryPage.set();
};
<commit_msg>cleanup local ip<commit_after>window.onload = function () {
  "use strict";

  var group = window.location.hash.slice(1);
  var BASEURL = "..";

  function eid(id) {
    return document.getElementById(id);
  }

  function ajax(url, data, cb) {
    var xhr = new window.XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onload = function () { cb(JSON.parse(this.responseText)); };
    xhr.send(JSON.stringify(data));
  }

  function upload(postUrl, fieldName, file, cb) {
    var formData = new FormData();
    formData.append(fieldName, file);

    var req = new XMLHttpRequest();
    req.open("POST", postUrl);
    req.onload = function() { cb(JSON.parse(this.responseText)); };
    req.send(formData);
  }

  function html(e, t) {
    e.innerHTML = t;
    return e;
  }

  function activate (e) {
    var contents = document.getElementsByClassName("content");
    for (var i = 0; i < contents.length; ++i) {
      contents[i].style.display = "none";
    }
    e.style.display = "flex";
  }

  function ask(code) {
    ajax(BASEURL + "/q/" + group, code, function (q) {
      if (q.status === "ok") {
        if (q.done) {
          challangePageDone.set();
          challangePageDone.text(q);
        } else {
          challangePage.set();
          challangePage.text(q);
        }
      } else {
        queryPage.set();
      }
    });
  }

  function solve(file, code) {
    var url = [BASEURL, "q", group, code, "file"].join('/');
    upload(url, "file", file, function (q) {
      challangePageDone.set();
      challangePageDone.text(q);
    });
  }

  var queryPage = (function () {
    var div = eid("query");
    var input = eid("qcode");
    var button = eid("qbutton");
    button.onclick = function () { ask({code: input.value}); };
    return {
      set: function () { activate(div); }
    };
  })();

  var challangePage = (function () {
    var div = eid("challange");
    var description = eid("cdesc");
    var file = eid("cfile");
    var button = eid("cbutton");
    var back = eid("cback");
    back.onclick = function () {
      queryPage.set();
    };

    function init (level) {
      html(description, level.desc);
      var code = level.code;
      button.onclick = function () {
        solve(file.files[0], code);
      }
    }
    return {
      text:  function (q) { init(q); }
      , set: function () { activate(div); }
    };
  })();

  var challangePageDone = (function () {
    var div = eid("challangeDone");
    var description = eid("ddesc");
    var next = eid("dnext");
    var back = eid("dback");
    back.onclick = function () {
      queryPage.set();
    };

    function init (level) {
      html(description, level.desc);
      html(next, level.next);
    }
    return {
      text:  function (q) { init(q); }
      , set: function () { activate(div); }
    };
  })();

  queryPage.set();
};
<|endoftext|>


<commit_before>const config = {}

const instanceMap = {}

export function init (cfg) {
  config.Document = cfg.Document
  config.Element = cfg.Element
  config.Comment = cfg.Comment
  config.sendTasks = cfg.sendTasks
}

export function registerComponents (components) {}

export function registerModules (modules) {}

export function registerMethods (apis) {}

export function prepareInstance (id, options, data) {}

export function createInstance (id, code, options, data) {
  const document = new config.Document(id, options.bundleUrl)
  const callbacks = {};
  let lastCallbackId = 0;
  document.addCallback = func => {
    lastCallbackId++
    callbacks[lastCallbackId] = func
    return lastCallbackId
  }
  document.handleCallback = (funcId, data, ifLast) => {
    const callback = callbacks[funcId]
    if (ifLast) {
      delete callbacks[funcId]
    }
    return callback(data)
  }
  instanceMap[id] = document
  const result = new Function(
    'Document',
    'Element',
    'Comment',
    'sendTasks',
    'id',
    'options',
    'data',
    'document',
    code
  )
  return result(
    config.Document,
    config.Element,
    config.Comment,
    config.sendTasks,
    id,
    options,
    data,
    document
  )
}

export function refreshInstance (id, data) {}

export function destroyInstance (id) {
  delete instanceMap[id];
}

export function getRoot (id) {
  return instanceMap[id].body.toJSON();
}

export function receiveTasks (id, tasks) {
  const jsHandlers = {
    fireEvent: (id, ref, type, data, domChanges) => {
      const document = instanceMap[id]
      const el = document.getRef(ref)
      return document.fireEvent(el, type, data, domChanges)
    },

    callback: (id, funcId, data, ifLast) => {
      const document = instanceMap[id]
      return document.handleCallback(funcId, data, ifLast)
    }
  }

  const document = instanceMap[id]
  if (document && Array.isArray(tasks)) {
    const results = []
    tasks.forEach((task) => {
      const handler = jsHandlers[task.method]
      const args = [...task.args]
      if (typeof handler === 'function') {
        args.unshift(id)
        results.push(handler(...args))
      }
    })
    return results
  }
}
<commit_msg>* [jsfm] passed eslint<commit_after>const config = {}

const instanceMap = {}

export function init (cfg) {
  config.Document = cfg.Document
  config.Element = cfg.Element
  config.Comment = cfg.Comment
  config.sendTasks = cfg.sendTasks
}

export function registerComponents (components) {}

export function registerModules (modules) {}

export function registerMethods (apis) {}

export function prepareInstance (id, options, data) {}

export function createInstance (id, code, options, data) {
  const document = new config.Document(id, options.bundleUrl)
  const callbacks = {}
  let lastCallbackId = 0
  document.addCallback = func => {
    lastCallbackId++
    callbacks[lastCallbackId] = func
    return lastCallbackId
  }
  document.handleCallback = (funcId, data, ifLast) => {
    const callback = callbacks[funcId]
    if (ifLast) {
      delete callbacks[funcId]
    }
    return callback(data)
  }
  instanceMap[id] = document
  const result = new Function(
    'Document',
    'Element',
    'Comment',
    'sendTasks',
    'id',
    'options',
    'data',
    'document',
    code
  )
  return result(
    config.Document,
    config.Element,
    config.Comment,
    config.sendTasks,
    id,
    options,
    data,
    document
  )
}

export function refreshInstance (id, data) {}

export function destroyInstance (id) {
  delete instanceMap[id]
}

export function getRoot (id) {
  return instanceMap[id].body.toJSON()
}

export function receiveTasks (id, tasks) {
  const jsHandlers = {
    fireEvent: (id, ref, type, data, domChanges) => {
      const document = instanceMap[id]
      const el = document.getRef(ref)
      return document.fireEvent(el, type, data, domChanges)
    },

    callback: (id, funcId, data, ifLast) => {
      const document = instanceMap[id]
      return document.handleCallback(funcId, data, ifLast)
    }
  }

  const document = instanceMap[id]
  if (document && Array.isArray(tasks)) {
    const results = []
    tasks.forEach((task) => {
      const handler = jsHandlers[task.method]
      const args = [...task.args]
      if (typeof handler === 'function') {
        args.unshift(id)
        results.push(handler(...args))
      }
    })
    return results
  }
}
<|endoftext|>


<commit_before>const karmaDefault = require('./karma.default');

module.exports = config => {
    // Browsers to run on Sauce Labs
    const customLaunchers = {
        'SL_Chrome': {
            base: 'SauceLabs',
            browserName: 'chrome',
            platform: 'Windows 10',
            version: 'latest'
        },
        'SL_Edge': {
            base: 'SauceLabs',
            browserName: 'MicrosoftEdge',
            platform: 'Windows 10',
            version: 'latest'
        },
        'SL_FireFox': {
            base: 'SauceLabs',
            browserName: 'firefox',
            platform: 'Windows 10',
            version: 'latest'
        }
    };

    config.set(Object.assign({}, karmaDefault(config), {
        // Webpack please don't spam the console when running in karma!
        webpackServer: { noInfo: true },

        reporters: ['dots', 'saucelabs'],

        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        sauceLabs: {
            testName: 'Angular lazy load images',
            tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
            username: process.env.SAUCE_USERNAME,
            accessKey: process.env.SAUCE_ACCESS_KEY,
            startConnect: false
        },
        captureTimeout: 120000,
        customLaunchers: customLaunchers,
        browsers: Object.keys(customLaunchers),
        singleRun: true,
        autoWatch: false
    }));
};
<commit_msg>:green_heart: Set SL currency to 1<commit_after>const karmaDefault = require('./karma.default');

module.exports = config => {
    // Browsers to run on Sauce Labs
    const customLaunchers = {
        'SL_Chrome': {
            base: 'SauceLabs',
            browserName: 'chrome',
            platform: 'Windows 10',
            version: 'latest'
        },
        'SL_Edge': {
            base: 'SauceLabs',
            browserName: 'MicrosoftEdge',
            platform: 'Windows 10',
            version: 'latest'
        },
        'SL_FireFox': {
            base: 'SauceLabs',
            browserName: 'firefox',
            platform: 'Windows 10',
            version: 'latest'
        }
    };

    config.set(Object.assign({}, karmaDefault(config), {
        // Webpack please don't spam the console when running in karma!
        webpackServer: { noInfo: true },

        reporters: ['dots', 'saucelabs'],

        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        sauceLabs: {
            testName: 'Angular lazy load images',
            tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
            username: process.env.SAUCE_USERNAME,
            accessKey: process.env.SAUCE_ACCESS_KEY,
            startConnect: false
        },
        captureTimeout: 120000,
        customLaunchers: customLaunchers,
        browsers: Object.keys(customLaunchers),
        singleRun: true,
        concurrency: 1,
        autoWatch: false
    }));
};
<|endoftext|>


<commit_before>// console.log('Loading Publishing...')

Spontaneous.Publishing = (function($, S) {
	var dom = S.Dom, Dialogue = Spontaneous.Dialogue;

	var PublishingDialogue = new JS.Class(Dialogue, {
		initialize: function(content) {
			this.change_sets = [];
			var callback = this.page_lock_removed.bind(this);
			var page_lock_removed = function(event) {
				callback($.parseJSON(event.data))
			};
			S.EventSource.addEventListener('page_lock_status', page_lock_removed);
			this.page_lock_removed_listener = page_lock_removed;
		},
		page_lock_removed: function(page_ids) {
			var changes = this.change_sets, toUnlock = [];
			page_ids.forEach(function(id) {
				toUnlock = toUnlock.concat(changes.filter(function(c) { return c.change.id == id }))
			});

			toUnlock.forEach(function(cs) {
				cs.unlock();
			});
		},
		cleanup: function() {
			S.EventSource.removeEventListener('page_lock_status', this.page_lock_removed_listener);
		},
		width: function() {
			return '90%';
		},
		title: function() {
			return "Publish Changes";
		},
		class_name: function() {
			return "publishing";
		},
		body: function() {
			var wrapper = dom.div('#publishing-dialogue');
			var spinner = dom.div(".spinner");
			wrapper.append(spinner);

			this.spinnerWrap = spinner;
			this.wrapper = wrapper;
			this.spinner = S.Progress(spinner[0], 48, {period: 800, segment_length: 0.30});
			this.spinner.start()
			spinner.append(dom.div().append(dom.p().text("Loading changes...")))
			Spontaneous.Ajax.get('/changes', this.change_list_loaded.bind(this));
			return wrapper;
		},
		buttons: function() {
			btns = {};
			btns['Publish'] = this.publish.bind(this);
			return btns;
		},
		publish: function() {
			var ids = [], changes = this.changes_to_publish();
			for (var i = 0, ii = changes.length; i < ii; i++) {
				ids = ids.concat(changes[i].page_ids());
			}
			if (ids.length > 0) {
				Spontaneous.Ajax.post('/changes', {'page_ids': ids}, this.publish_requested.bind(this));
			} else {
			}
		},

		publish_requested: function() {
			Spontaneous.TopBar.publishing_started();
			this.close();
		},

		change_list_loaded: function(outstanding) {
			var change_list = outstanding.changes
			, w = this.wrapper
			, self = this
			, changed_wrap = dom.div("#changes.change-list").css("opacity", 0)
			, publish_wrap = dom.div("#to-publish.change-list").css("opacity", 0)
			, first_publish = outstanding.first_publish
			, spinner = this.spinner
			, append_to;
			if (first_publish) {
				w.addClass("first-publish");
			}
			if (change_list.length === 0) {
				var summary = dom.p('.publish-up-to-date').text("The site is up to date");
				w.append(summary);
				self.disable_button('Publish');
			} else {
				var publish_all = dom.a('.button').text('Publish All').click(function() {
					self.set_publish_all(true);
				}.bind(self));
				var clear_all = dom.a('.button').text('Clear All').click(function() {
					self.set_publish_all(false);
				}.bind(self));

				var changed_toolbar = dom.div('.actions').append(dom.div().text("Modified pages")).append(publish_all);
				var publish_toolbar = dom.div('.actions').append(dom.div().text("Publish pages"));
				if (!first_publish) {
					publish_toolbar.append(clear_all);
				}
				var changed_entries = dom.div('.change-sets'), publish_entries = dom.div('.change-sets')
				changed_wrap.append(changed_toolbar, changed_entries);
				publish_wrap.append(publish_toolbar, publish_entries);
				append_to = changed_entries;
				if (first_publish) {
					append_to = publish_entries;
				}
				for (var i = 0, ii = change_list.length; i < ii; i++) {
					var cs = new ChangeSet(i, self, change_list[i], first_publish);
					self.change_sets.push(cs);
					append_to.append(cs.panel())
				}
				if (!first_publish) {
					publish_entries.append(dom.div('.instructions').text('Add pages to publish from the list on the left'));
				}
				spinner.stop();
				this.spinnerWrap.remove();
				w.empty();
				w.append(changed_wrap, publish_wrap)
				changed_wrap.add(publish_wrap).animate({opacity: 1});
				self.changed_entries = changed_entries;
				self.publish_entries = publish_entries;
			}
		},
		set_publish_all: function(state) {
			this.publish_all = state;
			$.each(this.change_sets, function() {
				this.select(state);
			});
		},
		change_set_state: function(change_set, state) {
			var id = 'cs-' + change_set.id, panel, __this = this;
			if (state) {
				this.publish_entries.find('.instructions').hide();
				panel = change_set.selected_panel(id).hide();
				this.publish_entries.prepend(panel);
				change_set.panel().disappear();
				panel.appear();
			} else {
				panel = this.publish_entries.find('#'+id)
				panel.disappear(function() {
					panel.remove();
					var entries = __this.publish_entries;
					if (entries.find('.change-set').length == 0) {
						entries.find('.instructions').fadeIn();
					}
				});
				change_set.panel().appear();
			}
		},
		change_set_dependency_state: function(dependentPage) {
			var self = this;
			var dependentSet = this.change_sets.filter(function(set) {
				return set.change.id === dependentPage.id;
			});
			var dependentGraph = this.change_sets.filter(function(set) {
				return set.has_dependency(dependentPage);
			});
			var group = dependentSet.concat(dependentGraph)
			group.forEach(function(set) {
				set.select(true);
			});
		},
		dependency_forces_publish: function(set) {
			var dependencyPage = set.page();
			return this.change_sets.some(function(set) {
				return set.selected && set.dependent_pages().some(function(page) {
					return page.id === dependencyPage.id;
				});
			});
		},
		selected: function() {
			var selected = [], cs;
			for (var i = 0, ii = this.change_sets.length; i < ii; i++) {
				cs = this.change_sets[i];
				if (cs.selected) {
					selected.push(cs);
				}
			}
			return selected;
		},
		changes_to_publish: function() {
			return this.selected();
		}
	});

	var Page = new JS.Class({
		initialize: function(details) {
			$.extend(this, details);
		},
		isUnpublished: function() {
			return !this.published_at;
		},
		isDependent: function() {
			return !this.hasOwnProperty("dependent");
		},

		panel: function() {
			var self = this
			, pageTitle = dom.span(".page-title").html(this.title)
			, classes = ".title" + (this.isDependent() ? ".dependent" : "")
			, modificationDate = dom.div('.modification-date').html(this.modifiedAt())
			, publicationDate = dom.div('.publication-date').html(this.publishedAt())
			, metadata = dom.div(".dates").append(modificationDate, publicationDate)
			if (this.isUnpublished()) {
				pageTitle.attr("title", "This page is new and has never been published");
			}
			return dom.div(classes).append(pageTitle, dom.div('.url').text(this.url)).append(metadata).click(function() {
				S.Dialogue.close();
				S.Location.load_id(self.id);
			});
		},
		modifiedAt: function() {
			return "Modified: " + this.formatDate(this.modified_at);
		},
		publishedAt: function() {
			var date;
			if (this.isUnpublished()) {
				date = 'Never';
			} else {
				date = this.formatDate(this.published_at);
			}
			return "Published: " + date;
		},
		formatDate: function(dateString) {
			if (!dateString) { return ""; }
			var d = new Date(dateString);
			// use date.js formatting
			return d.toString("d MMM yyyy, HH:mm");
		}
	});
	var ChangeSet = new JS.Class({
		initialize: function(id, dialogue, change, selected) {
			this.id = id;
			this.dialogue = dialogue;
			this.change = change;
			this.selected    = selected || false;
			this.mustPublish = selected || false;
		},
		locks: function(){
			return this.change.update_locks;
		},
		isLocked: function() {
			return this.locks().length > 0;
		},
		unlock: function() {
			var w = this.wrapper;
			w.removeClass("locked").find(".lock-state").remove();
			this.locks().length = 0;
		},
		page_ids: function() {
			var ids = [this.change.id];
			return ids.concat(this.dependent_pages().map(function(p) { return p.id; }));
		},
		panel: function() {
			if (!this._panel) {
				this._panel = this.createPanel();
				this.wrapper = this._panel;
			}
			return this._panel;
		},
		createPanel: function() {
			var w = dom.div('.change-set')
			, inner = dom.div('.inner')
			, page_list = dom.div('.pages')
			, add = dom.div('.add').append(dom.span().text(''))
			, page = this.page()
			, pages = this.dependent_pages()
			, locked = this.isLocked()
			, info = dom.div(".info").hide();

			if (page.isUnpublished()) {
				w.addClass('unpublished');
			}
			if (locked) {
				w.addClass('locked');
				var lockState = dom.div(".lock-state")
				, title = dom.h3().html("Cannot publish page until the following actions have completed:")
				, details = dom.div(".locks")
				, locks = this.locks();
				locks.forEach(function(lock) {
					var line = dom.p();
					line.text(lock.description);
					line.prepend(dom.strong().text(lock.location));
					details.append(line);
				});
				lockState.append(title, details)
				info.append(lockState);
				page_list.append(info);
				add.hover(function() {
					info.show().animate({"width": "100%"}, 150);
				}, function() {
					info.hide().css("width", 0);
				});
			}
			page_list.append(page.panel());
			for (var i = 0, ii = pages.length; i < ii; i++) {
				page_list.append(pages[i].panel());
			}

			add.click(function() {
				this.select_toggle();
			}.bind(this));

			inner.append(page_list);

			if (!this.mustPublish) {
				inner.append(add);
			}
			w.append(inner);
			return w;
		},
		selected_panel: function(id) {
			var panel = this.createPanel().attr('id', id);
			panel.find('.add').find('span').addClass('active');
			return panel;
		},
		select: function(state) {
			var self = this;
			if (this.isLocked()) { return ; }
			if (state === self.selected) { return; }
			if (!state && self.dependency_forces_publish()) {
				return;
			}
			self.selected = state;
			self.dialogue.change_set_state(self, self.selected);
			if (state) {
				self.dependent_pages().forEach(function(page) {
					self.dialogue.change_set_dependency_state(page);
				});
				var page = self.page();
				if (page.isUnpublished()) {
					self.dialogue.change_set_dependency_state(page);
				}
			}
		},
		select_toggle: function() {
			this.select(!this.selected)
		},
		update_view: function() {
			if (this.selected) {
				this.wrapper.addClass('selected')
			} else {
				this.wrapper.removeClass('selected')
			}
		},
		page: function() {
			return new Page(this.change);
		}.cache("_page_"),

		dependency_forces_publish: function() {
			return this.dialogue.dependency_forces_publish(this);
		},
		dependent_pages: function() {
			if (!this._dependent_pages) {
				this._dependent_pages = this.change.dependent.map(function(p) {
					return new Page(p);
				}).sort(function(p1, p2) {
					var a = p2.depth, b = p1.depth;
					if (a == b) return 0;
					return (a  0;
		}
	});

	var Publishing = new JS.Singleton({
		open_dialogue: function() {
			Dialogue.open(new PublishingDialogue());
		}
	});

	return Publishing;
})(jQuery, Spontaneous);

<commit_msg>Clean up after myself<commit_after>// console.log('Loading Publishing...')

Spontaneous.Publishing = (function($, S) {
	var dom = S.Dom, Dialogue = Spontaneous.Dialogue;

	var PublishingDialogue = new JS.Class(Dialogue, {
		initialize: function(content) {
			this.change_sets = [];
			var callback = this.page_lock_removed.bind(this);
			var page_lock_removed = function(event) {
				callback($.parseJSON(event.data))
			};
			S.EventSource.addEventListener('page_lock_status', page_lock_removed);
			this.page_lock_removed_listener = page_lock_removed;
		},
		page_lock_removed: function(page_ids) {
			var changes = this.change_sets, toUnlock = [];
			page_ids.forEach(function(id) {
				toUnlock = toUnlock.concat(changes.filter(function(c) { return c.change.id == id }))
			});

			toUnlock.forEach(function(cs) {
				cs.unlock();
			});
		},
		cleanup: function() {
			S.EventSource.removeEventListener('page_lock_status', this.page_lock_removed_listener);
		},
		width: function() {
			return '90%';
		},
		title: function() {
			return "Publish Changes";
		},
		class_name: function() {
			return "publishing";
		},
		body: function() {
			var wrapper = dom.div('#publishing-dialogue');
			var spinner = dom.div(".spinner");
			wrapper.append(spinner);

			this.spinnerWrap = spinner;
			this.wrapper = wrapper;
			this.spinner = S.Progress(spinner[0], 48, {period: 800, segment_length: 0.30});
			this.spinner.start()
			spinner.append(dom.div().append(dom.p().text("Loading changes...")))
			Spontaneous.Ajax.get('/changes', this.change_list_loaded.bind(this));
			return wrapper;
		},
		buttons: function() {
			btns = {};
			btns['Publish'] = this.publish.bind(this);
			return btns;
		},
		publish: function() {
			var ids = [], changes = this.changes_to_publish();
			for (var i = 0, ii = changes.length; i < ii; i++) {
				ids = ids.concat(changes[i].page_ids());
			}
			if (ids.length > 0) {
				Spontaneous.Ajax.post('/changes', {'page_ids': ids}, this.publish_requested.bind(this));
			} else {
			}
		},

		publish_requested: function() {
			Spontaneous.TopBar.publishing_started();
			this.close();
		},

		change_list_loaded: function(outstanding) {
			var change_list = outstanding.changes
			, w = this.wrapper
			, self = this
			, changed_wrap = dom.div("#changes.change-list").css("opacity", 0)
			, publish_wrap = dom.div("#to-publish.change-list").css("opacity", 0)
			, first_publish = outstanding.first_publish
			, spinner = this.spinner
			, append_to;
			if (first_publish) {
				w.addClass("first-publish");
			}
			if (change_list.length === 0) {
				var summary = dom.p('.publish-up-to-date').text("The site is up to date");
				w.append(summary);
				self.disable_button('Publish');
			} else {
				var publish_all = dom.a('.button').text('Publish All').click(function() {
					self.set_publish_all(true);
				}.bind(self));
				var clear_all = dom.a('.button').text('Clear All').click(function() {
					self.set_publish_all(false);
				}.bind(self));

				var changed_toolbar = dom.div('.actions').append(dom.div().text("Modified pages")).append(publish_all);
				var publish_toolbar = dom.div('.actions').append(dom.div().text("Publish pages"));
				if (!first_publish) {
					publish_toolbar.append(clear_all);
				}
				var changed_entries = dom.div('.change-sets'), publish_entries = dom.div('.change-sets')
				changed_wrap.append(changed_toolbar, changed_entries);
				publish_wrap.append(publish_toolbar, publish_entries);
				append_to = changed_entries;
				if (first_publish) {
					append_to = publish_entries;
				}
				for (var i = 0, ii = change_list.length; i < ii; i++) {
					var cs = new ChangeSet(i, self, change_list[i], first_publish);
					self.change_sets.push(cs);
					append_to.append(cs.panel())
				}
				if (!first_publish) {
					publish_entries.append(dom.div('.instructions').text('Add pages to publish from the list on the left'));
				}
				spinner.stop();
				this.spinnerWrap.remove();
				w.empty();
				w.append(changed_wrap, publish_wrap)
				changed_wrap.add(publish_wrap).animate({opacity: 1});
				self.changed_entries = changed_entries;
				self.publish_entries = publish_entries;
				this.spinner = this.spinnerWrap = null;
			}
		},
		set_publish_all: function(state) {
			this.publish_all = state;
			$.each(this.change_sets, function() {
				this.select(state);
			});
		},
		change_set_state: function(change_set, state) {
			var id = 'cs-' + change_set.id, panel, __this = this;
			if (state) {
				this.publish_entries.find('.instructions').hide();
				panel = change_set.selected_panel(id).hide();
				this.publish_entries.prepend(panel);
				change_set.panel().disappear();
				panel.appear();
			} else {
				panel = this.publish_entries.find('#'+id)
				panel.disappear(function() {
					panel.remove();
					var entries = __this.publish_entries;
					if (entries.find('.change-set').length == 0) {
						entries.find('.instructions').fadeIn();
					}
				});
				change_set.panel().appear();
			}
		},
		change_set_dependency_state: function(dependentPage) {
			var self = this;
			var dependentSet = this.change_sets.filter(function(set) {
				return set.change.id === dependentPage.id;
			});
			var dependentGraph = this.change_sets.filter(function(set) {
				return set.has_dependency(dependentPage);
			});
			var group = dependentSet.concat(dependentGraph)
			group.forEach(function(set) {
				set.select(true);
			});
		},
		dependency_forces_publish: function(set) {
			var dependencyPage = set.page();
			return this.change_sets.some(function(set) {
				return set.selected && set.dependent_pages().some(function(page) {
					return page.id === dependencyPage.id;
				});
			});
		},
		selected: function() {
			var selected = [], cs;
			for (var i = 0, ii = this.change_sets.length; i < ii; i++) {
				cs = this.change_sets[i];
				if (cs.selected) {
					selected.push(cs);
				}
			}
			return selected;
		},
		changes_to_publish: function() {
			return this.selected();
		}
	});

	var Page = new JS.Class({
		initialize: function(details) {
			$.extend(this, details);
		},
		isUnpublished: function() {
			return !this.published_at;
		},
		isDependent: function() {
			return !this.hasOwnProperty("dependent");
		},

		panel: function() {
			var self = this
			, pageTitle = dom.span(".page-title").html(this.title)
			, classes = ".title" + (this.isDependent() ? ".dependent" : "")
			, modificationDate = dom.div('.modification-date').html(this.modifiedAt())
			, publicationDate = dom.div('.publication-date').html(this.publishedAt())
			, metadata = dom.div(".dates").append(modificationDate, publicationDate)
			if (this.isUnpublished()) {
				pageTitle.attr("title", "This page is new and has never been published");
			}
			return dom.div(classes).append(pageTitle, dom.div('.url').text(this.url)).append(metadata).click(function() {
				S.Dialogue.close();
				S.Location.load_id(self.id);
			});
		},
		modifiedAt: function() {
			return "Modified: " + this.formatDate(this.modified_at);
		},
		publishedAt: function() {
			var date;
			if (this.isUnpublished()) {
				date = 'Never';
			} else {
				date = this.formatDate(this.published_at);
			}
			return "Published: " + date;
		},
		formatDate: function(dateString) {
			if (!dateString) { return ""; }
			var d = new Date(dateString);
			// use date.js formatting
			return d.toString("d MMM yyyy, HH:mm");
		}
	});
	var ChangeSet = new JS.Class({
		initialize: function(id, dialogue, change, selected) {
			this.id = id;
			this.dialogue = dialogue;
			this.change = change;
			this.selected    = selected || false;
			this.mustPublish = selected || false;
		},
		locks: function(){
			return this.change.update_locks;
		},
		isLocked: function() {
			return this.locks().length > 0;
		},
		unlock: function() {
			var w = this.wrapper;
			w.removeClass("locked").find(".lock-state").remove();
			this.locks().length = 0;
		},
		page_ids: function() {
			var ids = [this.change.id];
			return ids.concat(this.dependent_pages().map(function(p) { return p.id; }));
		},
		panel: function() {
			if (!this._panel) {
				this._panel = this.createPanel();
				this.wrapper = this._panel;
			}
			return this._panel;
		},
		createPanel: function() {
			var w = dom.div('.change-set')
			, inner = dom.div('.inner')
			, page_list = dom.div('.pages')
			, add = dom.div('.add').append(dom.span().text(''))
			, page = this.page()
			, pages = this.dependent_pages()
			, locked = this.isLocked()
			, info = dom.div(".info").hide();

			if (page.isUnpublished()) {
				w.addClass('unpublished');
			}
			if (locked) {
				w.addClass('locked');
				var lockState = dom.div(".lock-state")
				, title = dom.h3().html("Cannot publish page until the following actions have completed:")
				, details = dom.div(".locks")
				, locks = this.locks();
				locks.forEach(function(lock) {
					var line = dom.p();
					line.text(lock.description);
					line.prepend(dom.strong().text(lock.location));
					details.append(line);
				});
				lockState.append(title, details)
				info.append(lockState);
				page_list.append(info);
				add.hover(function() {
					info.show().animate({"width": "100%"}, 150);
				}, function() {
					info.hide().css("width", 0);
				});
			}
			page_list.append(page.panel());
			for (var i = 0, ii = pages.length; i < ii; i++) {
				page_list.append(pages[i].panel());
			}

			add.click(function() {
				this.select_toggle();
			}.bind(this));

			inner.append(page_list);

			if (!this.mustPublish) {
				inner.append(add);
			}
			w.append(inner);
			return w;
		},
		selected_panel: function(id) {
			var panel = this.createPanel().attr('id', id);
			panel.find('.add').find('span').addClass('active');
			return panel;
		},
		select: function(state) {
			var self = this;
			if (this.isLocked()) { return ; }
			if (state === self.selected) { return; }
			if (!state && self.dependency_forces_publish()) {
				return;
			}
			self.selected = state;
			self.dialogue.change_set_state(self, self.selected);
			if (state) {
				self.dependent_pages().forEach(function(page) {
					self.dialogue.change_set_dependency_state(page);
				});
				var page = self.page();
				if (page.isUnpublished()) {
					self.dialogue.change_set_dependency_state(page);
				}
			}
		},
		select_toggle: function() {
			this.select(!this.selected)
		},
		update_view: function() {
			if (this.selected) {
				this.wrapper.addClass('selected')
			} else {
				this.wrapper.removeClass('selected')
			}
		},
		page: function() {
			return new Page(this.change);
		}.cache("_page_"),

		dependency_forces_publish: function() {
			return this.dialogue.dependency_forces_publish(this);
		},
		dependent_pages: function() {
			if (!this._dependent_pages) {
				this._dependent_pages = this.change.dependent.map(function(p) {
					return new Page(p);
				}).sort(function(p1, p2) {
					var a = p2.depth, b = p1.depth;
					if (a == b) return 0;
					return (a  0;
		}
	});

	var Publishing = new JS.Singleton({
		open_dialogue: function() {
			Dialogue.open(new PublishingDialogue());
		}
	});

	return Publishing;
})(jQuery, Spontaneous);

<|endoftext|>


<commit_before>/** Pixel Circle Generator V0.1
 *
 * (c) Roel Walraven (cytodev) <mail@cytodev.io>
 *
 */

let isBetaVersion = true, version = 0.1.1;

window.onload = function() {
    var continuousSwitch = document.getElementById("ContinuousSwitch");
    var radiusInput = document.getElementById("radius");
    var areaInput = document.getElementById("area");
    var visualise = document.getElementById("visualise");
    var circumference = document.getElementById("circumference");
    var canvaswrapper = document.getElementById("VisualWrapper");
    var loading = document.getElementById("loading");
    var canvas = document.getElementById("Visualisation");
    var canvasContext = canvas.getContext("2d");
    var lastRadius = NaN;
    var lastX = canvas.width / 2;
    var lastY = canvas.height / 2;
    var dragStart;
    var dragged;
    var scaleFactor = 1.1;
    var continuous = false;

    var zoom = function(clicks) {
        var pt = canvasContext.transformedPoint(lastX, lastY);
        var factor = Math.pow(scaleFactor, clicks);

        canvasContext.translate(pt.x, pt.y);
        canvasContext.scale(factor, factor);
        canvasContext.translate(-pt.x, -pt.y);
        redraw();
    };

    var handleScroll = function(e){
        var delta = e.wheelDelta ? e.wheelDelta/40 : e.detail ? -e.detail : 0;

        if(delta) {
            zoom(delta);
        }

        return e.preventDefault() && false;
    };

    // scales correctly at times. At other times it doesn't...
    function scaleCanvas() {
        canvas.width = 0;
        canvas.height = 0;

        setTimeout(function() {
            canvas.width = document.getElementById("VisualWrapper").clientWidth - 34;
            canvas.height = canvas.width / 16 * 9;
            loading.style.display = "block";
            setTimeout(function() {
                redraw();
            }, 1400);
        }, 250);
    }

    function updateValues(element) {
        var r = 0;
        var a = 0;
        var c = 0;

        switch(element) {
            case radiusInput:
                r = radiusInput.value;
                a = Math.PI * Math.pow(r, 2)
                c = 2 * Math.PI * r;
                break;
            case areaInput:
                a = areaInput.value;
                r = Math.sqrt(a / Math.PI);
                c = 2 * Math.PI * r;
                break;
            default:
                break;
        }

        radiusInput.value = r;
        areaInput.value = a;

        circumference.innerHTML = c;
    }

    function clearCanvas() {
        var p1 = canvasContext.transformedPoint(0, 0);
        var p2 = canvasContext.transformedPoint(canvas.width, canvas.height);
        canvasContext.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
        canvasContext.save();
        canvasContext.setTransform(1, 0, 0, 1, 0, 0);
        canvasContext.clearRect(0, 0, canvas.width, canvas.height);
        canvasContext.restore();
    }

    function drawPixel(x, y) {
        canvasContext.rect(x * 4, y * 4, 4, 4);
        canvasContext.fillStyle = "#212121";
        canvasContext.fill();
    }

    function drawGrid() {
        var maxWidth = 2000;
        var maxHeight = 2000;

        canvasContext.beginPath();

        for(var x = -maxWidth; x <= maxWidth; x += 4) {
            canvasContext.moveTo(x, -maxWidth);
            canvasContext.lineTo(x, maxWidth);
        }

        for(var y = -maxHeight; y <= maxHeight; y += 4) {
            canvasContext.moveTo(-maxHeight, y);
            canvasContext.lineTo(maxHeight, y);
        }

        canvasContext.strokeStyle = "#E0E0E0";
        canvasContext.lineWidth = 0.1;
        canvasContext.stroke();
        canvasContext.closePath();

        loading.style.display = "none";
    }

    function draw(radius) {
        radius = Math.round(parseFloat(radius));

        if(!radius || 0 === radius.length || isNaN(radius) && !isFinite(radius)) {
            return;
        }

        var d = Math.round(Math.PI - (2 * radius));
        var x = 0;
        var y = radius;

        canvasContext.beginPath();
        while(x <= y) {
            drawPixel(radius + x + 1, radius - y);
            drawPixel(radius + y + 1, radius - x);
            drawPixel(radius + y + 1, radius + x + 1);
            drawPixel(radius + x + 1, radius + y + 1);
            drawPixel(radius - x, radius + y + 1);
            drawPixel(radius - y, radius + x + 1);
            drawPixel(radius - y, radius - x);
            drawPixel(radius - x, radius - y);

            if(continuous) {
                drawPixel(radius + x + 2, radius - y);
                drawPixel(radius + y + 1, radius - x - 1);
                drawPixel(radius + y + 1, radius + x + 2);
                drawPixel(radius + x + 2, radius + y + 1);
                drawPixel(radius - x - 1, radius + y + 1);
                drawPixel(radius - y, radius + x + 2);
                drawPixel(radius - y, radius - x - 1);
                drawPixel(radius - x - 1, radius - y);
            }

            if (d < 0) {
                d = d + (Math.PI * x) + (Math.PI * 2);
            } else {
                d = d + Math.PI * (x - y) + (Math.PI * 3);
                y--;
            }

            x++;
        }
        canvasContext.closePath();
    }

    function redraw() {
        clearCanvas();
        draw(lastRadius);
        drawGrid();
    }

    canvas.addEventListener("mousedown", function(e) {
        for(var i = document.getElementsByTagName("*").length - 1; i >= 0; i--) {
            document.getElementsByTagName("*")[i].classList.add("noselect");
        }

        lastX = e.offsetX || (e.pageX - canvas.offsetLeft);
        lastY = e.offsetY || (e.pageY - canvas.offsetTop);
        dragStart = canvasContext.transformedPoint(lastX, lastY);
        dragged = false;
    }, false);

    canvas.addEventListener("mousemove", function(e) {
        lastX = e.offsetX || (e.pageX - canvas.offsetLeft);
        lastY = e.offsetY || (e.pageY - canvas.offsetTop);
        dragged = true;

        if(dragStart) {
            var pt = canvasContext.transformedPoint(lastX, lastY);
            canvasContext.translate(pt.x - dragStart.x, pt.y - dragStart.y);
            redraw();
        }
    }, false);

    canvas.addEventListener("mouseup", function(e) {
        for(var i = document.getElementsByTagName("*").length - 1; i >= 0; i--) {
            document.getElementsByTagName("*")[i].classList.remove("noselect");
        }

        dragStart = null;

        if(!dragged) {
            // add highlighting logic here
        }
    }, false);

    canvas.addEventListener("DOMMouseScroll", handleScroll, false);
    canvas.addEventListener("mousewheel", handleScroll, false);

    continuousSwitch.addEventListener("click", function(e) {
        continuous = continuousSwitch.checked;
    }, false);

    radiusInput.addEventListener("keyup", function(e) {
        updateValues(radiusInput);
    }, false);

    areaInput.addEventListener("keyup", function(e) {
        updateValues(areaInput);
    }, false);

    visualise.addEventListener("click", function(e) {
        clearCanvas();
        loading.style.display = "block";
        lastRadius = radiusInput.value;
        draw(lastRadius);
        drawGrid();
    }, false);

    trackTransforms(canvasContext);
    scaleCanvas();
    window.onresize = scaleCanvas();

    loading.style.display = "none";

    if(isBetaVersion) {
        var betaNotice = document.createElement("span");

        betaNotice.id = "BetaNotice";
        betaNotice.innerHTML = "βῆτα v" + version;
        document.getElementsByTagName("header")[0].getElementsByTagName("h1")[0].appendChild(betaNotice);
    }
};

function trackTransforms(canvasContext) {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    var xform = svg.createSVGMatrix();
    var savedTransforms = [];
    var save = canvasContext.save;
    var restore = canvasContext.restore;
    var scale = canvasContext.scale;
    var translate = canvasContext.translate;
    var setTransform = canvasContext.setTransform;
    var pt  = svg.createSVGPoint();

    canvasContext.save = function() {
        savedTransforms.push(xform.translate(0, 0));
        return save.call(canvasContext);
    };

    canvasContext.restore = function() {
        xform = savedTransforms.pop();
        return restore.call(canvasContext);
    };

    canvasContext.scale = function(sx, sy) {
        xform = xform.scaleNonUniform(sx, sy);
        return scale.call(canvasContext, sx, sy);
    };

    canvasContext.translate = function(dx, dy) {
        xform = xform.translate(dx, dy);
        return translate.call(canvasContext, dx, dy);
    };

    canvasContext.setTransform = function(a, b, c, d, e, f) {
        xform.a = a;
        xform.b = b;
        xform.c = c;
        xform.d = d;
        xform.e = e;
        xform.f = f;

        return setTransform.call(canvasContext, a, b, c, d, e, f);
    };

    canvasContext.transformedPoint = function(x, y) {
        pt.x = x;
        pt.y = y;

        return pt.matrixTransform(xform.inverse());
    };
}
<commit_msg>Adds panning and zoom functionality<commit_after>/** Pixel Circle Generator V0.1
 *
 * (c) Roel Walraven (cytodev) <mail@cytodev.io>
 *
 */

let isBetaVersion = true, version = "0.1.2";

window.onload = function() {
    var continuousSwitch = document.getElementById("ContinuousSwitch");
    var radiusInput = document.getElementById("radius");
    var areaInput = document.getElementById("area");
    var visualise = document.getElementById("visualise");
    var circumference = document.getElementById("circumference");
    var canvaswrapper = document.getElementById("VisualWrapper");
    var loading = document.getElementById("loading");
    var canvas = document.getElementById("Visualisation");
    var canvasContext = canvas.getContext("2d");
    var lastRadius = NaN;
    var lastX = canvas.width / 2;
    var lastY = canvas.height / 2;
    var touch = {"start": [], "center": {"x": 0, "y": 0}, "offset": [], "delta": [], "zoom": 0};
    var dragStart;
    var dragged;
    var scaleFactor = 1.1;
    var continuous = false;

    var pointerDown = function(e) {
        for(var i = document.getElementsByTagName("*").length - 1; i >= 0; i--) {
            document.getElementsByTagName("*")[i].classList.add("noselect");
        }

        if(e.type === "touchstart") {
            e.preventDefault();

            touch.center.x = 0;
            touch.center.y = 0;

            for(var i = 0; i < e.touches.length; i++) {
                touch.start[i] = {};
                touch.start[i].x = e.touches[i].pageX;
                touch.start[i].y = e.touches[i].pageY;

                touch.center.x += touch.start[i].x;
                touch.center.y += touch.start[i].y;
            }

            touch.center.x = touch.center.x / touch.start.length;
            touch.center.y = touch.center.y / touch.start.length;

            lastX = touch.center.x - canvas.offsetLeft;
            lastY = touch.center.y - canvas.offsetTop;
        } else {
            lastX = e.offsetX || (e.pageX - canvas.offsetLeft);
            lastY = e.offsetY || (e.pageY - canvas.offsetTop);
        }

        dragStart = canvasContext.transformedPoint(lastX, lastY);
        dragged = false;
    };

    var pointerMove = function(e) {
        if(e.type === "touchmove") {
            e.preventDefault();
            if(e.touches.length > 1) {
                touch.zoom = 0;
                dragStart = null;

                for(var i = 0; i < e.touches.length; i++) {
                    touch.offset[i] = {};
                    touch.offset[i].x = e.touches[i].pageX;
                    touch.offset[i].y = e.touches[i].pageY;
                }

                for(var i = 0; i < touch.start.length; i++) {
                    touch.delta[i] = {};
                    touch.delta[i].x = Math.abs(touch.offset[i].x - touch.center.x) - Math.abs(touch.start[i].x - touch.center.x);
                    touch.delta[i].y = Math.abs(touch.offset[i].y - touch.center.y) - Math.abs(touch.start[i].y - touch.center.y);
                    touch.zoom += touch.delta[i].x + touch.delta[i].y;
                }

                handleScroll({"wheelDelta": touch.zoom / 5, "isTouchEvent": true});
            } else {
                lastX = e.touches[0].pageX - canvas.offsetLeft;
                lastY = e.touches[0].pageY - canvas.offsetTop;
            }
        } else {
            lastX = e.offsetX || (e.pageX - canvas.offsetLeft);
            lastY = e.offsetY || (e.pageY - canvas.offsetTop);
        }

        dragged = true;

        if(dragStart) {
            var pt = canvasContext.transformedPoint(lastX, lastY);
            canvasContext.translate(pt.x - dragStart.x, pt.y - dragStart.y);
            redraw();
        }
    };

    var pointerUp = function(e) {
        for(var i = document.getElementsByTagName("*").length - 1; i >= 0; i--) {
            document.getElementsByTagName("*")[i].classList.remove("noselect");
        }

        dragStart = null;

        if(!dragged) {
            // add highlighting logic here
        }
    }

    var handleScroll = function(e) {
        var delta = e.wheelDelta ? e.wheelDelta/40 : e.detail ? -e.detail : 0;

        if(delta) {
            var pt = canvasContext.transformedPoint(lastX, lastY);
            var factor = Math.pow(scaleFactor, delta);

            canvasContext.translate(pt.x, pt.y);
            canvasContext.scale(factor, factor);
            canvasContext.translate(-pt.x, -pt.y);
            redraw();
        }

        if(!e.isTouchEvent) {
            return e.preventDefault() && false;
        } else {
            return false;
        }
    };

    // scales correctly at times. At other times it doesn't...
    function scaleCanvas() {
        canvas.width = 0;
        canvas.height = 0;

        setTimeout(function() {
            canvas.width = document.getElementById("VisualWrapper").clientWidth - 34;
            canvas.height = canvas.width / 16 * 9;
            loading.style.display = "block";
            setTimeout(function() {
                redraw();
            }, 1400);
        }, 250);
    }

    function updateValues(element) {
        var r = 0;
        var a = 0;
        var c = 0;

        switch(element) {
            case radiusInput:
                r = radiusInput.value;
                a = Math.PI * Math.pow(r, 2)
                c = 2 * Math.PI * r;
                break;
            case areaInput:
                a = areaInput.value;
                r = Math.sqrt(a / Math.PI);
                c = 2 * Math.PI * r;
                break;
            default:
                break;
        }

        radiusInput.value = r;
        areaInput.value = a;

        circumference.innerHTML = c;
    }

    function clearCanvas() {
        var p1 = canvasContext.transformedPoint(0, 0);
        var p2 = canvasContext.transformedPoint(canvas.width, canvas.height);
        canvasContext.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
        canvasContext.save();
        canvasContext.setTransform(1, 0, 0, 1, 0, 0);
        canvasContext.clearRect(0, 0, canvas.width, canvas.height);
        canvasContext.restore();
    }

    function drawPixel(x, y) {
        canvasContext.rect(x * 4, y * 4, 4, 4);
        canvasContext.fillStyle = "#212121";
        canvasContext.fill();
    }

    function drawGrid() {
        var maxWidth = 2000;
        var maxHeight = 2000;

        canvasContext.beginPath();

        for(var x = -maxWidth; x <= maxWidth; x += 4) {
            canvasContext.moveTo(x, -maxWidth);
            canvasContext.lineTo(x, maxWidth);
        }

        for(var y = -maxHeight; y <= maxHeight; y += 4) {
            canvasContext.moveTo(-maxHeight, y);
            canvasContext.lineTo(maxHeight, y);
        }

        canvasContext.strokeStyle = "#E0E0E0";
        canvasContext.lineWidth = 0.1;
        canvasContext.stroke();
        canvasContext.closePath();

        loading.style.display = "none";
    }

    function draw(radius) {
        radius = Math.round(parseFloat(radius));

        if(!radius || 0 === radius.length || isNaN(radius) && !isFinite(radius)) {
            return;
        }

        var d = Math.round(Math.PI - (2 * radius));
        var x = 0;
        var y = radius;

        canvasContext.beginPath();
        while(x <= y) {
            drawPixel(radius + x + 1, radius - y);
            drawPixel(radius + y + 1, radius - x);
            drawPixel(radius + y + 1, radius + x + 1);
            drawPixel(radius + x + 1, radius + y + 1);
            drawPixel(radius - x, radius + y + 1);
            drawPixel(radius - y, radius + x + 1);
            drawPixel(radius - y, radius - x);
            drawPixel(radius - x, radius - y);

            if(continuous) {
                drawPixel(radius + x + 2, radius - y);
                drawPixel(radius + y + 1, radius - x - 1);
                drawPixel(radius + y + 1, radius + x + 2);
                drawPixel(radius + x + 2, radius + y + 1);
                drawPixel(radius - x - 1, radius + y + 1);
                drawPixel(radius - y, radius + x + 2);
                drawPixel(radius - y, radius - x - 1);
                drawPixel(radius - x - 1, radius - y);
            }

            if (d < 0) {
                d = d + (Math.PI * x) + (Math.PI * 2);
            } else {
                d = d + Math.PI * (x - y) + (Math.PI * 3);
                y--;
            }

            x++;
        }
        canvasContext.closePath();
    }

    function redraw() {
        clearCanvas();
        draw(lastRadius);
        drawGrid();
    }

    if(window.PointerEvent) {
        console.log("Pointer events are supported.");
        canvas.addEventListener("pointerdown", pointerDown, false);
        canvas.addEventListener("pointermove", pointerMove, false);
        canvas.addEventListener("pointerup", pointerUp, false);
    } else {
        console.log("Pointer events not supported. Defaulting to mouse and touch events");
        canvas.addEventListener("mousedown", pointerDown, false);
        canvas.addEventListener("mousemove", pointerMove, false);
        canvas.addEventListener("mouseup", pointerUp, false);

        canvas.addEventListener("touchstart", pointerDown, false);
        canvas.addEventListener("touchmove", pointerMove, false);
        canvas.addEventListener("touchend", pointerUp, false);

        canvas.addEventListener("DOMMouseScroll", handleScroll, false);
        canvas.addEventListener("mousewheel", handleScroll, false);
    }

    continuousSwitch.addEventListener("click", function(e) {
        continuous = continuousSwitch.checked;
    }, false);

    radiusInput.addEventListener("keyup", function(e) {
        updateValues(radiusInput);
    }, false);

    areaInput.addEventListener("keyup", function(e) {
        updateValues(areaInput);
    }, false);

    visualise.addEventListener("click", function(e) {
        clearCanvas();
        loading.style.display = "block";
        lastRadius = radiusInput.value;
        draw(lastRadius);
        drawGrid();
    }, false);

    trackTransforms(canvasContext);
    scaleCanvas();
    window.onresize = scaleCanvas();

    loading.style.display = "none";

    if(isBetaVersion) {
        var betaNotice = document.createElement("span");

        betaNotice.id = "BetaNotice";
        betaNotice.innerHTML = "βῆτα v" + version;
        document.getElementsByTagName("header")[0].getElementsByTagName("h1")[0].appendChild(betaNotice);
    }
};

function trackTransforms(canvasContext) {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    var xform = svg.createSVGMatrix();
    var savedTransforms = [];
    var save = canvasContext.save;
    var restore = canvasContext.restore;
    var scale = canvasContext.scale;
    var translate = canvasContext.translate;
    var setTransform = canvasContext.setTransform;
    var pt  = svg.createSVGPoint();

    canvasContext.save = function() {
        savedTransforms.push(xform.translate(0, 0));
        return save.call(canvasContext);
    };

    canvasContext.restore = function() {
        xform = savedTransforms.pop();
        return restore.call(canvasContext);
    };

    canvasContext.scale = function(sx, sy) {
        xform = xform.scaleNonUniform(sx, sy);
        return scale.call(canvasContext, sx, sy);
    };

    canvasContext.translate = function(dx, dy) {
        xform = xform.translate(dx, dy);
        return translate.call(canvasContext, dx, dy);
    };

    canvasContext.setTransform = function(a, b, c, d, e, f) {
        xform.a = a;
        xform.b = b;
        xform.c = c;
        xform.d = d;
        xform.e = e;
        xform.f = f;

        return setTransform.call(canvasContext, a, b, c, d, e, f);
    };

    canvasContext.transformedPoint = function(x, y) {
        pt.x = x;
        pt.y = y;

        return pt.matrixTransform(xform.inverse());
    };
}
<|endoftext|>


<commit_before>var colors = require('colors/safe');
var exec = require('child_process').exec;
//var execSync = require('exec-sync');

var io = function(error, stdout, stderr) {
  console.log(colors.green(stdout));
  console.log(colors.red(stderr));
};

var ADB = function(data) {
  if (!(this instanceof ADB)) {
    return new ADB(data);
  }
  exec("adb devices", io);
};

var makeShellCommand = function(sms) {
  return "adb shell \"am start -e recipient '" + sms.recipient + "' -e message '" + sms.message + "' 'com.example.tutorialspoint/.MainActivity' && input keyevent 20 && input keyevent 20 && input keyevent 66 && input keyevent 3\"";
};

ADB.prototype.sms = function(sms) {
  // TODO à revoir...
  exec("adb shell dumpsys input_method | grep -Po 'mScreenOn=false' &> /dev/null; if [ $? == 0 ]; then adb shell input keyevent 26; fi");
  var command = makeShellCommand(sms);
  console.log(colors.green(command));
  exec(command);
};

module.exports = {
  getInstance: function(data) {
    return new ADB(data);
  }
};
<commit_msg>added test to wake up phone<commit_after>var colors = require('colors/safe');
var exec = require('child_process').exec;
//var execSync = require('exec-sync');

var io = function(error, stdout, stderr) {
  console.log(colors.green(stdout));
  console.log(colors.red(stderr));
};

var ADB = function(data) {
  if (!(this instanceof ADB)) {
    return new ADB(data);
  }
  exec("adb devices", io);
};

var makeShellCommand = function(sms) {
  return "adb shell \"am start -e recipient '" + sms.recipient + "' -e message '" + sms.message + "' 'com.example.tutorialspoint/.MainActivity' && input keyevent 20 && input keyevent 20 && input keyevent 66 && input keyevent 3\"";
};

ADB.prototype.sms = function(sms) {
  exec("adb shell \"dumpsys input_method | grep -Po 'mScreenOn=false' &> /dev/null; if [ $? == 0 ]; then input keyevent 26; fi;\"", io);
  var command = makeShellCommand(sms);
  console.log(colors.green(command));
  exec(command, io);
};

module.exports = {
  getInstance: function(data) {
    return new ADB(data);
  }
};
<|endoftext|>


<commit_before>import MagnonElement from "../../src/magnon-element.js";

import { html, css } from "../../src/literals.js";

import { MagnonSocialButton } from "./magnon-social-button.js";
import "../magnon-icon/social-set.js";

export { MagnonSocialButton };

const content = html`

    <magnon-social-button></magnon-social-button>

`;

const style = css`
:host {
    display: inline-block;
}
`;

export const createSocialIconButton = (name, icon, color, hrefTemplate, titleTemplate, userTemplate, idURL) => {
    const socialIconButton = class extends MagnonElement {
        constructor() {
            super({ content: content + style });
        }

        static get elementName() {
            return name;
        }

        static get propertyAttributes() {
            return {
                string: ["user", "id"]
            };
        }

        contentReady() {
            this.root.querySelector("#container").style.setProperty(
                "--magnon-icon-color",
                `var(--magnon-social-icon-button-color, ${color})`
            );

            this._button = this.root.querySelector("magnon-social-button");
            this._button.setAttribute("icon", icon);
        }

        propertySet(property, old, value) {
            if (property === "user") {
                if (!idURL) this._button.setAttribute("href", hrefTemplate(value));
                this._button.setAttribute("title", titleTemplate(value));
                this._button.setAttribute("user", userTemplate(value));
            } else if (property === "id" && idURL) {
                this._button.setAttribute("href", hrefTemplate(value));
            }
        }
    };

    socialIconButton.init();
};

const userTmpl = (strings) => user => strings[0] + user + strings[1];

createSocialIconButton(
    "magnon-twitter-button",
    "social-twitter",
    "#1DA1F3",
    userTmpl`https://twitter.com/${0}`,
    userTmpl`Follow @${0} on Twitter!`,
    userTmpl`@${0}`
);

createSocialIconButton(
    "magnon-gplus-button",
    "social-gplus",
    "#DB4437",
    userTmpl`https://plus.google.com/+${0}`,
    userTmpl`Add +${0} on Google+!`,
    userTmpl`+${0}`
);

createSocialIconButton(
    "magnon-twitch-button",
    "social-twitch",
    "#6441A4",
    userTmpl`https://www.twitch.tv/${0}`,
    userTmpl`Follow ${0} on Twitch!`,
    userTmpl`${0}`
);

createSocialIconButton(
    "magnon-youtube-button",
    "social-youtube",
    "#CD201F",
    userTmpl`https://www.youtube.com/channel/${0}`,
    userTmpl`Subscribe to ${0} on YouTube!`,
    userTmpl`${0}`,
    true
);

createSocialIconButton(
    "magnon-github-button",
    "social-github",
    "#171515",
    userTmpl`https://github.com/${0}`,
    userTmpl`Follow ${0} on Github!`,
    userTmpl`${0}`
);

createSocialIconButton(
    "magnon-bitbucket-button",
    "social-bitbucket",
    "#172B4D",
    userTmpl`https://bitbucket.org/${0}/`,
    userTmpl`Check out ${0} on BitBucket`,
    userTmpl`${0}`
);

createSocialIconButton(
    "magnon-feedly-button",
    "social-rss",
    "#101010",
    userTmpl`http://cloud.feedly.com/#subscription/feed/${0}/rss/`,
    userTmpl`Follow ${0} on Feedly!`,
    userTmpl`${0}`,
    true
);
<commit_msg>Support using urls instead of usernames on social buttons<commit_after>import MagnonElement from "../../src/magnon-element.js";

import { html, css } from "../../src/literals.js";

import { MagnonSocialButton } from "./magnon-social-button.js";
import "../magnon-icon/social-set.js";

export { MagnonSocialButton };

const content = html`

    <magnon-social-button></magnon-social-button>

`;

const style = css`
:host {
    display: inline-block;
}
`;

export const createSocialIconButton = (name, icon, color, hrefTemplate, titleTemplate, userTemplate, idURL) => {
    const socialIconButton = class extends MagnonElement {
        constructor() {
            super({ content: content + style });
        }

        static get elementName() {
            return name;
        }

        static get propertyAttributes() {
            return {
                string: ["user", "id"]
            };
        }

        contentReady() {
            this.root.querySelector("#container").style.setProperty(
                "--magnon-icon-color",
                `var(--magnon-social-icon-button-color, ${color})`
            );

            this._button = this.root.querySelector("magnon-social-button");
            this._button.setAttribute("icon", icon);
        }

        propertySet(property, old, value) {
            if (property === "user") {
                const urlRegex = new RegExp(`^${hrefTemplate("(\\w+?)")}$`);
                const regexResult = urlRegex.exec(value.trim());
                if (regexResult) {
                    value = regexResult[1];
                }

                if (!idURL) this._button.setAttribute("href", hrefTemplate(value));
                this._button.setAttribute("title", titleTemplate(value));
                this._button.setAttribute("user", userTemplate(value));
            } else if (property === "id" && idURL) {
                this._button.setAttribute("href", hrefTemplate(value));
            }
        }
    };

    socialIconButton.init();
};

const userTmpl = (strings) => user => strings[0] + user + strings[1];

createSocialIconButton(
    "magnon-twitter-button",
    "social-twitter",
    "#1DA1F3",
    userTmpl`https://twitter.com/${0}`,
    userTmpl`Follow @${0} on Twitter!`,
    userTmpl`@${0}`
);

createSocialIconButton(
    "magnon-gplus-button",
    "social-gplus",
    "#DB4437",
    userTmpl`https://plus.google.com/+${0}`,
    userTmpl`Add +${0} on Google+!`,
    userTmpl`+${0}`
);

createSocialIconButton(
    "magnon-twitch-button",
    "social-twitch",
    "#6441A4",
    userTmpl`https://www.twitch.tv/${0}`,
    userTmpl`Follow ${0} on Twitch!`,
    userTmpl`${0}`
);

createSocialIconButton(
    "magnon-youtube-button",
    "social-youtube",
    "#CD201F",
    userTmpl`https://www.youtube.com/channel/${0}`,
    userTmpl`Subscribe to ${0} on YouTube!`,
    userTmpl`${0}`,
    true
);

createSocialIconButton(
    "magnon-github-button",
    "social-github",
    "#171515",
    userTmpl`https://github.com/${0}`,
    userTmpl`Follow ${0} on Github!`,
    userTmpl`${0}`
);

createSocialIconButton(
    "magnon-bitbucket-button",
    "social-bitbucket",
    "#172B4D",
    userTmpl`https://bitbucket.org/${0}/`,
    userTmpl`Check out ${0} on BitBucket`,
    userTmpl`${0}`
);

createSocialIconButton(
    "magnon-feedly-button",
    "social-rss",
    "#101010",
    userTmpl`http://cloud.feedly.com/#subscription/feed/${0}/rss/`,
    userTmpl`Follow ${0} on Feedly!`,
    userTmpl`${0}`,
    true
);
<|endoftext|>


<commit_before>var browserSync     = require('browser-sync'),
    config          = require('../config/jade'),
    gulp            = require('gulp'),
    handleErrors    = require('../lib/handleErrors'),
    jadeInheritance = require('gulp-jade-inheritance'),
    jade            = require('gulp-jade'),
    changed         = require('gulp-changed'),
    cached          = require('gulp-cached'),
    gulpif          = require('gulp-if'),
    rename          = require('gulp-rename'),
    filter          = require('gulp-filter'),
    inject          = require('gulp-inject'),
    browserSync     = require('browser-sync'),
    gulpif          = require('gulp-if'),
    argv            = require('yargs').argv,
    devel           = argv._[0] === undefined,
    deploy          = argv._[0] === 'deploy';

gulp.task('jade', ['compileJade'], function () {
  var target = gulp.src(config.injectJade);
  // It's not necessary to read the files (will speed up things), we're only after their paths
  var global = gulp.src([
    //Inject assests that only have `shared` in their name
    config.publicAssets + '/styles/**/*shared*.css',
    config.publicAssets + '/js/**/*shared*.js'
  ], {read: false})
  //Filter out any js or css files that have an underscore in file name
  //since we do not want to inject these files into html
  //NOTE: this is only done on produciton
  //This is mainly for buttron since we want a sepearte file during devel
  //avoide lengthy compile times but in production we only want one shared css file
  .pipe(filter(function (file) {
      if(devel){
        return file;
      }else{
        if (!(/\_/g).test(file.relative)) {
          console.log(file)
          return file;
        }
      }
  }));

  return target
    .pipe(inject(global ,{
      relative: true,
      ignorePath: 'dist',
      addRootSlash: false,
      name: 'global',
      //Transforimg file path to cut off the initial `../`
      //there is prbly a better way of doing this. But, this works.
      transform: function (filepath) {
        var newArg = arguments;
        filepath = filepath.substring(3, filepath.length);
        newArg[0] = filepath;
        return inject.transform.apply(inject.transform, newArg);
      },
    }))
    .on('error', handleErrors)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.reload({stream:true}));
});

gulp.task('compileJade', function() {
  return gulp.src(config.src)
    //only pass unchanged *main* files and *all* the partials
    .pipe(changed('dist', {extension: '.html'}))
    //filter out unchanged partials, but it only works when in devel
    .pipe(gulpif(devel, cached('jade')))
    //find files that depend on the files that have changed
    .pipe(jadeInheritance({basedir: './app/views'}))
    //filter out partials (folders and files starting with "_" )
    .pipe(filter(function (file) {
        return !/\/_/.test(file.path) || !/^_/.test(file.relative);
    }))
    .pipe(jade({
      pretty: true
    }))
    .on('error', handleErrors)
    //Remove subPages dirc
    .pipe(rename(function (path) {
      // console.log(arguments)
      var newDir = path.dirname.replace('subPages', '');
      //On deploy to github remove all directories and hifenate them
      if (deploy) {
        if (/(\\|\/)$|^(\\|\/)/.test(newDir)) {
          newDir = newDir.replace('/', '-');
          path.basename = path.basename + newDir;
          newDir = '.';
        }
      }
      path.dirname = newDir;
      return path;
    }))
    .on('error', handleErrors)
    .pipe(gulp.dest(config.publicTemp));
});
<commit_msg>removed <comments></comments><commit_after>var browserSync     = require('browser-sync'),
    config          = require('../config/jade'),
    gulp            = require('gulp'),
    handleErrors    = require('../lib/handleErrors'),
    jadeInheritance = require('gulp-jade-inheritance'),
    jade            = require('gulp-jade'),
    changed         = require('gulp-changed'),
    cached          = require('gulp-cached'),
    gulpif          = require('gulp-if'),
    rename          = require('gulp-rename'),
    filter          = require('gulp-filter'),
    inject          = require('gulp-inject'),
    browserSync     = require('browser-sync'),
    gulpif          = require('gulp-if'),
    argv            = require('yargs').argv,
    devel           = argv._[0] === undefined,
    deploy          = argv._[0] === 'deploy';

gulp.task('jade', ['compileJade'], function () {
  var target = gulp.src(config.injectJade);
  // It's not necessary to read the files (will speed up things), we're only after their paths
  var global = gulp.src([
    //Inject assests that only have `shared` in their name
    config.publicAssets + '/styles/**/*shared*.css',
    config.publicAssets + '/js/**/*shared*.js'
  ], {read: false})
  //Filter out any js or css files that have an underscore in file name
  //since we do not want to inject these files into html
  //NOTE: this is only done on produciton
  //This is mainly for buttron since we want a sepearte file during devel
  //avoide lengthy compile times but in production we only want one shared css file
  .pipe(filter(function (file) {
      if(devel){
        return file;
      }else{
        if (!(/\_/g).test(file.relative)) {
          return file;
        }
      }
  }));

  return target
    .pipe(inject(global ,{
      relative: true,
      ignorePath: 'dist',
      addRootSlash: false,
      name: 'global',
      //Transforimg file path to cut off the initial `../`
      //there is prbly a better way of doing this. But, this works.
      transform: function (filepath) {
        var newArg = arguments;
        filepath = filepath.substring(3, filepath.length);
        newArg[0] = filepath;
        return inject.transform.apply(inject.transform, newArg);
      },
    }))
    .on('error', handleErrors)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.reload({stream:true}));
});

gulp.task('compileJade', function() {
  return gulp.src(config.src)
    //only pass unchanged *main* files and *all* the partials
    .pipe(changed('dist', {extension: '.html'}))
    //filter out unchanged partials, but it only works when in devel
    .pipe(gulpif(devel, cached('jade')))
    //find files that depend on the files that have changed
    .pipe(jadeInheritance({basedir: './app/views'}))
    //filter out partials (folders and files starting with "_" )
    .pipe(filter(function (file) {
        return !/\/_/.test(file.path) || !/^_/.test(file.relative);
    }))
    .pipe(jade({
      pretty: true
    }))
    .on('error', handleErrors)
    //Remove subPages dirc
    .pipe(rename(function (path) {
      var newDir = path.dirname.replace('subPages', '');
      //On deploy to github remove all directories and hifenate them
      if (deploy) {
        if (/(\\|\/)$|^(\\|\/)/.test(newDir)) {
          newDir = newDir.replace('/', '-');
          path.basename = path.basename + newDir;
          newDir = '.';
        }
      }
      path.dirname = newDir;
      return path;
    }))
    .on('error', handleErrors)
    .pipe(gulp.dest(config.publicTemp));
});
<|endoftext|>


<commit_before>const Validation     = require('../form_validation');
const getElementById = require('../../../_common/common_functions').getElementById;
const createElement  = require('../../../_common/utility').createElement;

const cache = {};
const popup_queue = [];

// use this function if you need to show a form with some validations in popup
// if you need a simple popup with just a confirm or also a cancel button use Dialog instead
const showPopup = (options) => {
    if (cache[options.url]) {
        callback(options);
    } else {
        const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState !== 4 || this.status !== 200) {
                return;
            }
            cache[options.url] = this.responseText;
            callback(options);
        };
        xhttp.open('GET', options.url, true);
        xhttp.send();
    }
};

const callback = (options) => {
    const div      = createElement('div', { html: cache[options.url] });
    const lightbox = createElement('div', { id: options.popup_id, class: 'lightbox' });
    lightbox.appendChild(div.querySelector(options.content_id));
    lightbox.addEventListener('DOMNodeRemoved', (e) => {
        if (!popup_queue.length || e.target.className !== 'lightbox') return;
        document.body.appendChild(popup_queue.pop()); // show popup in queue
    });

    const has_lightbox = document.querySelector('.lightbox');
    if (has_lightbox) {
        // store this popup in queue to show it after the previous popup has been removed
        // to avoid having multiple popup showing at the same time
        popup_queue.push(lightbox);
    } else {
        document.body.appendChild(lightbox);
    }

    if (options.validations) {
        Validation.init(options.form_id, options.validations);
    }

    if (typeof options.additionalFunction === 'function') {
        options.additionalFunction(lightbox);
    }

    getElementById(options.form_id.slice(1)).addEventListener('submit', (e) => {
        e.preventDefault();
        if (options.validations) {
            if (Validation.validate(options.form_id)) {
                if (lightbox) {
                    lightbox.remove();
                }
                if (typeof options.onAccept === 'function') {
                    options.onAccept();
                }
            }
        } else if (lightbox) {
            lightbox.remove();
        }
    });
};

module.exports = showPopup;
<commit_msg>fix: don't regenerate existing popup (#6237)<commit_after>const Validation     = require('../form_validation');
const getElementById = require('../../../_common/common_functions').getElementById;
const createElement  = require('../../../_common/utility').createElement;

const cache = {};
const popup_queue = [];

// use this function if you need to show a form with some validations in popup
// if you need a simple popup with just a confirm or also a cancel button use Dialog instead
const showPopup = (options) => {
    const el_popup = document.getElementById(options.popup_id);

    if (el_popup){
        return;
    }
    if (cache[options.url]) {
        callback(options);
    } else {
        const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState !== 4 || this.status !== 200) {
                return;
            }
            cache[options.url] = this.responseText;
            callback(options);
        };
        xhttp.open('GET', options.url, true);
        xhttp.send();
    }
};

const callback = (options) => {
    const div      = createElement('div', { html: cache[options.url] });
    const lightbox = createElement('div', { id: options.popup_id, class: 'lightbox' });
    lightbox.appendChild(div.querySelector(options.content_id));
    lightbox.addEventListener('DOMNodeRemoved', (e) => {
        if (!popup_queue.length || e.target.className !== 'lightbox') return;
        document.body.appendChild(popup_queue.pop()); // show popup in queue
    });

    const has_lightbox = document.querySelector('.lightbox');
    if (has_lightbox) {
        // store this popup in queue to show it after the previous popup has been removed
        // to avoid having multiple popup showing at the same time
        popup_queue.push(lightbox);
    } else {
        document.body.appendChild(lightbox);
    }

    if (options.validations) {
        Validation.init(options.form_id, options.validations);
    }

    if (typeof options.additionalFunction === 'function') {
        options.additionalFunction(lightbox);
    }

    getElementById(options.form_id.slice(1)).addEventListener('submit', (e) => {
        e.preventDefault();
        if (options.validations) {
            if (Validation.validate(options.form_id)) {
                if (lightbox) {
                    lightbox.remove();
                }
                if (typeof options.onAccept === 'function') {
                    options.onAccept();
                }
            }
        } else if (lightbox) {
            lightbox.remove();
        }
    });
};

module.exports = showPopup;
<|endoftext|>