<commit_before>
/* A rectangular panel that is absolutely positioned over other content
------------------------------------------------------------------------------------------------------------------------
Options:
	- className (string)
	- content (HTML string or jQuery element set)
	- parentEl
	- top
	- left
	- right (the x coord of where the right edge should be. not a "CSS" right)
	- autoHide (boolean)
	- show (callback)
	- hide (callback)
*/

var Popover = Class.extend(ListenerMixin, {

	isHidden: true,
	options: null,
	el: null, // the container element for the popover. generated by this object
	margin: 10, // the space required between the popover and the edges of the scroll container

	constructor: function(options) {
		this.options = options || {};
	},

	// Shows the popover on the specified position. Renders it if not already
	show: function() {
		if (this.isHidden) {
			if (!this.el) {
				this.render();
			}
			this.el.show();
			this.position();
			this.isHidden = false;
			this.trigger('show');
		}
	},

	// Hides the popover, through CSS, but does not remove it from the DOM
	hide: function() {
		if (!this.isHidden) {
			this.el.hide();
			this.isHidden = true;
			this.trigger('hide');
		}
	},

	// Creates `this.el` and renders content inside of it
	render: function() {
		var _this = this;
		var options = this.options;

		this.el = $('
')
			.addClass(options.className || '')
			.css({
				// position initially to the top left to avoid creating scrollbars
				top: 0,
				left: 0
			})
			.append(options.content)
			.appendTo(options.parentEl);

		// when a click happens on anything inside with a 'fc-close' className, hide the popover
		this.el.on('click', '.fc-close', function() {
			_this.hide();
		});

		if (options.autoHide) {
			this.listenTo($(document), 'mousedown', this.documentMousedown);
		}
	},

	// Triggered when the user clicks *anywhere* in the document, for the autoHide feature
	documentMousedown: function(ev) {
		// only hide the popover if the click happened outside the popover
		if (this.el && !$(ev.target).closest(this.el).length) {
			this.hide();
		}
	},

	// Hides and unregisters any handlers
	removeElement: function() {
		this.hide();

		if (this.el) {
			this.el.remove();
			this.el = null;
		}

		this.stopListeningTo($(document), 'mousedown');
	},

	// Positions the popover optimally, using the top/left/right options
	position: function() {
		var options = this.options;
		var origin = this.el.offsetParent().offset();
		var width = this.el.outerWidth();
		var height = this.el.outerHeight();
		var windowEl = $(window);
		var viewportEl = getScrollParent(this.el);
		var viewportTop;
		var viewportLeft;
		var viewportOffset;
		var top; // the "position" (not "offset") values for the popover
		var left; //

		// compute top and left
		top = options.top || 0;
		if (options.left !== undefined) {
			left = options.left;
		}
		else if (options.right !== undefined) {
			left = options.right - width; // derive the left value from the right value
		}
		else {
			left = 0;
		}

		if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
			viewportEl = windowEl;
			viewportTop = 0; // the window is always at the top left
			viewportLeft = 0; // (and .offset() won't work if called here)
		}
		else {
			viewportOffset = viewportEl.offset();
			viewportTop = viewportOffset.top;
			viewportLeft = viewportOffset.left;
		}

		// if the window is scrolled, it causes the visible area to be further down
		viewportTop += windowEl.scrollTop();
		viewportLeft += windowEl.scrollLeft();

		// constrain to the view port. if constrained by two edges, give precedence to top/left
		if (options.viewportConstrain !== false) {
			top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
			top = Math.max(top, viewportTop + this.margin);
			left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
			left = Math.max(left, viewportLeft + this.margin);
		}

		this.el.css({
			top: top - origin.top,
			left: left - origin.left
		});
	},

	// Triggers a callback. Calls a function in the option hash of the same name.
	// Arguments beyond the first `name` are forwarded on.
	// TODO: better code reuse for this. Repeat code
	trigger: function(name) {
		if (this.options[name]) {
			this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
		}
	}

});
<commit_msg>stop native touch selection on popover<commit_after>
/* A rectangular panel that is absolutely positioned over other content
------------------------------------------------------------------------------------------------------------------------
Options:
	- className (string)
	- content (HTML string or jQuery element set)
	- parentEl
	- top
	- left
	- right (the x coord of where the right edge should be. not a "CSS" right)
	- autoHide (boolean)
	- show (callback)
	- hide (callback)
*/

var Popover = Class.extend(ListenerMixin, {

	isHidden: true,
	options: null,
	el: null, // the container element for the popover. generated by this object
	margin: 10, // the space required between the popover and the edges of the scroll container

	constructor: function(options) {
		this.options = options || {};
	},

	// Shows the popover on the specified position. Renders it if not already
	show: function() {
		if (this.isHidden) {
			if (!this.el) {
				this.render();
			}
			this.el.show();
			this.position();
			this.isHidden = false;
			this.trigger('show');
		}
	},

	// Hides the popover, through CSS, but does not remove it from the DOM
	hide: function() {
		if (!this.isHidden) {
			this.el.hide();
			this.isHidden = true;
			this.trigger('hide');
		}
	},

	// Creates `this.el` and renders content inside of it
	render: function() {
		var _this = this;
		var options = this.options;

		this.el = $('
')
			.addClass(options.className || '')
			.css({
				// position initially to the top left to avoid creating scrollbars
				top: 0,
				left: 0
			})
			.append(options.content)
			.appendTo(options.parentEl);

		// prevent a touch-related native selection
		preventSelection(this.el);

		// when a click happens on anything inside with a 'fc-close' className, hide the popover
		this.el.on('click', '.fc-close', function() {
			_this.hide();
		});

		if (options.autoHide) {
			this.listenTo($(document), 'mousedown', this.documentMousedown);
		}
	},

	// Triggered when the user clicks *anywhere* in the document, for the autoHide feature
	documentMousedown: function(ev) {
		// only hide the popover if the click happened outside the popover
		if (this.el && !$(ev.target).closest(this.el).length) {
			this.hide();
		}
	},

	// Hides and unregisters any handlers
	removeElement: function() {
		this.hide();

		if (this.el) {
			this.el.remove();
			this.el = null;
		}

		this.stopListeningTo($(document), 'mousedown');
	},

	// Positions the popover optimally, using the top/left/right options
	position: function() {
		var options = this.options;
		var origin = this.el.offsetParent().offset();
		var width = this.el.outerWidth();
		var height = this.el.outerHeight();
		var windowEl = $(window);
		var viewportEl = getScrollParent(this.el);
		var viewportTop;
		var viewportLeft;
		var viewportOffset;
		var top; // the "position" (not "offset") values for the popover
		var left; //

		// compute top and left
		top = options.top || 0;
		if (options.left !== undefined) {
			left = options.left;
		}
		else if (options.right !== undefined) {
			left = options.right - width; // derive the left value from the right value
		}
		else {
			left = 0;
		}

		if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
			viewportEl = windowEl;
			viewportTop = 0; // the window is always at the top left
			viewportLeft = 0; // (and .offset() won't work if called here)
		}
		else {
			viewportOffset = viewportEl.offset();
			viewportTop = viewportOffset.top;
			viewportLeft = viewportOffset.left;
		}

		// if the window is scrolled, it causes the visible area to be further down
		viewportTop += windowEl.scrollTop();
		viewportLeft += windowEl.scrollLeft();

		// constrain to the view port. if constrained by two edges, give precedence to top/left
		if (options.viewportConstrain !== false) {
			top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
			top = Math.max(top, viewportTop + this.margin);
			left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
			left = Math.max(left, viewportLeft + this.margin);
		}

		this.el.css({
			top: top - origin.top,
			left: left - origin.left
		});
	},

	// Triggers a callback. Calls a function in the option hash of the same name.
	// Arguments beyond the first `name` are forwarded on.
	// TODO: better code reuse for this. Repeat code
	trigger: function(name) {
		if (this.options[name]) {
			this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
		}
	}

});
<|endoftext|>


<commit_before>var Auditor = function() {

  var self = this;
  var deviceId = Ti.Platform.getId();
  var auditFileName = "audit-" + deviceId + ".log";
  var auditUrl = Ti.App.Properties.getString('server_url') + '/api/audits';

  var getFile = function() {
    return Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, auditFileName);
  };

  var getPlatformData = function() {
    return {
      version : Ti.Platform.getVersion(),
      processorCount : Ti.Platform.getProcessorCount(),
      name : Ti.Platform.getName(),
      model : Ti.Platform.getModel(),
      manufacturer : Ti.Platform.getManufacturer(),
      macaddress : Ti.Platform.getMacaddress(),
      id : deviceId,
      batteryLevel : Ti.Platform.getBatteryLevel(),
      availableMemory : Ti.Platform.getAvailableMemory(),
      address : Ti.Platform.getAddress()
    };
  };

  var readFile = function() {
    var file = getFile();
    var content = file.read();
    file = null;
    return content.text;
  };

  self.writeIntoAuditFile = function(text) {
    var file = getFile();
    file.write("\n" + text, true);
    file = null;
  };

  self.sendAuditFile = function() {
    var client = Ti.Network.createHTTPClient();
    client.onload = function(){alert("audit send success");};
    client.onerror = function(){alert("error");};
    client.open("POST", auditUrl);
    client.send({
      device_id : deviceId,
      content :  readFile(),
      platform_data : getPlatformData()
    });
  };

  return self;
};

module.exports = new Auditor();
<commit_msg>Do a PUT request if the device's audit file has been sync'd once.<commit_after>var Auditor = function() {

  var self = this;
  var deviceId = Ti.Platform.getId();
  var auditFileName = "audit-" + deviceId + ".log";
  var auditUrl = Ti.App.Properties.getString('server_url') + '/api/audits';

  self.firstAudit = Ti.App.Properties.getString('firstAudit') === null ? true : false;

  setNotFirstAudit = function(){
    self.firstAudit = false;
    Ti.App.Properties.setString('firstAudit', false);
  };

  var getFile = function() {
    return Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, auditFileName);
  };

  var getPlatformData = function() {
    return {
      version : Ti.Platform.getVersion(),
      processorCount : Ti.Platform.getProcessorCount(),
      name : Ti.Platform.getName(),
      model : Ti.Platform.getModel(),
      manufacturer : Ti.Platform.getManufacturer(),
      macaddress : Ti.Platform.getMacaddress(),
      id : deviceId,
      batteryLevel : Ti.Platform.getBatteryLevel(),
      availableMemory : Ti.Platform.getAvailableMemory(),
      address : Ti.Platform.getAddress()
    };
  };

  var readFile = function() {
    var file = getFile();
    var content = file.read();
    file = null;
    return content.text;
  };

  var truncateAuditFile = function() {
    var file = getFile();
    file.write("");
    file = null;
  };

  var params = function() {
    var params = {
      device_id : deviceId,
      content :  readFile()
    };
    if(self.firstAudit)
      params['platform_data'] = getPlatformData();
    return params;
  };

  self.writeIntoAuditFile = function(text) {
    var file = getFile();
    file.write("\n" + (new Date()).toString(), true);
    file.write(" : " + text, true);
    file = null;
  };

  self.sendAuditFile = function() {
    var client = Ti.Network.createHTTPClient();
    var requestMethod = self.firstAudit ? "POST" : "PUT";
    client.onload = function(){
      truncateAuditFile();
      setNotFirstAudit();
    };
    client.onerror = function(){alert("error");};
    client.open(requestMethod, auditUrl);
    client.send(params());
  };

  return self;
};

module.exports = new Auditor();
<|endoftext|>


<commit_before>/**
 * @license
 * NoSleep.js v0.5.0 - git.io/vfn01
 * Rich Tibbett
 * MIT license
 **/
/*global define*/
define(function() {
    "use strict";

    // UA matching
    var ua = {
        Android: /Android/ig.test(navigator.userAgent),
        iOS: /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent)
    };

    var media = {
        WebM: "data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=",
        MP4: "data:video/mp4;base64,AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAG21kYXQAAAGzABAHAAABthADAowdbb9/AAAC6W1vb3YAAABsbXZoZAAAAAB8JbCAfCWwgAAAA+gAAAAAAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIVdHJhawAAAFx0a2hkAAAAD3wlsIB8JbCAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAIAAAACAAAAAABsW1kaWEAAAAgbWRoZAAAAAB8JbCAfCWwgAAAA+gAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAVxtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEcc3RibAAAALhzdHNkAAAAAAAAAAEAAACobXA0dgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAIAAgASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAFJlc2RzAAAAAANEAAEABDwgEQAAAAADDUAAAAAABS0AAAGwAQAAAbWJEwAAAQAAAAEgAMSNiB9FAEQBFGMAAAGyTGF2YzUyLjg3LjQGAQIAAAAYc3R0cwAAAAAAAAABAAAAAQAAAAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAFHN0c3oAAAAAAAAAEwAAAAEAAAAUc3RjbwAAAAAAAAABAAAALAAAAGB1ZHRhAAAAWG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAK2lsc3QAAAAjqXRvbwAAABtkYXRhAAAAAQAAAABMYXZmNTIuNzguMw=="
    };

    function addSourceToVideo(element, type, dataURI) {
        var source = document.createElement('source');
        source.src = dataURI;
        source.type = "video/" + type;
        element.appendChild(source);
    }

    // NoSleep instance constructor
    var NoSleep = function() {
        if (ua.iOS) {
            this.noSleepTimer = null;
        } else if (ua.Android) {
            // Set up no sleep video element
            this.noSleepVideo = document.createElement('video');
            this.noSleepVideo.setAttribute("loop", "");

            // Append nosleep video sources
            addSourceToVideo(this.noSleepVideo, "webm", media.WebM);
            addSourceToVideo(this.noSleepVideo, "mp4", media.MP4);
        }

        return this;
    };

    // Enable NoSleep instance
    NoSleep.prototype.enable = function(duration) {
        if (ua.iOS) {
            this.disable();
            this.noSleepTimer = window.setInterval(function() {
                window.location = window.location;
                window.setTimeout(window.stop, 0);
            }, duration || 15000);
        } else if (ua.Android) {
            this.noSleepVideo.play();
        }
    };

    // Disable NoSleep instance
    NoSleep.prototype.disable = function() {
        if (ua.iOS) {
            if (this.noSleepTimer) {
                window.clearInterval(this.noSleepTimer);
                this.noSleepTimer = null;
            }
        } else if (ua.Android) {
            this.noSleepVideo.pause();
        }
    };

    // Append NoSleep API to root object
    //root.NoSleep = NoSleep;

    return NoSleep;
});
<commit_msg>check if navigator is undefined<commit_after>/**
 * @license
 * NoSleep.js v0.5.0 - git.io/vfn01
 * Rich Tibbett
 * MIT license
 **/
/*global define*/
define(function() {
    "use strict";

    // UA matching
    var ua = {
        Android: typeof navigator !== 'undefined' && /Android/ig.test(navigator.userAgent),
        iOS: typeof navigator !== 'undefined' && /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent)
    };

    var media = {
        WebM: "data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=",
        MP4: "data:video/mp4;base64,AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAG21kYXQAAAGzABAHAAABthADAowdbb9/AAAC6W1vb3YAAABsbXZoZAAAAAB8JbCAfCWwgAAAA+gAAAAAAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIVdHJhawAAAFx0a2hkAAAAD3wlsIB8JbCAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAIAAAACAAAAAABsW1kaWEAAAAgbWRoZAAAAAB8JbCAfCWwgAAAA+gAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAVxtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEcc3RibAAAALhzdHNkAAAAAAAAAAEAAACobXA0dgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAIAAgASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAFJlc2RzAAAAAANEAAEABDwgEQAAAAADDUAAAAAABS0AAAGwAQAAAbWJEwAAAQAAAAEgAMSNiB9FAEQBFGMAAAGyTGF2YzUyLjg3LjQGAQIAAAAYc3R0cwAAAAAAAAABAAAAAQAAAAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAFHN0c3oAAAAAAAAAEwAAAAEAAAAUc3RjbwAAAAAAAAABAAAALAAAAGB1ZHRhAAAAWG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAK2lsc3QAAAAjqXRvbwAAABtkYXRhAAAAAQAAAABMYXZmNTIuNzguMw=="
    };

    function addSourceToVideo(element, type, dataURI) {
        var source = document.createElement('source');
        source.src = dataURI;
        source.type = "video/" + type;
        element.appendChild(source);
    }

    // NoSleep instance constructor
    var NoSleep = function() {
        if (ua.iOS) {
            this.noSleepTimer = null;
        } else if (ua.Android) {
            // Set up no sleep video element
            this.noSleepVideo = document.createElement('video');
            this.noSleepVideo.setAttribute("loop", "");

            // Append nosleep video sources
            addSourceToVideo(this.noSleepVideo, "webm", media.WebM);
            addSourceToVideo(this.noSleepVideo, "mp4", media.MP4);
        }

        return this;
    };

    // Enable NoSleep instance
    NoSleep.prototype.enable = function(duration) {
        if (ua.iOS) {
            this.disable();
            this.noSleepTimer = window.setInterval(function() {
                window.location = window.location;
                window.setTimeout(window.stop, 0);
            }, duration || 15000);
        } else if (ua.Android) {
            this.noSleepVideo.play();
        }
    };

    // Disable NoSleep instance
    NoSleep.prototype.disable = function() {
        if (ua.iOS) {
            if (this.noSleepTimer) {
                window.clearInterval(this.noSleepTimer);
                this.noSleepTimer = null;
            }
        } else if (ua.Android) {
            this.noSleepVideo.pause();
        }
    };

    // Append NoSleep API to root object
    //root.NoSleep = NoSleep;

    return NoSleep;
});
<|endoftext|>


<commit_before>'use strict';

const expect = require('chai').expect;
const sinon = require('sinon');
const _ = require('lodash');

describe('registry : routes : helpers : nested-renderer', () => {
  const NestedRenderer =
    require('../../dist/registry/domain/nested-renderer').default;

  let nestedRenderer;
  let renderer;

  const initialise = function (rendererMocks, conf) {
    if (Array.isArray(rendererMocks)) {
      renderer = sinon.stub();

      _.each(rendererMocks, (rendererMock, i) => {
        renderer.onCall(i).yields(rendererMock);
      });
    } else {
      renderer = sinon.stub().yields(rendererMocks);
    }

    nestedRenderer = NestedRenderer(renderer, conf || {});
  };

  describe('when rendering nested component', () => {
    describe('when req is not valid', () => {
      describe('when componentName not valid', () => {
        beforeEach(() => {
          initialise();
        });

        it('should throw an error', () => {
          const f = function () {
            nestedRenderer.renderComponent();
          };
          expect(f).to.throw("component's name is not valid");
        });
      });

      describe('when componentName empty', () => {
        beforeEach(() => {
          initialise();
        });

        it('should throw an error', () => {
          const f = function () {
            nestedRenderer.renderComponent('');
          };
          expect(f).to.throw("component's name is not valid");
        });
      });

      describe('when requesting a not existent component', () => {
        let error;
        beforeEach(done => {
          initialise({
            status: 404,
            response: {
              error: 'Component not found 404'
            }
          });

          nestedRenderer
            .renderComponent('404-component', {})
            .catch(err => (error = err))
            .finally(done);
        });

        it('should return an error in the callback', () => {
          expect(error).to.equal('Component not found 404');
        });
      });
    });

    describe('when req is valid', () => {
      describe('when all params specified', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise(
            {
              status: 200,
              response: {
                html: 'Some html'
              }
            },
            { bla: 'blabla' }
          );

          nestedRenderer
            .renderComponent('my-component', {
              headers: {
                'accept-language': 'en-GB',
                accept: 'blargh'
              },
              parameters: { a: 1234 },
              version: '1.2.X'
            })
            .then(res => (result = res))
            .catch(err => (error = err))
            .finally(done);
        });

        it('should get the html result', () => {
          expect(result).to.equal('Some html');
        });

        it('should make correct request to renderer', () => {
          expect(renderer.args[0][0]).to.eql({
            name: 'my-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: {
              'accept-language': 'en-GB',
              accept: 'application/vnd.oc.rendered+json'
            },
            parameters: { a: 1234 },
            version: '1.2.X'
          });
        });

        it('should get no error', () => {
          expect(error).to.be.undefined;
        });
      });

      describe('when minimal params specified', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise(
            {
              status: 200,
              response: {
                html: 'Some html'
              }
            },
            { bla: 'blabla' }
          );

          nestedRenderer
            .renderComponent('my-component')
            .then(res => (result = res))
            .catch(err => (error = err))
            .finally(done);
        });

        it('should get the html result', () => {
          expect(result).to.equal('Some html');
        });

        it('should make correct request to renderer', () => {
          expect(renderer.args[0][0]).to.eql({
            name: 'my-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: {
              accept: 'application/vnd.oc.rendered+json'
            },
            parameters: {},
            version: ''
          });
        });

        it('should get no error', () => {
          expect(error).to.be.undefined;
        });
      });
    });
  });

  describe('when rendering nested components', () => {
    describe('when req is not valid', () => {
      describe('when components not valid', () => {
        beforeEach(() => {
          initialise();
        });

        it('should throw an error', () => {
          const f = function () {
            nestedRenderer.renderComponents();
          };
          expect(f).to.throw('components is not valid');
        });
      });

      describe('when components empty', () => {
        beforeEach(() => {
          initialise();
        });

        it('should throw an error', () => {
          const f = function () {
            nestedRenderer.renderComponents([]);
          };
          expect(f).to.throw('components is not valid');
        });
      });

      describe('when requesting not existent components', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise({
            status: 404,
            response: {
              error: 'Component not found!'
            }
          });

          nestedRenderer
            .renderComponents(
              [
                { name: '404-component' },
                { name: 'another-not-existent-component' }
              ],
              {}
            )
            .then(res => {
              console.log('RES:', res);
              result = res;
            })
            .catch(err => {
              console.log('HI:', err);
              error = err;
            })
            .finally(done);
        });

        it('should return no error in the callback', () => {
          expect(error).to.be.undefined;
        });

        it('should return error in result callback', () => {
          expect(result[0].toString()).to.equal('Error: Component not found!');
          expect(result[1].toString()).to.equal('Error: Component not found!');
        });
      });
    });

    describe('when req is valid', () => {
      describe('when all params specified', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise(
            [
              {
                status: 200,
                response: { html: 'Some html' }
              },
              {
                status: 200,
                response: { html: 'Some other html' }
              }
            ],
            { bla: 'blabla' }
          );

          nestedRenderer
            .renderComponents(
              [
                {
                  name: 'my-component',
                  parameters: { x: 123 },
                  version: '1.2.X'
                },
                {
                  name: 'my-other-component',
                  parameters: { y: 456 },
                  version: '^1.4.6'
                }
              ],
              {
                headers: {
                  'accept-language': 'en-GB',
                  accept: 'blargh'
                },
                parameters: {
                  x: 456,
                  z: 789
                }
              }
            )
            .then(res => (result = res))
            .catch(err => (error = err))
            .finally(done);
        });

        it('should get the html result', () => {
          expect(result).to.eql(['Some html', 'Some other html']);
        });

        it('should make correct request to renderer', () => {
          expect(renderer.args.length).to.equal(2);

          expect(renderer.args[0][0]).to.eql({
            name: 'my-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: {
              'accept-language': 'en-GB',
              accept: 'application/vnd.oc.rendered+json'
            },
            parameters: {
              x: 123,
              z: 789
            },
            version: '1.2.X'
          });

          expect(renderer.args[1][0]).to.eql({
            name: 'my-other-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: {
              'accept-language': 'en-GB',
              accept: 'application/vnd.oc.rendered+json'
            },
            parameters: {
              x: 456,
              y: 456,
              z: 789
            },
            version: '^1.4.6'
          });
        });

        it('should get no error', () => {
          expect(error).to.be.undefined;
        });
      });

      describe('when minimal params specified', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise(
            [
              {
                status: 200,
                response: { html: 'Some html' }
              },
              {
                status: 200,
                response: { html: 'Some other html' }
              }
            ],
            { bla: 'blabla' }
          );

          nestedRenderer
            .renderComponents([
              { name: 'my-component' },
              { name: 'my-other-component' }
            ])
            .then(res => (result = res))
            .catch(err => (error = err))
            .finally(done);
        });

        it('should get the html result', () => {
          expect(result).to.eql(['Some html', 'Some other html']);
        });

        it('should make correct request to renderer', () => {
          expect(renderer.args.length).to.equal(2);

          expect(renderer.args[0][0]).to.eql({
            name: 'my-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: { accept: 'application/vnd.oc.rendered+json' },
            parameters: {},
            version: ''
          });

          expect(renderer.args[1][0]).to.eql({
            name: 'my-other-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: { accept: 'application/vnd.oc.rendered+json' },
            parameters: {},
            version: ''
          });
        });

        it('should get no error', () => {
          expect(error).to.be.undefined;
        });
      });
    });
  });
});
<commit_msg>Remove console.logs on tests<commit_after>'use strict';

const expect = require('chai').expect;
const sinon = require('sinon');
const _ = require('lodash');

describe('registry : routes : helpers : nested-renderer', () => {
  const NestedRenderer =
    require('../../dist/registry/domain/nested-renderer').default;

  let nestedRenderer;
  let renderer;

  const initialise = function (rendererMocks, conf) {
    if (Array.isArray(rendererMocks)) {
      renderer = sinon.stub();

      _.each(rendererMocks, (rendererMock, i) => {
        renderer.onCall(i).yields(rendererMock);
      });
    } else {
      renderer = sinon.stub().yields(rendererMocks);
    }

    nestedRenderer = NestedRenderer(renderer, conf || {});
  };

  describe('when rendering nested component', () => {
    describe('when req is not valid', () => {
      describe('when componentName not valid', () => {
        beforeEach(() => {
          initialise();
        });

        it('should throw an error', () => {
          const f = function () {
            nestedRenderer.renderComponent();
          };
          expect(f).to.throw("component's name is not valid");
        });
      });

      describe('when componentName empty', () => {
        beforeEach(() => {
          initialise();
        });

        it('should throw an error', () => {
          const f = function () {
            nestedRenderer.renderComponent('');
          };
          expect(f).to.throw("component's name is not valid");
        });
      });

      describe('when requesting a not existent component', () => {
        let error;
        beforeEach(done => {
          initialise({
            status: 404,
            response: {
              error: 'Component not found 404'
            }
          });

          nestedRenderer
            .renderComponent('404-component', {})
            .catch(err => (error = err))
            .finally(done);
        });

        it('should return an error in the callback', () => {
          expect(error).to.equal('Component not found 404');
        });
      });
    });

    describe('when req is valid', () => {
      describe('when all params specified', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise(
            {
              status: 200,
              response: {
                html: 'Some html'
              }
            },
            { bla: 'blabla' }
          );

          nestedRenderer
            .renderComponent('my-component', {
              headers: {
                'accept-language': 'en-GB',
                accept: 'blargh'
              },
              parameters: { a: 1234 },
              version: '1.2.X'
            })
            .then(res => (result = res))
            .catch(err => (error = err))
            .finally(done);
        });

        it('should get the html result', () => {
          expect(result).to.equal('Some html');
        });

        it('should make correct request to renderer', () => {
          expect(renderer.args[0][0]).to.eql({
            name: 'my-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: {
              'accept-language': 'en-GB',
              accept: 'application/vnd.oc.rendered+json'
            },
            parameters: { a: 1234 },
            version: '1.2.X'
          });
        });

        it('should get no error', () => {
          expect(error).to.be.undefined;
        });
      });

      describe('when minimal params specified', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise(
            {
              status: 200,
              response: {
                html: 'Some html'
              }
            },
            { bla: 'blabla' }
          );

          nestedRenderer
            .renderComponent('my-component')
            .then(res => (result = res))
            .catch(err => (error = err))
            .finally(done);
        });

        it('should get the html result', () => {
          expect(result).to.equal('Some html');
        });

        it('should make correct request to renderer', () => {
          expect(renderer.args[0][0]).to.eql({
            name: 'my-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: {
              accept: 'application/vnd.oc.rendered+json'
            },
            parameters: {},
            version: ''
          });
        });

        it('should get no error', () => {
          expect(error).to.be.undefined;
        });
      });
    });
  });

  describe('when rendering nested components', () => {
    describe('when req is not valid', () => {
      describe('when components not valid', () => {
        beforeEach(() => {
          initialise();
        });

        it('should throw an error', () => {
          const f = function () {
            nestedRenderer.renderComponents();
          };
          expect(f).to.throw('components is not valid');
        });
      });

      describe('when components empty', () => {
        beforeEach(() => {
          initialise();
        });

        it('should throw an error', () => {
          const f = function () {
            nestedRenderer.renderComponents([]);
          };
          expect(f).to.throw('components is not valid');
        });
      });

      describe('when requesting not existent components', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise({
            status: 404,
            response: {
              error: 'Component not found!'
            }
          });

          nestedRenderer
            .renderComponents(
              [
                { name: '404-component' },
                { name: 'another-not-existent-component' }
              ],
              {}
            )
            .then(res => {
              result = res;
            })
            .catch(err => {
              error = err;
            })
            .finally(done);
        });

        it('should return no error in the callback', () => {
          expect(error).to.be.undefined;
        });

        it('should return error in result callback', () => {
          expect(result[0].toString()).to.equal('Error: Component not found!');
          expect(result[1].toString()).to.equal('Error: Component not found!');
        });
      });
    });

    describe('when req is valid', () => {
      describe('when all params specified', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise(
            [
              {
                status: 200,
                response: { html: 'Some html' }
              },
              {
                status: 200,
                response: { html: 'Some other html' }
              }
            ],
            { bla: 'blabla' }
          );

          nestedRenderer
            .renderComponents(
              [
                {
                  name: 'my-component',
                  parameters: { x: 123 },
                  version: '1.2.X'
                },
                {
                  name: 'my-other-component',
                  parameters: { y: 456 },
                  version: '^1.4.6'
                }
              ],
              {
                headers: {
                  'accept-language': 'en-GB',
                  accept: 'blargh'
                },
                parameters: {
                  x: 456,
                  z: 789
                }
              }
            )
            .then(res => (result = res))
            .catch(err => (error = err))
            .finally(done);
        });

        it('should get the html result', () => {
          expect(result).to.eql(['Some html', 'Some other html']);
        });

        it('should make correct request to renderer', () => {
          expect(renderer.args.length).to.equal(2);

          expect(renderer.args[0][0]).to.eql({
            name: 'my-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: {
              'accept-language': 'en-GB',
              accept: 'application/vnd.oc.rendered+json'
            },
            parameters: {
              x: 123,
              z: 789
            },
            version: '1.2.X'
          });

          expect(renderer.args[1][0]).to.eql({
            name: 'my-other-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: {
              'accept-language': 'en-GB',
              accept: 'application/vnd.oc.rendered+json'
            },
            parameters: {
              x: 456,
              y: 456,
              z: 789
            },
            version: '^1.4.6'
          });
        });

        it('should get no error', () => {
          expect(error).to.be.undefined;
        });
      });

      describe('when minimal params specified', () => {
        let result;
        let error;
        beforeEach(done => {
          initialise(
            [
              {
                status: 200,
                response: { html: 'Some html' }
              },
              {
                status: 200,
                response: { html: 'Some other html' }
              }
            ],
            { bla: 'blabla' }
          );

          nestedRenderer
            .renderComponents([
              { name: 'my-component' },
              { name: 'my-other-component' }
            ])
            .then(res => (result = res))
            .catch(err => (error = err))
            .finally(done);
        });

        it('should get the html result', () => {
          expect(result).to.eql(['Some html', 'Some other html']);
        });

        it('should make correct request to renderer', () => {
          expect(renderer.args.length).to.equal(2);

          expect(renderer.args[0][0]).to.eql({
            name: 'my-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: { accept: 'application/vnd.oc.rendered+json' },
            parameters: {},
            version: ''
          });

          expect(renderer.args[1][0]).to.eql({
            name: 'my-other-component',
            ip: '',
            conf: { bla: 'blabla' },
            headers: { accept: 'application/vnd.oc.rendered+json' },
            parameters: {},
            version: ''
          });
        });

        it('should get no error', () => {
          expect(error).to.be.undefined;
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright 2011 eBay Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
var extend = require('raptor-util').extend;
var forEachEntry = require('raptor-util').forEachEntry;
var stringify = require('raptor-json/stringify');

function addHandlerVar(template, renderer) {
    var handlerVars = template._handlerVars || (template._handlerVars = {});
    var handlerVar = handlerVars[renderer];
    if (!handlerVar) {
        handlerVars[renderer] = handlerVar = renderer.replace(/[.\-\/]/g, '_').replace(/^[_]+/g, '');
        template.addStaticVar(handlerVar, 'require(' + stringify(renderer) + ')');
    }
    return handlerVar;
}
function getPropsStr(props, template) {
    var propsArray = [];
    if (props) {
        template.indent(function () {
            forEachEntry(props, function (name, value) {
                if (template.isExpression(value)) {
                    var expressionStr;
                    template.indent(function () {
                        expressionStr = value.expression.toString();
                    });
                    propsArray.push(template.indentStr() + stringify(name) + ': ' + expressionStr);
                } else if (typeof value === 'string' || typeof value === 'object') {
                    propsArray.push(template.indentStr() + stringify(name) + ': ' + stringify(value));
                } else {
                    propsArray.push(template.indentStr() + stringify(name) + ': ' + value);
                }
            });
        });

        if (propsArray.length) {
            return '{\n' + propsArray.join(',\n') + '\n' + template.indentStr() + '}';
        } else {
            return '{}';
        }
    } else {
        return '{}';
    }
}
function TagHandlerNode(tag) {
    if (!this.nodeType) {
        TagHandlerNode.$super.call(this);
    }
    this.tag = tag;
    this.dynamicAttributes = null;
    this.inputExpression = null;
}
TagHandlerNode.nodeType = 'element';

TagHandlerNode.convertNode = function (node, tag) {
    extend(node, TagHandlerNode.prototype);
    TagHandlerNode.call(node, tag);
};

TagHandlerNode.prototype = {
    addDynamicAttribute: function (name, value) {
        if (!this.dynamicAttributes) {
            this.dynamicAttributes = {};
        }
        this.dynamicAttributes[name] = value;
    },
    setDynamicAttributesProperty: function(name) {
        this.dynamicAttributesProperty = name;
    },
    setInputExpression: function (expression) {
        this.inputExpression = expression;
    },
    doGenerateCode: function (template) {
        var rendererPath = template.getRequirePath(this.tag.renderer); // Resolve a path to the renderer relative to the directory of the template
        var handlerVar = addHandlerVar(template, rendererPath);
        var tagHelperVar = template.addStaticVar('_tag', '__helpers.t');

        this.tag.forEachImportedVariable(function (importedVariable) {
            this.setProperty(importedVariable.targetProperty, template.makeExpression(importedVariable.expression));
        }, this);

        var _this = this;
        var variableNames = [];
        _this.tag.forEachVariable(function (nestedVar) {
            var varName;
            if (nestedVar.nameFromAttribute) {
                var possibleNameAttributes = nestedVar.nameFromAttribute.split(/\s+or\s+|\s*,\s*/i);
                for (var i = 0, len = possibleNameAttributes.length; i < len; i++) {
                    var attrName = possibleNameAttributes[i];
                    var keep = false;
                    if (attrName.endsWith('|keep')) {
                        keep = true;
                        attrName = attrName.slice(0, 0 - '|keep'.length);
                        possibleNameAttributes[i] = attrName;
                    }
                    varName = this.getAttribute(attrName);
                    if (varName) {
                        if (!keep) {
                            this.removeProperty(attrName);
                        }
                        break;
                    }
                }
                if (!varName) {
                    this.addError('Attribute ' + possibleNameAttributes.join(' or ') + ' is required');
                    varName = '_var';    // Let it continue with errors
                }
            } else {
                varName = nestedVar.name;
                if (!varName) {
                    this.addError('Variable name is required');
                    varName = '_var';    // Let it continue with errors
                }
            }
            variableNames.push(varName);
        }, this);

        template.functionCall(tagHelperVar, function () {
            template.code('context,\n').indent(function () {
                template.line(handlerVar + ',').indent();
                if (_this.inputExpression) {
                    template.code(_this.inputExpression);
                } else {
                    if (_this.dynamicAttributes) {
                        template.indent(function() {
                            _this.setProperty(_this.dynamicAttributesProperty, template.makeExpression(getPropsStr(_this.dynamicAttributes, template)));
                        });
                    }

                    template.code(getPropsStr(_this.getProperties(), template));
                }
                if (_this.hasChildren()) {
                    var bodyParams = [];
                    variableNames.forEach(function (varName) {
                        bodyParams.push(varName);
                    });
                    template.code(',\n').line('function(' + bodyParams.join(',') + ') {').indent(function () {
                        _this.generateCodeForChildren(template);
                    }).indent().code('}');
                }
            });
        });
    }
};

module.exports = TagHandlerNode;<commit_msg>Allow property values to be functions that resolve to the actual value<commit_after>/*
 * Copyright 2011 eBay Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
var extend = require('raptor-util').extend;
var forEachEntry = require('raptor-util').forEachEntry;
var stringify = require('raptor-json/stringify');

function addHandlerVar(template, renderer) {
    var handlerVars = template._handlerVars || (template._handlerVars = {});
    var handlerVar = handlerVars[renderer];
    if (!handlerVar) {
        handlerVars[renderer] = handlerVar = renderer.replace(/[.\-\/]/g, '_').replace(/^[_]+/g, '');
        template.addStaticVar(handlerVar, 'require(' + stringify(renderer) + ')');
    }
    return handlerVar;
}
function getPropsStr(props, template) {
    var propsArray = [];
    if (props) {
        template.indent(function () {
            forEachEntry(props, function (name, value) {
                if (typeof value === 'function') {
                    value = value();
                }

                if (template.isExpression(value)) {
                    var expressionStr;
                    template.indent(function () {
                        expressionStr = value.expression.toString();
                    });
                    propsArray.push(template.indentStr() + stringify(name) + ': ' + expressionStr);
                } else if (typeof value === 'string' || typeof value === 'object') {
                    propsArray.push(template.indentStr() + stringify(name) + ': ' + stringify(value));
                } else {
                    propsArray.push(template.indentStr() + stringify(name) + ': ' + value);
                }
            });
        });

        if (propsArray.length) {
            return '{\n' + propsArray.join(',\n') + '\n' + template.indentStr() + '}';
        } else {
            return '{}';
        }
    } else {
        return '{}';
    }
}
function TagHandlerNode(tag) {
    if (!this.nodeType) {
        TagHandlerNode.$super.call(this);
    }
    this.tag = tag;
    this.dynamicAttributes = null;
    this.inputExpression = null;
    this.additionalVars = [];
}
TagHandlerNode.nodeType = 'element';

TagHandlerNode.convertNode = function (node, tag) {
    if (node._TagHandlerNode) {
        return;
    }

    extend(node, TagHandlerNode.prototype);
    TagHandlerNode.call(node, tag);
};

TagHandlerNode.prototype = {

    _TagHandlerNode: true,

    addNestedVariable: function(name) {
        this.additionalVars.push(name);
    },
    addDynamicAttribute: function (name, value) {
        if (!this.dynamicAttributes) {
            this.dynamicAttributes = {};
        }
        this.dynamicAttributes[name] = value;
    },
    setDynamicAttributesProperty: function(name) {
        this.dynamicAttributesProperty = name;
    },
    setInputExpression: function (expression) {
        this.inputExpression = expression;
    },
    doGenerateCode: function (template) {
        var rendererPath = template.getRequirePath(this.tag.renderer); // Resolve a path to the renderer relative to the directory of the template
        var handlerVar = addHandlerVar(template, rendererPath);
        var tagHelperVar = template.addStaticVar('_tag', '__helpers.t');

        this.tag.forEachImportedVariable(function (importedVariable) {
            this.setProperty(importedVariable.targetProperty, template.makeExpression(importedVariable.expression));
        }, this);

        var _this = this;
        var variableNames = [];
        _this.tag.forEachVariable(function (nestedVar) {
            var varName;
            if (nestedVar.nameFromAttribute) {
                var possibleNameAttributes = nestedVar.nameFromAttribute.split(/\s+or\s+|\s*,\s*/i);
                for (var i = 0, len = possibleNameAttributes.length; i < len; i++) {
                    var attrName = possibleNameAttributes[i];
                    var keep = false;
                    if (attrName.endsWith('|keep')) {
                        keep = true;
                        attrName = attrName.slice(0, 0 - '|keep'.length);
                        possibleNameAttributes[i] = attrName;
                    }
                    varName = this.getAttribute(attrName);
                    if (varName) {
                        if (!keep) {
                            this.removeProperty(attrName);
                        }
                        break;
                    }
                }
                if (!varName) {
                    this.addError('Attribute ' + possibleNameAttributes.join(' or ') + ' is required');
                    varName = '_var';    // Let it continue with errors
                }
            } else {
                varName = nestedVar.name;
                if (!varName) {
                    this.addError('Variable name is required');
                    varName = '_var';    // Let it continue with errors
                }
            }
            variableNames.push(varName);
        }, this);

        if (this.additionalVars.length) {
            variableNames = variableNames.concat(this.additionalVars);
        }

        template.functionCall(tagHelperVar, function () {
            template.code('context,\n').indent(function () {
                template.line(handlerVar + ',').indent();
                if (_this.inputExpression) {
                    template.code(_this.inputExpression);
                } else {
                    if (_this.dynamicAttributes) {
                        template.indent(function() {
                            _this.setProperty(_this.dynamicAttributesProperty, template.makeExpression(getPropsStr(_this.dynamicAttributes, template)));
                        });
                    }

                    template.code(getPropsStr(_this.getProperties(), template));
                }
                if (_this.hasChildren()) {
                    var bodyParams = [];
                    variableNames.forEach(function (varName) {
                        bodyParams.push(varName);
                    });
                    template.code(',\n').line('function(' + bodyParams.join(',') + ') {').indent(function () {
                        _this.generateCodeForChildren(template);
                    }).indent().code('}');
                }
            });
        });
    }
};

module.exports = TagHandlerNode;<|endoftext|>


<commit_before>/*
 * grunt-wp-readme-to-markdown
 * https://github.com/stephen/wp-readme-to-markdown
 *
 * Copyright (c) 2013 Stephen Harris
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

 grunt.registerMultiTask('wp_readme_to_markdown', 'Converts WP readme.txt file to markdown (readme.md)', function() {

	var options = this.options({
		screenshot_url: false,
		pre_convert: function( readme ){},
		post_convert: function( readme ){}
	});

	grunt.verbose.writeflags( options );
	this.files.forEach(function(f) {

		// Concat specified files.
		var readme = f.src.filter(function(filepath) {
			// Warn on and remove invalid source files (if nonull was set).
			if ( !grunt.file.exists(filepath)) {
				grunt.log.warn('Source file "' + filepath + '" not found.');
				return false;
			} else {
				return true;
			}
		}).map(function(filepath) {
			// Read file source.
			return grunt.file.read(filepath);
		}).join(grunt.util.normalizelf(' '));

		readme = options.pre_convert(readme) || readme;

		/* The following is a ported version of {@see https://github.com/benbalter/WP-Readme-to-Github-Markdown}*/

		//Convert Headings
		grunt.log.debug("Converting headings");
		readme = readme.replace( new RegExp("^=([^=]+)=*?[\\s ]*?$","gim"),"###$1###");
		readme = readme.replace( new RegExp("^==([^=]+)==*?[\\s ]*?$","mig"),"##$1##");
		readme = readme.replace( new RegExp("^===([^=]+)===*?[\\s ]*?$","gim"),"#$1#");

		//parse contributors, donate link, etc.
		grunt.log.debug("Parse contributors, donate link etc");
		var header_match = readme.match( new RegExp("([^##]*)(?:\n##|$)", "m") );
		if ( header_match && header_match.length >= 1 ) {
			var header_search = header_match[1];
			var header_replace = header_search.replace( new RegExp("^([^:\r\n*]{1}[^:\r\n#\\]\\[]+): (.+)","gim"),"**$1:** $2  ");
			readme = readme.replace( header_search, header_replace );
		}

		// Include w.org profiles for contributors.
		grunt.log.debug("Including contributors profiles");
		var contributors_match = readme.match( new RegExp("(\\*\\*Contributors:\\*\\* )(.+)", "m") );
		if ( header_match && header_match.length >= 1 ) {
			var contributors_search = contributors_match[0];
			var contributors_replace = contributors_match[1];
			var profiles = [];

			// Fill profiles.
			contributors_match[2].split(",").forEach(function(value) {
				value = value.trim();
				profiles.push("[" + value + "](https://profiles.wordpress.org/" + value.toLowerCase().replaceAll(" ", "-") + ")");
			});

			contributors_replace += profiles.join(", ");

			// Add line break.
			contributors_replace += '  ';

			readme = readme.replace( contributors_search, contributors_replace );
		}

		//guess plugin slug from plugin name
		//@todo Get this from config instead?
		grunt.log.debug("Get plugin name");
		var _match =  readme.match( new RegExp("^#([^#]+)#[\\s ]*?$","im") );

		//process screenshots, if any
		grunt.log.debug("Get screenshots");
		var screenshot_match = readme.match( new RegExp("## Screenshots ##([^#]*)","im") );
		if ( options.screenshot_url && _match && screenshot_match && screenshot_match.length > 1 ) {

			var plugin = _match[1].trim().toLowerCase().replace(/ /g, '-');

			//Collect screenshots content
			var screenshots = screenshot_match[1];

			//parse screenshot list into array
			var globalMatch = screenshots.match( new RegExp( "^[0-9]+\\. (.*)", "gim") );

			var matchArray = [], nonGlobalMatch;
			for ( var i in globalMatch ) {
				nonGlobalMatch = globalMatch[i].match(  new RegExp( "^[0-9]+\\. (.*)", 'im' ) );
				matchArray.push( nonGlobalMatch[1] );
			}

			//replace list item with markdown image syntax, hotlinking to plugin repo
			//@todo assumes .png, perhaps should check that file exists first?
			for( i=1; i <= matchArray.length; i++ ) {
				var url = options.screenshot_url;
				url = url.replace( '{plugin}', plugin );
				url = url.replace( '{screenshot}', 'screenshot-'+i );
				readme = readme.replace(  globalMatch[i-1], "### "+i+". "+ matchArray[i-1] +" ###\n!["+matchArray[i-1]+"](" + url + ")\n" );
			}
		}

		//Code blocks
		readme = readme.replace( new RegExp("^`$[\n\r]+([^`]*)[\n\r]+^`$","gm"),function( codeblock, codeblockContents ){
			var lines = codeblockContents.split("\n");
			//Add newline and indent all lines in the codeblock by one tab.
			return "\n\t" + lines.join("\n\t") + "\n"; //trailing newline is unnecessary but adds some symmetry.
		});

		readme = options.post_convert(readme) || readme;

		// Write the destination file.
		grunt.file.write( f.dest, readme );

		// Print a success message.
		grunt.log.writeln('File "' + f.dest + '" created.');
	});
});

};
<commit_msg>Add trailing slash to WP.org profiles<commit_after>/*
 * grunt-wp-readme-to-markdown
 * https://github.com/stephen/wp-readme-to-markdown
 *
 * Copyright (c) 2013 Stephen Harris
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

 grunt.registerMultiTask('wp_readme_to_markdown', 'Converts WP readme.txt file to markdown (readme.md)', function() {

	var options = this.options({
		screenshot_url: false,
		pre_convert: function( readme ){},
		post_convert: function( readme ){}
	});

	grunt.verbose.writeflags( options );
	this.files.forEach(function(f) {

		// Concat specified files.
		var readme = f.src.filter(function(filepath) {
			// Warn on and remove invalid source files (if nonull was set).
			if ( !grunt.file.exists(filepath)) {
				grunt.log.warn('Source file "' + filepath + '" not found.');
				return false;
			} else {
				return true;
			}
		}).map(function(filepath) {
			// Read file source.
			return grunt.file.read(filepath);
		}).join(grunt.util.normalizelf(' '));

		readme = options.pre_convert(readme) || readme;

		/* The following is a ported version of {@see https://github.com/benbalter/WP-Readme-to-Github-Markdown}*/

		//Convert Headings
		grunt.log.debug("Converting headings");
		readme = readme.replace( new RegExp("^=([^=]+)=*?[\\s ]*?$","gim"),"###$1###");
		readme = readme.replace( new RegExp("^==([^=]+)==*?[\\s ]*?$","mig"),"##$1##");
		readme = readme.replace( new RegExp("^===([^=]+)===*?[\\s ]*?$","gim"),"#$1#");

		//parse contributors, donate link, etc.
		grunt.log.debug("Parse contributors, donate link etc");
		var header_match = readme.match( new RegExp("([^##]*)(?:\n##|$)", "m") );
		if ( header_match && header_match.length >= 1 ) {
			var header_search = header_match[1];
			var header_replace = header_search.replace( new RegExp("^([^:\r\n*]{1}[^:\r\n#\\]\\[]+): (.+)","gim"),"**$1:** $2  ");
			readme = readme.replace( header_search, header_replace );
		}

		// Include w.org profiles for contributors.
		grunt.log.debug("Including contributors profiles");
		var contributors_match = readme.match( new RegExp("(\\*\\*Contributors:\\*\\* )(.+)", "m") );
		if ( header_match && header_match.length >= 1 ) {
			var contributors_search = contributors_match[0];
			var contributors_replace = contributors_match[1];
			var profiles = [];

			// Fill profiles.
			contributors_match[2].split(",").forEach(function(value) {
				value = value.trim();
				profiles.push("[" + value + "](https://profiles.wordpress.org/" + value.toLowerCase().replaceAll(" ", "-") + "/)");
			});

			contributors_replace += profiles.join(", ");

			// Add line break.
			contributors_replace += '  ';

			readme = readme.replace( contributors_search, contributors_replace );
		}

		//guess plugin slug from plugin name
		//@todo Get this from config instead?
		grunt.log.debug("Get plugin name");
		var _match =  readme.match( new RegExp("^#([^#]+)#[\\s ]*?$","im") );

		//process screenshots, if any
		grunt.log.debug("Get screenshots");
		var screenshot_match = readme.match( new RegExp("## Screenshots ##([^#]*)","im") );
		if ( options.screenshot_url && _match && screenshot_match && screenshot_match.length > 1 ) {

			var plugin = _match[1].trim().toLowerCase().replace(/ /g, '-');

			//Collect screenshots content
			var screenshots = screenshot_match[1];

			//parse screenshot list into array
			var globalMatch = screenshots.match( new RegExp( "^[0-9]+\\. (.*)", "gim") );

			var matchArray = [], nonGlobalMatch;
			for ( var i in globalMatch ) {
				nonGlobalMatch = globalMatch[i].match(  new RegExp( "^[0-9]+\\. (.*)", 'im' ) );
				matchArray.push( nonGlobalMatch[1] );
			}

			//replace list item with markdown image syntax, hotlinking to plugin repo
			//@todo assumes .png, perhaps should check that file exists first?
			for( i=1; i <= matchArray.length; i++ ) {
				var url = options.screenshot_url;
				url = url.replace( '{plugin}', plugin );
				url = url.replace( '{screenshot}', 'screenshot-'+i );
				readme = readme.replace(  globalMatch[i-1], "### "+i+". "+ matchArray[i-1] +" ###\n!["+matchArray[i-1]+"](" + url + ")\n" );
			}
		}

		//Code blocks
		readme = readme.replace( new RegExp("^`$[\n\r]+([^`]*)[\n\r]+^`$","gm"),function( codeblock, codeblockContents ){
			var lines = codeblockContents.split("\n");
			//Add newline and indent all lines in the codeblock by one tab.
			return "\n\t" + lines.join("\n\t") + "\n"; //trailing newline is unnecessary but adds some symmetry.
		});

		readme = options.post_convert(readme) || readme;

		// Write the destination file.
		grunt.file.write( f.dest, readme );

		// Print a success message.
		grunt.log.writeln('File "' + f.dest + '" created.');
	});
});

};
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { currentURL, visit, fillIn, click} from '@ember/test-helpers';
import { authenticateSession } from 'ember-simple-auth/test-support';

module('Acceptance | client_admin | client', function(hooks) {
  setupApplicationTest(hooks);

  test('visiting client AWI', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi');

    assert.equal(currentURL(), '/clients/tib.awi');
    assert.dom('h2.work').hasText('Alfred Wegener Institute');
    assert.dom('a.nav-link.active').hasText('Info');
  });

  test('visiting client AWI settings', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/settings');

    assert.equal(currentURL(), '/clients/tib.awi/settings');
    assert.dom('h2.work').hasText('Alfred Wegener Institute');
    assert.dom('a.nav-link.active').hasText('Settings');
    assert.dom('button#edit-client').includesText('Update Account');
    assert.dom('button#delete-client').doesNotExist();
  });

  test('visiting client AWI prefixes', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/prefixes');

    assert.equal(currentURL(), '/clients/tib.awi/prefixes');
    assert.dom('h2.work').hasText('Alfred Wegener Institute');
    assert.dom('a.nav-link.active').hasText('Prefixes');
  });

  test('visiting client AWI dois', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/dois');

    assert.equal(currentURL(), '/clients/tib.awi/dois');
    assert.dom('h2.work').hasText('Alfred Wegener Institute');
    assert.dom('a.nav-link.active').hasText('DOIs');
    assert.dom('a#new-doi').includesText('Create DOI (Form)');
    assert.dom('a#upload-doi').includesText('Create DOI (File Upload)');
    assert.dom('a#transfer-dois').doesNotExist();
  });

  test('creating a new DOI for client AWI renders', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/dois/new');
    //on landing
    assert.equal(currentURL(), '/clients/tib.awi/dois/new');
    assert.dom('h3').hasText('Create DOI (Form)');
    assert.dom('input#url-field').hasNoValue();
    assert.dom('input#publisher-field').hasNoValue();
    assert.dom('input#publication-year-field').hasNoValue();
    assert.dom('input#draft-radio').isChecked();
    assert.dom('input#registered-radio').isNotChecked();
    assert.dom('input#findable-radio').isNotChecked();
    assert.dom('input#suffix-field').hasAnyValue();
  });

  test('creating a new DOI for client AWI', async function(assert) {
    assert.expect(5);
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/dois/new');
    await fillIn('input#url-field', 'http://bbc.co.uk');
    await fillIn('input#publisher-field', 'the BBC');
    await fillIn('input#publication-year-field', 1928);

    assert.dom('input#url-field').hasValue('http://bbc.co.uk');
    assert.dom('input#publisher-field').hasValue('the BBC');
    assert.dom('input#publication-year-field').hasValue("1928");
    assert.dom('input#url-field').hasStyle({color:'rgb(46, 204, 113)'});
    assert.dom('input#publisher-field').hasStyle({color:'rgb(46, 204, 113)'});
  });
});
<commit_msg>fix tests. #160<commit_after>import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { currentURL, visit, fillIn } from '@ember/test-helpers';
import { authenticateSession } from 'ember-simple-auth/test-support';

module('Acceptance | client_admin | client', function(hooks) {
  setupApplicationTest(hooks);

  test('visiting client AWI', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi');

    assert.equal(currentURL(), '/clients/tib.awi');
    assert.dom('h2.work').hasText('Alfred Wegener Institute');
    assert.dom('a.nav-link.active').hasText('Info');
  });

  test('visiting client AWI settings', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/settings');

    assert.equal(currentURL(), '/clients/tib.awi/settings');
    assert.dom('h2.work').hasText('Alfred Wegener Institute');
    assert.dom('a.nav-link.active').hasText('Settings');
    assert.dom('button#edit-client').includesText('Update Account');
    assert.dom('button#delete-client').doesNotExist();
  });

  test('visiting client AWI prefixes', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/prefixes');

    assert.equal(currentURL(), '/clients/tib.awi/prefixes');
    assert.dom('h2.work').hasText('Alfred Wegener Institute');
    assert.dom('a.nav-link.active').hasText('Prefixes');
  });

  test('visiting client AWI dois', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/dois');

    assert.equal(currentURL(), '/clients/tib.awi/dois');
    assert.dom('h2.work').hasText('Alfred Wegener Institute');
    assert.dom('a.nav-link.active').hasText('DOIs');
    assert.dom('a#new-doi').includesText('Create DOI (Form)');
    assert.dom('a#upload-doi').includesText('Create DOI (File Upload)');
    assert.dom('a#transfer-dois').doesNotExist();
  });

  test('creating a new DOI for client AWI renders', async function(assert) {
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/dois/new');
    //on landing
    assert.equal(currentURL(), '/clients/tib.awi/dois/new');
    assert.dom('h3').hasText('Create DOI (Form)');
    assert.dom('input#url-field').hasNoValue();
    assert.dom('input#publisher-field').hasNoValue();
    assert.dom('input#publication-year-field').hasNoValue();
    assert.dom('input#draft-radio').isChecked();
    assert.dom('input#registered-radio').isNotChecked();
    assert.dom('input#findable-radio').isNotChecked();
    assert.dom('input#suffix-field').hasAnyValue();
  });

  test('creating a new DOI for client AWI', async function(assert) {
    assert.expect(5);
    await authenticateSession({
      uid: 'tib.awi',
      name: 'Alfred Wegener Institute',
      role_id: 'client_admin',
      provider_id: 'tib',
      client_id: 'tib.awi'
    });
    await visit('/clients/tib.awi/dois/new');
    await fillIn('input#url-field', 'http://bbc.co.uk');
    await fillIn('input#publisher-field', 'the BBC');
    await fillIn('input#publication-year-field', 1928);

    assert.dom('input#url-field').hasValue('http://bbc.co.uk');
    assert.dom('input#publisher-field').hasValue('the BBC');
    assert.dom('input#publication-year-field').hasValue("1928");
    assert.dom('input#url-field').hasStyle({color:'rgb(46, 204, 113)'});
    assert.dom('input#publisher-field').hasStyle({color:'rgb(46, 204, 113)'});
  });
});
<|endoftext|>


<commit_before>var path = require('path');
var app_test = require('./nw_test_app');
var os = require('os');
var fs = require('fs-extra');
var cp = require('child_process');

describe('snapshot', function() {

    before(function(done) {
      var snapshotExec;
      if (os.platform() == 'darwin' || os.platform() == 'linux') {
        snapshotExec = 'nwsnapshot';
      }
      if (os.platform() == 'win32') {
        snapshotExec = 'nwsnapshot.exe';
      }

      var snapshotPath = path.join(process.execPath, '..', snapshotExec);

      cp.execFile(snapshotPath,
                  ['--extra_code', 'mytest.js', 'mytest.bin'],
                  {cwd:'./' + global.tests_dir + '/snapshot/'},
                  function (error, stdout, stderr) {
                    done();
                  }

      );
    })

    after(function() {
      fs.unlink(path.join(global.tests_dir, 'snapshot', 'mytest.bin'), function(err) {if(err && err.code !== 'ENOENT') throw err});
      fs.unlink(path.join(global.tests_dir, 'snapshot', 'v8.log'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    })

    it('the native code could be exectuted',
	  function(done) {
        this.timeout(0);
        var result = false;

        var child = app_test.createChildProcess({
          execPath: process.execPath,
          appPath: path.join(global.tests_dir, 'snapshot'),
          end: function(data, app) {
            done();
            app.kill();
            result = true;
          }
        });

        setTimeout(function(){
          if (!result) {
            done('the native code does not been executed');
            child.close();
            //child.removeConnection();
            //child.app.kill();
          }
        }, 3000);
        //child.app.stderr.on('data', function(d){ console.log ('app' + d);});

    })

})
<commit_msg>[test] fix path for snapshot case on Mac<commit_after>var path = require('path');
var app_test = require('./nw_test_app');
var os = require('os');
var fs = require('fs-extra');
var cp = require('child_process');

describe('snapshot', function() {

    before(function(done) {
      var snapshotExec;
      if (os.platform() == 'darwin') {
        snapshotExec = '../../../../../../nwsnapshot';
      }
      if (os.platform() == 'linux') {
        snapshotExec = 'nwsnapshot';
      }
      if (os.platform() == 'win32') {
        snapshotExec = 'nwsnapshot.exe';
      }

      var snapshotPath = path.join(process.execPath, '..', snapshotExec);
      console.log("snapshotPath: " + snapshotPath);

      cp.execFile(snapshotPath,
                  ['--extra_code', 'mytest.js', 'mytest.bin'],
                  {cwd:'./' + global.tests_dir + '/snapshot/'},
                  function (error, stdout, stderr) {
                    done();
                  }

      );
    })

    after(function() {
      fs.unlink(path.join(global.tests_dir, 'snapshot', 'mytest.bin'), function(err) {if(err && err.code !== 'ENOENT') throw err});
      fs.unlink(path.join(global.tests_dir, 'snapshot', 'v8.log'), function(err) {if(err && err.code !== 'ENOENT') throw err});
    })

    it('the native code could be exectuted',
	  function(done) {
        this.timeout(0);
        var result = false;

        var child = app_test.createChildProcess({
          execPath: process.execPath,
          appPath: path.join(global.tests_dir, 'snapshot'),
          end: function(data, app) {
            done();
            app.kill();
            result = true;
          }
        });

        setTimeout(function(){
          if (!result) {
            done('the native code does not been executed');
            child.close();
            //child.removeConnection();
            //child.app.kill();
          }
        }, 3000);
        //child.app.stderr.on('data', function(d){ console.log ('app' + d);});

    })

})
<|endoftext|>


<commit_before>//==============================================================================
// Elements which contains the location of the previous and next site
//==============================================================================
const prev = document.getElementById("prev-site");
const next = document.getElementById("next-site");

//==============================================================================
// Handle arrow keys and change the location to the desired direction
//==============================================================================
document.addEventListener("keyup", function(event) {
	if(!event.ctrlKey && !event.shiftKey) {
		(event.keyCode === 37 && prev) && (window.location.href = prev.getAttribute("href"));
		(event.keyCode === 39 && next) && (window.location.href = next.getAttribute("href"));
	}
}, false);<commit_msg>Rename function parameter "event" to "e"<commit_after>//==============================================================================
// Elements which contains the location of the previous and next site
//==============================================================================
const prev = document.getElementById("prev-site");
const next = document.getElementById("next-site");

//==============================================================================
// Handle arrow keys and change the location to the desired direction
//==============================================================================
document.addEventListener("keyup", function(e) {
	if(!e.ctrlKey && !e.shiftKey) {
		(e.keyCode === 37 && prev) && (window.location.href = prev.getAttribute("href"));
		(e.keyCode === 39 && next) && (window.location.href = next.getAttribute("href"));
	}
}, false);<|endoftext|>


<commit_before>import {proceed, create as layer}  from "src/external/ContextJS.js"
import * as cop  from "src/external/ContextJS.js"

/* A COP Layer that adapts D3 and Lively Containers to display D3 examples inline */

layer(window, "ScopedD3").refineObject(d3, {
  select(name, ...rest) {
    console.log("select " + name)
    if (ScopedD3.currentBody && name == "body")
      return proceed(ScopedD3.currentBody);
    return cop.withLayers([D3ScopedDocument], () => proceed(name, ...rest))
  },
  json(url, ...rest) {
    url = "" + url
    console.log("json url: " + url)
    if (!url.match(/^((https?:\/\/)|\/)/)) {
      url =  ScopedD3.currentBaseURL + "/" + url
      console.log("json adapt url: " + url)
    }
    return proceed(url, ...rest)
  },
  text(url, ...rest) {
    url = "" + url
    console.log("text url: " + url)
    if (!url.match(/^((https?:\/\/)|\/)/)) {
      url =  ScopedD3.currentBaseURL + "/" + url
      console.log("text adapt url: " + url)
    }
    return proceed(url, ...rest)
  }
}).refineObject(lively.components.prototypes['lively-container'], {
  clear() {
    this.getSubmorph('#container-content').innerHTML = null;
    proceed()
  },
  appendScript(scriptElement) {
    if (scriptElement.src && scriptElement.src.match(/d3\.v3(\.min)?\.js/)) {
      console.log("ignore D3")
      return
    }
    if (scriptElement.src && scriptElement.src.match(/cola(\.min)?\.js/)) {
      console.log("ignore cola")
      return
    }
    return proceed(scriptElement)
  },
  setPath(...rest) {
    ScopedD3.currentBody = null
    return proceed(...rest)
  },
  appendHtml(content) {
    console.log("append html " + this)
    if (content.match(/<script src=".*d3\.v3(.min)?\.js".*>/)) {
      ScopedD3.updateCurrentBodyAndURLFrom(this)
      console.log("SCOPE D3: " +ScopedD3.currentBody)

    }
    var result = proceed(content)
  },
  getContentRoot() {
    console.log("get content root")
    if (ScopedD3.currentBody)
      return ScopedD3.currentBody
    else
      return proceed()
  }
})
ScopedD3.updateCurrentBodyAndURLFrom = function (container) {
  ScopedD3.currentBody = container.getSubmorph('#container-content');
  ScopedD3.currentBaseURL = (""+ container.getURL()).replace(/[^/]*$/,"")
}
ScopedD3.beGlobal()

layer(window, "D3ScopedDocument").refineObject(document, {
  querySelector(s, ...rest) {
    // console.log("query selector " + s)
    if (ScopedD3.currentBody)
      return ScopedD3.currentBody.querySelector(s, ...rest)
    return proceed(s, ...rest)
  },
  querySelectorAll(s, ...rest) {
    // console.log("query selectorAll " + s)
    if (ScopedD3.currentBody)
      return ScopedD3.currentBody.querySelectorAll(s, ...rest)
    return proceed(s, ...rest)
  }
})
// D3ScopedDocument.beGlobal()

cop.create(window, "PrettyPrint").refineObject([].__proto__, {
  toString() {
    return "[" + proceed() + "]"
  }
})

// PrettyPrint.beNotGloba<commit_msg>[container]  make d3 examples work again....<commit_after>import {proceed, create as layer}  from "src/external/ContextJS.js"
import * as cop  from "src/external/ContextJS.js"

/* A COP Layer that adapts D3 and Lively Containers to display D3 examples inline */

layer(window, "ScopedD3").refineObject(d3, {
  select(name, ...rest) {
    console.log("select " + name)
    if (ScopedD3.currentBody && name == "body")
      return proceed(ScopedD3.currentBody);
    return cop.withLayers([D3ScopedDocument], () => proceed(name, ...rest))
  },
  json(url, ...rest) {
    url = "" + url
    console.log("json url: " + url)
    if (!url.match(/^((https?:\/\/)|\/)/)) {
      url =  ScopedD3.currentBaseURL + "/" + url
      console.log("json adapt url: " + url)
    }
    return proceed(url, ...rest)
  },
  text(url, ...rest) {
    url = "" + url
    console.log("text url: " + url)
    if (!url.match(/^((https?:\/\/)|\/)/)) {
      url =  ScopedD3.currentBaseURL + "/" + url
      console.log("text adapt url: " + url)
    }
    return proceed(url, ...rest)
  }
}).refineObject(lively.components.prototypes['lively-container'], {
  clear() {
    this.getContentRoot().innerHTML = null;
    proceed()
  },
  appendScript(scriptElement) {
    if (scriptElement.src && scriptElement.src.match(/d3\.v3(\.min)?\.js/)) {
      console.log("ignore D3")
      return
    }
    if (scriptElement.src && scriptElement.src.match(/cola(\.min)?\.js/)) {
      console.log("ignore cola")
      return
    }
    return proceed(scriptElement)
  },
  setPath(...rest) {
    ScopedD3.currentBody = null
    return proceed(...rest)
  },
  appendHtml(content) {
    console.log("append html " + this)
    if (content.match(/<script src=".*d3\.v3(.min)?\.js".*>/)) {
      ScopedD3.updateCurrentBodyAndURLFrom(this)
      console.log("SCOPE D3: " +ScopedD3.currentBody)

    }
    var result = proceed(content)
  },
  getContentRoot() {
    console.log("get content root")
    if (ScopedD3.currentBody)
      return ScopedD3.currentBody
    else
      return proceed()
  }
})
ScopedD3.updateCurrentBodyAndURLFrom = function (container) {
  ScopedD3.currentBody = container.getContentRoot();
  ScopedD3.currentBaseURL = (""+ container.getURL()).replace(/[^/]*$/,"")
}
ScopedD3.beGlobal()

layer(window, "D3ScopedDocument").refineObject(document, {
  querySelector(s, ...rest) {
    // console.log("query selector " + s)
    if (ScopedD3.currentBody)
      return ScopedD3.currentBody.querySelector(s, ...rest)
    return proceed(s, ...rest)
  },
  querySelectorAll(s, ...rest) {
    // console.log("query selectorAll " + s)
    if (ScopedD3.currentBody)
      return ScopedD3.currentBody.querySelectorAll(s, ...rest)
    return proceed(s, ...rest)
  }
})
// D3ScopedDocument.beGlobal()

cop.create(window, "PrettyPrint").refineObject([].__proto__, {
  toString() {
    return "[" + proceed() + "]"
  }
})

// PrettyPrint.beNotGloba<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.ArrayController.extend({
    actions: {
        rowClick( row ) {
            window.console.log( 'Clicked', row );
        },

        sendLog( row ) {
            window.console.log( 'Record:', Ember.get( row, 'name' ) );
        },

        sortColumn( column, sortAscending ) {
            this.setProperties({
                sortAscending,
                'sortProperties': [ Ember.get( column, 'valuePath' ) ]
            });
        }
    },

    columns: new Ember.A([
        {
            primary: true,
            size: 'small',
            title: 'Color',
            valuePath: 'name'
        }, {
            size: 'small',
            sortable: true,
            title: 'Fruit',
            valuePath: 'fruit'
        }, {
            size: 'small',
            sortable: true,
            title: 'Hex Code',
            valuePath: 'hexCode'
        }
    ]),

    rowActions: new Ember.A([
        {
            label: 'Log',
            action: 'sendLog'
        }
    ]),

    totalCount: 6
});
<commit_msg>closes https://github.com/softlayer/sl-ember-components/issues/556<commit_after>import Ember from 'ember';

export default Ember.Controller.extend({
    actions: {
        rowClick( row ) {
            window.console.log( 'Clicked', row );
        },

        sendLog( row ) {
            window.console.log( 'Record:', Ember.get( row, 'name' ) );
        },

        sortColumn( column, sortAscending ) {
            this.setProperties({
                sortAscending,
                'sortProperties': [ Ember.get( column, 'valuePath' ) ]
            });
        }
    },

    columns: new Ember.A([
        {
            primary: true,
            size: 'small',
            title: 'Color',
            valuePath: 'name'
        }, {
            size: 'small',
            sortable: true,
            title: 'Fruit',
            valuePath: 'fruit'
        }, {
            size: 'small',
            sortable: true,
            title: 'Hex Code',
            valuePath: 'hexCode'
        }
    ]),

    rowActions: new Ember.A([
        {
            label: 'Log',
            action: 'sendLog'
        }
    ]),

    totalCount: 6
});
<|endoftext|>