<commit_before>define(['app', 'text!./national-report-6.html', 'lodash', 'utilities/km-storage', 'ngDialog',
		"utilities/solr",'scbd-angularjs-services/locale', './national-target', './national-assessment'],
function(app, template, _){

app.directive('viewNationalReport6', ["$q", "IStorage", function ($q, storage) {
	return {
		restrict   : 'E',
		template   : template,
		replace    : true,
		transclude : false,
		scope: {
			document: "=ngModel",
			locale  : "=",
			target  : "@linkTarget",
			allowDrafts : "@"
		},
		link : function ($scope)
		{

		},
		controller	:  ["$scope", "$http","$rootScope", "$q", "$location", "$filter", 'IStorage',
						 "navigation", "authentication", "siteMapUrls", "Thesaurus", "guid", "$route" ,
						 "solr", "realm",'ngDialog', 'locale', 'smoothScroll',
			function ($scope, $http, $rootScope, $q, $location, $filter, storage, navigation, authentication,
			siteMapUrls, thesaurus, guid, $route, solr, realm, ngDialog, locale, smoothScroll) {

				if(!$scope.locale)
					$scope.locale = locale;

				var progressAssessments = [];
				$scope.nationalTargets = [];

				$scope.$watch('document', function(document, old){

					if(!$scope.document||!document)
						return;
					if(document.targetPursued){
						$scope.isLoadingTargets = true
						var nationalTargets = _.map(document.nationalTargets, function(target){ return loadDocument(target.identifier);});
						$q.all(nationalTargets)
						  .then(function(data){
							  $scope.nationalTargets = [];
							  _.each(_.compact(data), function(target){
								if(target.data){
									target.data.government = undefined;
									$scope.nationalTargets.push(target.data);
								}
							  });
						  })
						  .finally(function(){
							$scope.isLoadingTargets = false;
						  });
					}

					$scope.isLoadingAssessments = true;
					var nationalAssessmentQuery=[];
					_.each($scope.document.progressAssessments, function (mod) {
						if(mod.assessment && mod.assessment.identifier){
							nationalAssessmentQuery.push(loadDocument(mod.assessment.identifier));
						}
					});
					$q.all(nationalAssessmentQuery)
					.then(function(results){
						if(results){
							var documents = _.map(_.compact(results), function(result){
												result.data.government = undefined; return (result||{}).data || {};
											});
							$scope.progressAssessments = documents;
						}
					})
					.finally(function(){
					  $scope.isLoadingAssessments = false;
					});

					if($scope.document.nationalContribution){
						var queries = [];

						var target16 = $scope.document.nationalContribution.aichiTarget16;
						var target20 = $scope.document.nationalContribution.aichiTarget20;

						if(target16){
							var queries = [];
							var realmConfig;
							if(realm == "CHM-DEV")
								realmConfig = 'abs-dev';
							else if(realm == "CHM-TRG")
								realmConfig = 'abs-trg';
							else
								realmConfig = 'abs';
							$scope.absNationalReport = undefined;
							if(target16.nationalReport)
								loadReferenceRecords({identifier:removeRevisonNumber(target16.nationalReport.identifier)}, realmConfig)
								.then(function(data){
									$scope.absNationalReport = _.head(data);
								});

							$scope.absLinkedRecords = undefined;
							if((target16.includeLinkedRecords && target16.linkedRecords) ||
							   (!target16.nationalReport && target16.includeLinkedRecords==undefined && target16.linkedRecords)){
								var options = {
									identifier : "(" + _.pluck(target16.linkedRecords, 'identifier').join(' ') + ")"
								}
								loadReferenceRecords(options, realmConfig)
								.then(function(data){
									$scope.absLinkedRecords = data;
								});;
							}

						}
						if(target20 && target20.resourceMobilisationReport){
							$scope.resourceMobilisationReport = undefined;
							loadReferenceRecords({identifier : target20.resourceMobilisationReport.identifier})
							.then(function(data){
								$scope.resourceMobilisationReport = _.head(data)
							})
						}
					}
				});

				//============================================================
				//
				//============================================================
				$scope.getNationalTargetTitle = function(identifier){

					if($scope.nationalTargets){
						var nationalTarget = _.find($scope.nationalTargets, function(target){
												return target && target.header.identifier == identifier;
											});
						if(nationalTarget)
							return nationalTarget.title;
					}
				};

				//============================================================
				//
				//============================================================
				$scope.hasNationalContributions = function () {
					if($scope.document && $scope.document.nationalContributions){
						return _.has($scope.document.nationalContributions, 'description') || _.has($scope.document.nationalContributions, 'achievementActivities');
					}
				};

				//============================================================
				//
				//============================================================
				$scope.getAssessmentInfo = function(assessment, field){
					var existingAssesment = _.find(progressAssessments, function(progress){
														return  progress.identifier_s == assessment.identifier;
													});
					if(existingAssesment)
						return existingAssesment[field];

				};

				function removeRevisonNumber(identifier){
					if(identifier && identifier.indexOf('@')>0)
						return identifier.substr(0, identifier.indexOf('@'));

					return identifier;
				}

				function getRevisonNumber(identifier){
					if(identifier && identifier.indexOf('@')>0)
						return identifier.substr(identifier.indexOf('@')+1, identifier.length - (identifier.indexOf('@')+1));

					return identifier;
				}

				//============================================================
				//
				//============================================================
				function loadReferenceRecords(options, appRealm) {

					if(options.latest===undefined)
						options.latest = true;

					options = _.assign({
						schema    : options.schema,
						target    : options.nationaTargetId,
						rows	  : 500
					}, options || {});

					var query  = [];

					// Add Schema
					if(options.schema)
					query.push("schema_s:" + solr.escape(options.schema));

					if(options.government)
						query.push("government_s:"+solr.escape(options.government));

					if(options.target)
						query.push("nationalTarget_s:"+solr.escape(options.target));

					if(options.identifier)
						query.push("(identifier_s:"+solr.escape(options.identifier)+")");

					if(options.revision)
						query.push("_revision_i:"+solr.escape(options.revision));
					// Apply ownership
					query.push(["realm_ss:" + (appRealm||realm).toLowerCase(), "(*:* NOT realm_ss:*)"]);

					// Apply ownership
					// query.push(_.map(($rootScope.user||{}).userGroups, function(v){
					// 	return "_ownership_s:"+solr.escape(v);
					// }));

					if(options.latest!==undefined){
						query.push("_latest_s:" + (options.latest ? "true" : "false"));
					}

					// AND / OR everything

					var query =  solr.andOr(query);
					var qsParams =
					{
						"q"  : query,
						"fl" : "identifier_s,uniqueIdentifier_s, schema_t, title_t, summary_t, description_t, reportType_EN_t, " +
							"url_ss, _revision_i, _state_s, _latest_s, _workflow_s, isAichiTarget_b, aichiTargets_*, otherAichiTargets_*, date_dt, progress_s",
						"sort"  : "createdDate_dt desc",
						"start" : 0,
						"rows"   : options.rows,
					};

					return $http.get("/api/v2013/index", { params : qsParams }).then(function(res) {

						return _.map(res.data.response.docs, function(v){
							return _.defaults(v, {
								schemaName     : solr.lstring(v, "schema_*_t",     "schema_EN_t",     "schema_s"),
								title          : solr.lstring(v, "title_*_t",      "title_EN_t",      "title_t"),
								summary        : solr.lstring(v, "summary_*_t",    "description_*_t", "summary_EN_t", "description_EN_t", "summary_t", "description_t")
							});
						});

					});
				}

				$scope.showReferenceRecordDetailss = function(documentId){
					openDialog(documentId, {});
				};

				//============================================================
				//
				//============================================================
				function openDialog(documentId, options) {

					options = options || {};

					return $q(function(resolve, reject) {

						require(['directives/formats/views/form-loader'], function() {

							var directiveHtml = '<DIRECTIVE document-id="@documentId"></DIRECTIVE>

Close
'
												.replace(/DIRECTIVE/g, 'view-form-loader')
												.replace(/@documentId/g, documentId);

							$scope.$apply(function(){
								options.template = directiveHtml;
							});
							options.className = 'ngdialog-theme-default wide';
							options.plain = true;
							options.controller = ['$scope', function($scope){
								$scope.close = ngDialog.closeAll;
							}];

							var dialogWindow = ngDialog.open(options);

							dialogWindow.closePromise.then(function(res){

								if(res.value=="$escape")      delete res.value;
								if(res.value=="$document")    delete res.value;
								if(res.value=="$closeButton") delete res.value;

								return res;
							});

							resolve(dialogWindow);

						}, reject);
					});
				}

				function loadDocument(identifier) {

					if (identifier) { //lookup single record

						return storage.documents.get(identifier)
									.catch(function(e) {
										if (e.status == 404 && $location.path() != '/database/record') {
											return storage.drafts.get(identifier).catch(function(e) {});
										}
									});
					}
				};

		}]
	};
}]);
});
<commit_msg>use workingdocument when not on public url<commit_after>define(['app', 'text!./national-report-6.html', 'lodash', 'utilities/km-storage', 'ngDialog',
		"utilities/solr",'scbd-angularjs-services/locale', './national-target', './national-assessment'],
function(app, template, _){

app.directive('viewNationalReport6', ["$q", "IStorage", function ($q, storage) {
	return {
		restrict   : 'E',
		template   : template,
		replace    : true,
		transclude : false,
		scope: {
			document: "=ngModel",
			locale  : "=",
			target  : "@linkTarget",
			allowDrafts : "@"
		},
		link : function ($scope)
		{

		},
		controller	:  ["$scope", "$http","$rootScope", "$q", "$location", "$filter", 'IStorage',
						 "navigation", "authentication", "siteMapUrls", "Thesaurus", "guid", "$route" ,
						 "solr", "realm",'ngDialog', 'locale', 'smoothScroll',
			function ($scope, $http, $rootScope, $q, $location, $filter, storage, navigation, authentication,
			siteMapUrls, thesaurus, guid, $route, solr, realm, ngDialog, locale, smoothScroll) {

				if(!$scope.locale)
					$scope.locale = locale;

				var progressAssessments = [];
				$scope.nationalTargets = [];

				$scope.$watch('document', function(document, old){

					if(!$scope.document||!document)
						return;
					if(document.targetPursued){
						$scope.isLoadingTargets = true
						var nationalTargets = _.map(document.nationalTargets, function(target){ return loadDocument(target.identifier);});
						$q.all(nationalTargets)
						  .then(function(data){
							  $scope.nationalTargets = [];
							  _.each(_.compact(data), function(target){
								if(target && target.data){
									target.data.government = undefined;
									$scope.nationalTargets.push(target.data);
								}
							  });
						  })
						  .finally(function(){
							$scope.isLoadingTargets = false;
						  });
					}

					$scope.isLoadingAssessments = true;
					var nationalAssessmentQuery=[];
					_.each($scope.document.progressAssessments, function (mod) {
						if(mod.assessment && mod.assessment.identifier){
							nationalAssessmentQuery.push(loadDocument(mod.assessment.identifier));
						}
					});
					$q.all(nationalAssessmentQuery)
					.then(function(results){
						if(results){
							var documents = _.map(_.compact(results), function(result){
												result.data.government = undefined; return (result||{}).data || {};
											});
							$scope.progressAssessments = documents;
						}
					})
					.finally(function(){
					  $scope.isLoadingAssessments = false;
					});

					if($scope.document.nationalContribution){
						var queries = [];

						var target16 = $scope.document.nationalContribution.aichiTarget16;
						var target20 = $scope.document.nationalContribution.aichiTarget20;

						if(target16){
							var queries = [];
							var realmConfig;
							if(realm == "CHM-DEV")
								realmConfig = 'abs-dev';
							else if(realm == "CHM-TRG")
								realmConfig = 'abs-trg';
							else
								realmConfig = 'abs';
							$scope.absNationalReport = undefined;
							if(target16.nationalReport)
								loadReferenceRecords({identifier:removeRevisonNumber(target16.nationalReport.identifier)}, realmConfig)
								.then(function(data){
									$scope.absNationalReport = _.head(data);
								});

							$scope.absLinkedRecords = undefined;
							if((target16.includeLinkedRecords && target16.linkedRecords) ||
							   (!target16.nationalReport && target16.includeLinkedRecords==undefined && target16.linkedRecords)){
								var options = {
									identifier : "(" + _.pluck(target16.linkedRecords, 'identifier').join(' ') + ")"
								}
								loadReferenceRecords(options, realmConfig)
								.then(function(data){
									$scope.absLinkedRecords = data;
								});;
							}

						}
						if(target20 && target20.resourceMobilisationReport){
							$scope.resourceMobilisationReport = undefined;
							loadReferenceRecords({identifier : target20.resourceMobilisationReport.identifier})
							.then(function(data){
								$scope.resourceMobilisationReport = _.head(data)
							})
						}
					}
				});

				//============================================================
				//
				//============================================================
				$scope.getNationalTargetTitle = function(identifier){

					if($scope.nationalTargets){
						var nationalTarget = _.find($scope.nationalTargets, function(target){
												return target && target.header.identifier == identifier;
											});
						if(nationalTarget)
							return nationalTarget.title;
					}
				};

				//============================================================
				//
				//============================================================
				$scope.hasNationalContributions = function () {
					if($scope.document && $scope.document.nationalContributions){
						return _.has($scope.document.nationalContributions, 'description') || _.has($scope.document.nationalContributions, 'achievementActivities');
					}
				};

				//============================================================
				//
				//============================================================
				$scope.getAssessmentInfo = function(assessment, field){
					var existingAssesment = _.find(progressAssessments, function(progress){
														return  progress.identifier_s == assessment.identifier;
													});
					if(existingAssesment)
						return existingAssesment[field];

				};

				function removeRevisonNumber(identifier){
					if(identifier && identifier.indexOf('@')>0)
						return identifier.substr(0, identifier.indexOf('@'));

					return identifier;
				}

				function getRevisonNumber(identifier){
					if(identifier && identifier.indexOf('@')>0)
						return identifier.substr(identifier.indexOf('@')+1, identifier.length - (identifier.indexOf('@')+1));

					return identifier;
				}

				//============================================================
				//
				//============================================================
				function loadReferenceRecords(options, appRealm) {

					if(options.latest===undefined)
						options.latest = true;

					options = _.assign({
						schema    : options.schema,
						target    : options.nationaTargetId,
						rows	  : 500
					}, options || {});

					var query  = [];

					// Add Schema
					if(options.schema)
					query.push("schema_s:" + solr.escape(options.schema));

					if(options.government)
						query.push("government_s:"+solr.escape(options.government));

					if(options.target)
						query.push("nationalTarget_s:"+solr.escape(options.target));

					if(options.identifier)
						query.push("(identifier_s:"+solr.escape(options.identifier)+")");

					if(options.revision)
						query.push("_revision_i:"+solr.escape(options.revision));
					// Apply ownership
					query.push(["realm_ss:" + (appRealm||realm).toLowerCase(), "(*:* NOT realm_ss:*)"]);

					// Apply ownership
					// query.push(_.map(($rootScope.user||{}).userGroups, function(v){
					// 	return "_ownership_s:"+solr.escape(v);
					// }));

					if(options.latest!==undefined){
						query.push("_latest_s:" + (options.latest ? "true" : "false"));
					}

					// AND / OR everything

					var query =  solr.andOr(query);
					var qsParams =
					{
						"q"  : query,
						"fl" : "identifier_s,uniqueIdentifier_s, schema_t, title_t, summary_t, description_t, reportType_EN_t, " +
							"url_ss, _revision_i, _state_s, _latest_s, _workflow_s, isAichiTarget_b, aichiTargets_*, otherAichiTargets_*, date_dt, progress_s",
						"sort"  : "createdDate_dt desc",
						"start" : 0,
						"rows"   : options.rows,
					};

					return $http.get("/api/v2013/index", { params : qsParams }).then(function(res) {

						return _.map(res.data.response.docs, function(v){
							return _.defaults(v, {
								schemaName     : solr.lstring(v, "schema_*_t",     "schema_EN_t",     "schema_s"),
								title          : solr.lstring(v, "title_*_t",      "title_EN_t",      "title_t"),
								summary        : solr.lstring(v, "summary_*_t",    "description_*_t", "summary_EN_t", "description_EN_t", "summary_t", "description_t")
							});
						});

					});
				}

				$scope.showReferenceRecordDetailss = function(documentId){
					openDialog(documentId, {});
				};

				//============================================================
				//
				//============================================================
				function openDialog(documentId, options) {

					options = options || {};

					return $q(function(resolve, reject) {

						require(['directives/formats/views/form-loader'], function() {

							var directiveHtml = '<DIRECTIVE document-id="@documentId"></DIRECTIVE>

Close
'
												.replace(/DIRECTIVE/g, 'view-form-loader')
												.replace(/@documentId/g, documentId);

							$scope.$apply(function(){
								options.template = directiveHtml;
							});
							options.className = 'ngdialog-theme-default wide';
							options.plain = true;
							options.controller = ['$scope', function($scope){
								$scope.close = ngDialog.closeAll;
							}];

							var dialogWindow = ngDialog.open(options);

							dialogWindow.closePromise.then(function(res){

								if(res.value=="$escape")      delete res.value;
								if(res.value=="$document")    delete res.value;
								if(res.value=="$closeButton") delete res.value;

								return res;
							});

							resolve(dialogWindow);

						}, reject);
					});
				}

				function loadDocument(identifier) {

					if (identifier) { //lookup single record

						return storage.documents.get(identifier, {info:true})
									.then(function(target){
										if($location.path() != '/database/record')//if user is not on public record page show working draf document else published record.
											return { data : target.data.workingDocumentBody || target.data.body };
										else
											return { data : target.data.body };
									})
									.catch(function(e) {
										if (e.status == 404 && $location.path() != '/database/record') {
											return storage.drafts.get(identifier).catch(function(e) {});
										}
									});
					}
				};

		}]
	};
}]);
});
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// TODO(dbeam): test for loading upacked extensions?

GEN('#include "chrome/browser/ui/webui/extensions/' +
    'extension_settings_browsertest.h"');

// The id of the extension from |InstallGoodExtension|.
var GOOD_EXTENSION_ID = 'ldnnhddmnhbkjipkidpdiheffobcpfmf';

// The id of the extension from |InstallErrorsExtension|.
var ERROR_EXTENSION_ID = 'pdlpifnclfacjobnmbpngemkalkjamnf';

/**
 * Test C++ fixture for settings WebUI testing.
 * @constructor
 * @extends {testing.Test}
 */
function ExtensionSettingsUIBrowserTest() {}

/**
 * TestFixture for extension settings WebUI testing.
 * @extends {testing.Test}
 * @constructor
 */
function ExtensionSettingsWebUITest() {}

ExtensionSettingsWebUITest.prototype = {
  __proto__: testing.Test.prototype,

  /** @override */
  isAsync: true,

  /** @override */
  runAccessibilityChecks: true,

  /** @override */
  accessibilityIssuesAreErrors: true,

  /**
   * A URL to load before starting each test.
   * @type {string}
   * @const
   */
  browsePreload: 'chrome://extensions-frame/',

  /** @override */
  typedefCppFixture: 'ExtensionSettingsUIBrowserTest',

  /** @override */
  setUp: function() {
    testing.Test.disableAnimationsAndTransitions();
  },

  /**
   * Holds an array of steps that should happen in order during a test.
   * The last step should be |testDone|.
   * @protected {Array<!Function>}
   * */
  steps: [],

  /**
   * Advances to the next step in the test. Every step should call this.
   * @protected
   * */
  nextStep: function() {
    assertTrue(this.steps.length > 0);
    this.steps.shift().call(this);
  },

  /**
   * Will wait for the page to load before calling the next step. This should be
   * the first step in every test.
   * @protected
   * */
  waitForPageLoad: function() {
    assertEquals(this.browsePreload, document.location.href);
    var extensionList = getRequiredElement('extension-settings-list');
    extensionList.loadFinished.then(this.nextStep.bind(this));
  },

  /** @protected */
  enableDeveloperMode: function() {
    var next = this.nextStep.bind(this);
    document.addEventListener('devControlsVisibilityUpdated',
                              function devCallback() {
      // Callback should only be handled once.
      document.removeEventListener(devCallback);

      chrome.developerPrivate.getProfileConfiguration(function(profileInfo) {
        assertTrue(extensionSettings.classList.contains('dev-mode'));
        assertTrue(profileInfo.inDeveloperMode);

        // This event isn't thrown because transitions are disabled.
        // Ensure transition here so that any dependent code does not break.
        ensureTransitionEndEvent($('dev-controls'), 0);

        next();
      });
    });

    var extensionSettings = getRequiredElement('extension-settings');
    assertFalse(extensionSettings.classList.contains('dev-mode'));
    $('toggle-dev-on').click();
  },

  /** @protected */
  testDeveloperMode: function() {
    var next = this.nextStep.bind(this);
    var checkDevModeIsOff = function() {
      chrome.developerPrivate.getProfileConfiguration(function(profileInfo) {
        assertFalse(profileInfo.inDeveloperMode);
        next();
      });
    };
    this.steps = [this.waitForPageLoad,
                  checkDevModeIsOff,
                  this.enableDeveloperMode,
                  testDone];
    this.nextStep();
  },
};

// Verify that developer mode doesn't change behavior when the number of
// extensions changes.
TEST_F('ExtensionSettingsWebUITest', 'testDeveloperModeNoExtensions',
       function() {
  this.testDeveloperMode();
});

TEST_F('ExtensionSettingsWebUITest', 'testEmptyExtensionList', function() {
  var verifyListIsHiddenAndEmpty = function() {
    assertTrue($('extension-list-wrapper').hidden);
    assertFalse($('no-extensions').hidden);
    assertEquals(0, $('extension-settings-list').childNodes.length);
    this.nextStep();
  };

  this.steps = [this.waitForPageLoad, verifyListIsHiddenAndEmpty, testDone];
  this.nextStep();
});

TEST_F('ExtensionSettingsWebUITest', 'testChromeSendHandled', function() {
  var testPackExtenion = function() {
    // This dialog should be hidden at first.
    assertFalse($('pack-extension-overlay').classList.contains('showing'));

    // Show the dialog, which triggers a chrome.send() for metrics purposes.
    cr.dispatchSimpleEvent($('pack-extension'), 'click');
    assertTrue($('pack-extension-overlay').classList.contains('showing'));
    this.nextStep();
  };

  this.steps = [this.waitForPageLoad, testPackExtenion, testDone];
  this.nextStep();
});

/**
 * @param {chrome.developerPrivate.EventType} eventType
 * @param {function():void} callback
 * @constructor
 */
function UpdateListener(eventType, callback) {
  this.callback_ = callback;
  this.eventType_ = eventType;
  this.onItemStateChangedListener_ = this.onItemStateChanged_.bind(this);
  chrome.developerPrivate.onItemStateChanged.addListener(
      this.onItemStateChangedListener_);
}

UpdateListener.prototype = {
  /** @private */
  onItemStateChanged_: function(data) {
    if (this.eventType_ == data.event_type) {
      window.setTimeout(function() {
        chrome.developerPrivate.onItemStateChanged.removeListener(
            this.onItemStateChangedListener_);
        this.callback_();
      }.bind(this), 0);
    }
  }
};

function BasicExtensionSettingsWebUITest() {}

BasicExtensionSettingsWebUITest.prototype = {
  __proto__: ExtensionSettingsWebUITest.prototype,

  /** @override */
  testGenPreamble: function() {
    // Install multiple types of extensions to ensure we handle each type.
    // TODO(devlin): There are more types to add here.
    GEN('  InstallGoodExtension();');
    GEN('  InstallErrorsExtension();');
    GEN('  InstallSharedModule();');
    GEN('  InstallPackagedApp();');

    GEN('  SetAutoConfirmUninstall();');
  },

  /** @protected */
  verifyDisabledWorks: function() {
    var listener = new UpdateListener(
        chrome.developerPrivate.EventType.UNLOADED,
        function() {
      var node = getRequiredElement(GOOD_EXTENSION_ID);
      assertTrue(node.classList.contains('inactive-extension'));
      this.nextStep();
    }.bind(this));
    chrome.management.setEnabled(GOOD_EXTENSION_ID, false);
  },

  /** @protected */
  verifyEnabledWorks: function() {
    var listener = new UpdateListener(
        chrome.developerPrivate.EventType.LOADED,
        function() {
      var node = getRequiredElement(GOOD_EXTENSION_ID);
      assertFalse(node.classList.contains('inactive-extension'));
      this.nextStep();
    }.bind(this));
    chrome.management.setEnabled(GOOD_EXTENSION_ID, true);
  },

  /** @protected */
  verifyUninstallWorks: function() {
    var listener = new UpdateListener(
        chrome.developerPrivate.EventType.UNINSTALLED,
        function() {
      assertEquals(null, $(GOOD_EXTENSION_ID));
      this.nextStep();
    }.bind(this));
    chrome.test.runWithUserGesture(function() {
      chrome.management.uninstall(GOOD_EXTENSION_ID);
    });
  },
};

// Verify that developer mode doesn't change behavior when the number of
// extensions changes.
TEST_F('BasicExtensionSettingsWebUITest', 'testDeveloperModeManyExtensions',
       function() {
  this.testDeveloperMode();
});

TEST_F('BasicExtensionSettingsWebUITest', 'testDisable', function() {
  this.steps = [this.waitForPageLoad, this.verifyDisabledWorks, testDone];
  this.nextStep();
});

TEST_F('BasicExtensionSettingsWebUITest', 'testEnable', function() {
  this.steps = [this.waitForPageLoad,
                this.verifyDisabledWorks,
                this.verifyEnabledWorks,
                testDone];
  this.nextStep();
});

TEST_F('BasicExtensionSettingsWebUITest', 'testUninstall', function() {
  this.steps = [this.waitForPageLoad, this.verifyUninstallWorks, testDone];
  this.nextStep();
});

TEST_F('BasicExtensionSettingsWebUITest', 'testNonEmptyExtensionList',
       function() {
  var verifyListIsNotHiddenAndEmpty = function() {
    assertFalse($('extension-list-wrapper').hidden);
    assertTrue($('no-extensions').hidden);
    assertGT($('extension-settings-list').childNodes.length, 0);
    this.nextStep();
  };

  this.steps = [this.waitForPageLoad, verifyListIsNotHiddenAndEmpty, testDone];
  this.nextStep();
});

function ErrorConsoleExtensionSettingsWebUITest() {}

ErrorConsoleExtensionSettingsWebUITest.prototype = {
  __proto__: ExtensionSettingsWebUITest.prototype,

  /** @override */
  testGenPreamble: function() {
    GEN('  EnableErrorConsole();');
    GEN('  InstallGoodExtension();');
    GEN('  InstallErrorsExtension();');
  },
};

GEN('#if defined(OS_CHROMEOS)');  // Flaky on ChromeOS; http://crbug.com/499884.
GEN('#define MAYBE_testErrorListButtonVisibility ' +
    'DISABLED_testErrorListButtonVisibility');
GEN('#elif defined(OS_WIN)');  // Flaky on Win7 dbg; http://crbug.com/463245.
GEN('#define MAYBE_testErrorListButtonVisibility ' +
    'DISABLED_testErrorListButtonVisibility');
GEN('#else');
GEN('#define MAYBE_testErrorListButtonVisibility ' +
    'testErrorListButtonVisibility');
GEN('#endif');

TEST_F('ErrorConsoleExtensionSettingsWebUITest',
       'MAYBE_testErrorListButtonVisibility', function() {
  var testButtonVisibility = function() {
    var extensionList = $('extension-list-wrapper');

    var visibleButtons = extensionList.querySelectorAll(
        '.errors-link:not([hidden])');
    expectEquals(1, visibleButtons.length);

    if (visibleButtons.length > 0) {
      var errorLink = $(ERROR_EXTENSION_ID).querySelector('.errors-link');
      expectEquals(visibleButtons[0], errorLink);

      var errorIcon = errorLink.querySelector('img');
      expectTrue(errorIcon.classList.contains('extension-error-warning-icon'));
    }

    var hiddenButtons = extensionList.querySelectorAll('.errors-link[hidden]');
    expectEquals(1, hiddenButtons.length);

    this.nextStep();
  };

  this.steps = [this.waitForPageLoad,
                this.enableDeveloperMode,
                testButtonVisibility,
                testDone];
  this.nextStep();
});

/**
 * TestFixture for extension settings WebUI testing (commands config edition).
 * @extends {testing.Test}
 * @constructor
 */
function SettingsCommandsExtensionSettingsWebUITest() {}

SettingsCommandsExtensionSettingsWebUITest.prototype = {
  __proto__: ExtensionSettingsWebUITest.prototype,

  /**
   * A URL to load before starting each test.
   * @type {string}
   * @const
   */
  browsePreload: 'chrome://extensions-frame/configureCommands',
};

TEST_F('SettingsCommandsExtensionSettingsWebUITest', 'testChromeSendHandler',
    function() {
  // Just navigating to the page should trigger the chrome.send().
  var assertOverlayVisible = function() {
    assertTrue($('extension-commands-overlay').classList.contains('showing'));
    this.nextStep();
  };

  this.steps = [this.waitForPageLoad, assertOverlayVisible, testDone];
  this.nextStep();
});

/**
 * @constructor
 * @extends {ExtensionSettingsWebUITest}
 */
function InstallGoodExtensionSettingsWebUITest() {}

InstallGoodExtensionSettingsWebUITest.prototype = {
  __proto__: ExtensionSettingsWebUITest.prototype,

  /** @override */
  testGenPreamble: function() {
    GEN('  InstallGoodExtension();');
  },

  emptyTestForAccessibility() {
    this.steps = [this.waitForPageLoad, testDone];
    this.nextStep();
  },
};

TEST_F('InstallGoodExtensionSettingsWebUITest', 'testAccessibility',
       function() {
  this.emptyTestForAccessibility();
});

TEST_F('InstallGoodExtensionSettingsWebUITest', 'showOptions', function() {
  var showExtensionOptions = function() {
    var optionsOverlay = extensions.ExtensionOptionsOverlay.getInstance();
    optionsOverlay.setExtensionAndShow(GOOD_EXTENSION_ID, 'GOOD!', '',
                                       this.nextStep.bind(this));

    // Preferred size changes don't happen in browser tests. Just fake it.
    document.querySelector('extensionoptions').onpreferredsizechanged(
        {width: 500, height: 500});
  };

  this.steps = [this.waitForPageLoad, showExtensionOptions, testDone];
  this.nextStep();
});

/**
 * @constructor
 * @extends {InstallGoodExtensionSettingsWebUITest}
 */
function ManagedExtensionSettingsWebUITest() {}

ManagedExtensionSettingsWebUITest.prototype = {
  __proto__: InstallGoodExtensionSettingsWebUITest.prototype,

  /** @override */
  testGenPreamble: function() {
    GEN('  AddManagedPolicyProvider();');
    InstallGoodExtensionSettingsWebUITest.prototype.testGenPreamble.call(this);
  },
};

TEST_F('ManagedExtensionSettingsWebUITest', 'testAccessibility', function() {
  this.emptyTestForAccessibility();
});

/**
 * @constructor
 * @extends {InstallGoodExtensionSettingsWebUITest}
 */
function OptionsDialogExtensionSettingsWebUITest() {}

OptionsDialogExtensionSettingsWebUITest.prototype = {
  __proto__: InstallGoodExtensionSettingsWebUITest.prototype,

  /** @override */
  browsePreload: ExtensionSettingsWebUITest.prototype.browsePreload +
      '?options=' + GOOD_EXTENSION_ID,
};

TEST_F('OptionsDialogExtensionSettingsWebUITest', 'testAccessibility',
       function() {
  this.emptyTestForAccessibility();
});
<commit_msg>Disables flaky test<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// TODO(dbeam): test for loading upacked extensions?

GEN('#include "chrome/browser/ui/webui/extensions/' +
    'extension_settings_browsertest.h"');

// The id of the extension from |InstallGoodExtension|.
var GOOD_EXTENSION_ID = 'ldnnhddmnhbkjipkidpdiheffobcpfmf';

// The id of the extension from |InstallErrorsExtension|.
var ERROR_EXTENSION_ID = 'pdlpifnclfacjobnmbpngemkalkjamnf';

/**
 * Test C++ fixture for settings WebUI testing.
 * @constructor
 * @extends {testing.Test}
 */
function ExtensionSettingsUIBrowserTest() {}

/**
 * TestFixture for extension settings WebUI testing.
 * @extends {testing.Test}
 * @constructor
 */
function ExtensionSettingsWebUITest() {}

ExtensionSettingsWebUITest.prototype = {
  __proto__: testing.Test.prototype,

  /** @override */
  isAsync: true,

  /** @override */
  runAccessibilityChecks: true,

  /** @override */
  accessibilityIssuesAreErrors: true,

  /**
   * A URL to load before starting each test.
   * @type {string}
   * @const
   */
  browsePreload: 'chrome://extensions-frame/',

  /** @override */
  typedefCppFixture: 'ExtensionSettingsUIBrowserTest',

  /** @override */
  setUp: function() {
    testing.Test.disableAnimationsAndTransitions();
  },

  /**
   * Holds an array of steps that should happen in order during a test.
   * The last step should be |testDone|.
   * @protected {Array<!Function>}
   * */
  steps: [],

  /**
   * Advances to the next step in the test. Every step should call this.
   * @protected
   * */
  nextStep: function() {
    assertTrue(this.steps.length > 0);
    this.steps.shift().call(this);
  },

  /**
   * Will wait for the page to load before calling the next step. This should be
   * the first step in every test.
   * @protected
   * */
  waitForPageLoad: function() {
    assertEquals(this.browsePreload, document.location.href);
    var extensionList = getRequiredElement('extension-settings-list');
    extensionList.loadFinished.then(this.nextStep.bind(this));
  },

  /** @protected */
  enableDeveloperMode: function() {
    var next = this.nextStep.bind(this);
    document.addEventListener('devControlsVisibilityUpdated',
                              function devCallback() {
      // Callback should only be handled once.
      document.removeEventListener(devCallback);

      chrome.developerPrivate.getProfileConfiguration(function(profileInfo) {
        assertTrue(extensionSettings.classList.contains('dev-mode'));
        assertTrue(profileInfo.inDeveloperMode);

        // This event isn't thrown because transitions are disabled.
        // Ensure transition here so that any dependent code does not break.
        ensureTransitionEndEvent($('dev-controls'), 0);

        next();
      });
    });

    var extensionSettings = getRequiredElement('extension-settings');
    assertFalse(extensionSettings.classList.contains('dev-mode'));
    $('toggle-dev-on').click();
  },

  /** @protected */
  testDeveloperMode: function() {
    var next = this.nextStep.bind(this);
    var checkDevModeIsOff = function() {
      chrome.developerPrivate.getProfileConfiguration(function(profileInfo) {
        assertFalse(profileInfo.inDeveloperMode);
        next();
      });
    };
    this.steps = [this.waitForPageLoad,
                  checkDevModeIsOff,
                  this.enableDeveloperMode,
                  testDone];
    this.nextStep();
  },
};

GEN('#if defined(OS_CHROMEOS)');  // Flaky on ChromeOS; http://crbug.com/506321.
GEN('#define MAYBE_testDeveloperModeNoExtensions ' +
    'DISABLED_testDeveloperModeNoExtensions');
GEN('#else');
GEN('#define MAYBE_testDeveloperModeNoExtensions ' +
    'testDeveloperModeNoExtensions');
GEN('#endif');

// Verify that developer mode doesn't change behavior when the number of
// extensions changes.
TEST_F('ExtensionSettingsWebUITest', 'testDeveloperModeNoExtensions',
       function() {
  this.testDeveloperMode();
});

TEST_F('ExtensionSettingsWebUITest', 'testEmptyExtensionList', function() {
  var verifyListIsHiddenAndEmpty = function() {
    assertTrue($('extension-list-wrapper').hidden);
    assertFalse($('no-extensions').hidden);
    assertEquals(0, $('extension-settings-list').childNodes.length);
    this.nextStep();
  };

  this.steps = [this.waitForPageLoad, verifyListIsHiddenAndEmpty, testDone];
  this.nextStep();
});

TEST_F('ExtensionSettingsWebUITest', 'testChromeSendHandled', function() {
  var testPackExtenion = function() {
    // This dialog should be hidden at first.
    assertFalse($('pack-extension-overlay').classList.contains('showing'));

    // Show the dialog, which triggers a chrome.send() for metrics purposes.
    cr.dispatchSimpleEvent($('pack-extension'), 'click');
    assertTrue($('pack-extension-overlay').classList.contains('showing'));
    this.nextStep();
  };

  this.steps = [this.waitForPageLoad, testPackExtenion, testDone];
  this.nextStep();
});

/**
 * @param {chrome.developerPrivate.EventType} eventType
 * @param {function():void} callback
 * @constructor
 */
function UpdateListener(eventType, callback) {
  this.callback_ = callback;
  this.eventType_ = eventType;
  this.onItemStateChangedListener_ = this.onItemStateChanged_.bind(this);
  chrome.developerPrivate.onItemStateChanged.addListener(
      this.onItemStateChangedListener_);
}

UpdateListener.prototype = {
  /** @private */
  onItemStateChanged_: function(data) {
    if (this.eventType_ == data.event_type) {
      window.setTimeout(function() {
        chrome.developerPrivate.onItemStateChanged.removeListener(
            this.onItemStateChangedListener_);
        this.callback_();
      }.bind(this), 0);
    }
  }
};

function BasicExtensionSettingsWebUITest() {}

BasicExtensionSettingsWebUITest.prototype = {
  __proto__: ExtensionSettingsWebUITest.prototype,

  /** @override */
  testGenPreamble: function() {
    // Install multiple types of extensions to ensure we handle each type.
    // TODO(devlin): There are more types to add here.
    GEN('  InstallGoodExtension();');
    GEN('  InstallErrorsExtension();');
    GEN('  InstallSharedModule();');
    GEN('  InstallPackagedApp();');

    GEN('  SetAutoConfirmUninstall();');
  },

  /** @protected */
  verifyDisabledWorks: function() {
    var listener = new UpdateListener(
        chrome.developerPrivate.EventType.UNLOADED,
        function() {
      var node = getRequiredElement(GOOD_EXTENSION_ID);
      assertTrue(node.classList.contains('inactive-extension'));
      this.nextStep();
    }.bind(this));
    chrome.management.setEnabled(GOOD_EXTENSION_ID, false);
  },

  /** @protected */
  verifyEnabledWorks: function() {
    var listener = new UpdateListener(
        chrome.developerPrivate.EventType.LOADED,
        function() {
      var node = getRequiredElement(GOOD_EXTENSION_ID);
      assertFalse(node.classList.contains('inactive-extension'));
      this.nextStep();
    }.bind(this));
    chrome.management.setEnabled(GOOD_EXTENSION_ID, true);
  },

  /** @protected */
  verifyUninstallWorks: function() {
    var listener = new UpdateListener(
        chrome.developerPrivate.EventType.UNINSTALLED,
        function() {
      assertEquals(null, $(GOOD_EXTENSION_ID));
      this.nextStep();
    }.bind(this));
    chrome.test.runWithUserGesture(function() {
      chrome.management.uninstall(GOOD_EXTENSION_ID);
    });
  },
};

// Verify that developer mode doesn't change behavior when the number of
// extensions changes.
TEST_F('BasicExtensionSettingsWebUITest', 'testDeveloperModeManyExtensions',
       function() {
  this.testDeveloperMode();
});

TEST_F('BasicExtensionSettingsWebUITest', 'testDisable', function() {
  this.steps = [this.waitForPageLoad, this.verifyDisabledWorks, testDone];
  this.nextStep();
});

TEST_F('BasicExtensionSettingsWebUITest', 'testEnable', function() {
  this.steps = [this.waitForPageLoad,
                this.verifyDisabledWorks,
                this.verifyEnabledWorks,
                testDone];
  this.nextStep();
});

TEST_F('BasicExtensionSettingsWebUITest', 'testUninstall', function() {
  this.steps = [this.waitForPageLoad, this.verifyUninstallWorks, testDone];
  this.nextStep();
});

TEST_F('BasicExtensionSettingsWebUITest', 'testNonEmptyExtensionList',
       function() {
  var verifyListIsNotHiddenAndEmpty = function() {
    assertFalse($('extension-list-wrapper').hidden);
    assertTrue($('no-extensions').hidden);
    assertGT($('extension-settings-list').childNodes.length, 0);
    this.nextStep();
  };

  this.steps = [this.waitForPageLoad, verifyListIsNotHiddenAndEmpty, testDone];
  this.nextStep();
});

function ErrorConsoleExtensionSettingsWebUITest() {}

ErrorConsoleExtensionSettingsWebUITest.prototype = {
  __proto__: ExtensionSettingsWebUITest.prototype,

  /** @override */
  testGenPreamble: function() {
    GEN('  EnableErrorConsole();');
    GEN('  InstallGoodExtension();');
    GEN('  InstallErrorsExtension();');
  },
};

GEN('#if defined(OS_CHROMEOS)');  // Flaky on ChromeOS; http://crbug.com/499884.
GEN('#define MAYBE_testErrorListButtonVisibility ' +
    'DISABLED_testErrorListButtonVisibility');
GEN('#elif defined(OS_WIN)');  // Flaky on Win7 dbg; http://crbug.com/463245.
GEN('#define MAYBE_testErrorListButtonVisibility ' +
    'DISABLED_testErrorListButtonVisibility');
GEN('#else');
GEN('#define MAYBE_testErrorListButtonVisibility ' +
    'testErrorListButtonVisibility');
GEN('#endif');

TEST_F('ErrorConsoleExtensionSettingsWebUITest',
       'MAYBE_testErrorListButtonVisibility', function() {
  var testButtonVisibility = function() {
    var extensionList = $('extension-list-wrapper');

    var visibleButtons = extensionList.querySelectorAll(
        '.errors-link:not([hidden])');
    expectEquals(1, visibleButtons.length);

    if (visibleButtons.length > 0) {
      var errorLink = $(ERROR_EXTENSION_ID).querySelector('.errors-link');
      expectEquals(visibleButtons[0], errorLink);

      var errorIcon = errorLink.querySelector('img');
      expectTrue(errorIcon.classList.contains('extension-error-warning-icon'));
    }

    var hiddenButtons = extensionList.querySelectorAll('.errors-link[hidden]');
    expectEquals(1, hiddenButtons.length);

    this.nextStep();
  };

  this.steps = [this.waitForPageLoad,
                this.enableDeveloperMode,
                testButtonVisibility,
                testDone];
  this.nextStep();
});

/**
 * TestFixture for extension settings WebUI testing (commands config edition).
 * @extends {testing.Test}
 * @constructor
 */
function SettingsCommandsExtensionSettingsWebUITest() {}

SettingsCommandsExtensionSettingsWebUITest.prototype = {
  __proto__: ExtensionSettingsWebUITest.prototype,

  /**
   * A URL to load before starting each test.
   * @type {string}
   * @const
   */
  browsePreload: 'chrome://extensions-frame/configureCommands',
};

TEST_F('SettingsCommandsExtensionSettingsWebUITest', 'testChromeSendHandler',
    function() {
  // Just navigating to the page should trigger the chrome.send().
  var assertOverlayVisible = function() {
    assertTrue($('extension-commands-overlay').classList.contains('showing'));
    this.nextStep();
  };

  this.steps = [this.waitForPageLoad, assertOverlayVisible, testDone];
  this.nextStep();
});

/**
 * @constructor
 * @extends {ExtensionSettingsWebUITest}
 */
function InstallGoodExtensionSettingsWebUITest() {}

InstallGoodExtensionSettingsWebUITest.prototype = {
  __proto__: ExtensionSettingsWebUITest.prototype,

  /** @override */
  testGenPreamble: function() {
    GEN('  InstallGoodExtension();');
  },

  emptyTestForAccessibility() {
    this.steps = [this.waitForPageLoad, testDone];
    this.nextStep();
  },
};

TEST_F('InstallGoodExtensionSettingsWebUITest', 'testAccessibility',
       function() {
  this.emptyTestForAccessibility();
});

TEST_F('InstallGoodExtensionSettingsWebUITest', 'showOptions', function() {
  var showExtensionOptions = function() {
    var optionsOverlay = extensions.ExtensionOptionsOverlay.getInstance();
    optionsOverlay.setExtensionAndShow(GOOD_EXTENSION_ID, 'GOOD!', '',
                                       this.nextStep.bind(this));

    // Preferred size changes don't happen in browser tests. Just fake it.
    document.querySelector('extensionoptions').onpreferredsizechanged(
        {width: 500, height: 500});
  };

  this.steps = [this.waitForPageLoad, showExtensionOptions, testDone];
  this.nextStep();
});

/**
 * @constructor
 * @extends {InstallGoodExtensionSettingsWebUITest}
 */
function ManagedExtensionSettingsWebUITest() {}

ManagedExtensionSettingsWebUITest.prototype = {
  __proto__: InstallGoodExtensionSettingsWebUITest.prototype,

  /** @override */
  testGenPreamble: function() {
    GEN('  AddManagedPolicyProvider();');
    InstallGoodExtensionSettingsWebUITest.prototype.testGenPreamble.call(this);
  },
};

TEST_F('ManagedExtensionSettingsWebUITest', 'testAccessibility', function() {
  this.emptyTestForAccessibility();
});

/**
 * @constructor
 * @extends {InstallGoodExtensionSettingsWebUITest}
 */
function OptionsDialogExtensionSettingsWebUITest() {}

OptionsDialogExtensionSettingsWebUITest.prototype = {
  __proto__: InstallGoodExtensionSettingsWebUITest.prototype,

  /** @override */
  browsePreload: ExtensionSettingsWebUITest.prototype.browsePreload +
      '?options=' + GOOD_EXTENSION_ID,
};

TEST_F('OptionsDialogExtensionSettingsWebUITest', 'testAccessibility',
       function() {
  this.emptyTestForAccessibility();
});
<|endoftext|>


<commit_before>// Copyright (c) 2011 Google, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 * @fileoverview Dygraphs options palette.
 *
 * @author konigsberg@google.com (Robert Konigsberg)
 */
"use strict";

function Palette() {
  this.model = {};
  this.onchange = function() {};
  this.filterBar = null;
}

Palette.createChild = function(type, parentElement) {
  var element = document.createElement(type);
  parentElement.appendChild(element);
  return element;
};

function Tooltip(parent) {
  if (!parent) {
    parent = document.getElementsByTagName("body")[0];
  }
  this.elem = Palette.createChild("div", parent);
  this.title = Palette.createChild("div", this.elem);
  this.elem.className = "tooltip";
  this.title.className = "title";
  this.type = Palette.createChild("div", this.elem);
  this.type.className = "type";
  this.body = Palette.createChild("div", this.elem);
  this.body.className = "body";
  this.hide();
}

Tooltip.prototype.show = function(source, event, title, type, body) {
  this.title.innerHTML = title;
  this.body.innerHTML = body;
  this.type.innerText = type; // innerText for arrays.

  var getTopLeft = function(element) {
    var x = element.offsetLeft;
    var y = element.offsetTop;
    element = element.offsetParent;

    while(element != null) {
      x = parseInt(x) + parseInt(element.offsetLeft);
      y = parseInt(y) + parseInt(element.offsetTop);
      element = element.offsetParent;
    }
    return [y, x];
  }

  this.elem.style.height = source.style.height;
  this.elem.style.width = "280";
  var topLeft = getTopLeft(source);
  this.elem.style.top = parseInt(topLeft[0] + source.offsetHeight) + 'px';
  this.elem.style.left = parseInt(topLeft[1] + 10) + 'px';
  this.elem.style.visibility = "visible";
}

Tooltip.prototype.hide = function() {
  this.elem.style.visibility = "hidden";
}

Palette.prototype.create = function(document, parentElement) {
  var palette = this;

  var table = Palette.createChild("div", parentElement);
  table.className = "palette";
  table.width="300px";

  this.tooltip = new Tooltip();

  var row = Palette.createChild("div", table);
  row.style.visibility = "visible";
  row.className = "header";

  Palette.createChild("span", row).innerText = "Filter:";
  this.filterBar = Palette.createChild("input", Palette.createChild("span", row));
  this.filterBar.onkeyup = function() {
    palette.filter(palette.filterBar.value)
  };
  var go = document.createElement("button");
  Palette.createChild("span", row).appendChild(go);
  go.innerText = "Redraw"
  go.onclick = function() {
    palette.onchange();
  };

  for (var opt in opts) {
    try {
      if (opts.hasOwnProperty(opt)) {
        var type = opts[opt].type;
        var isFunction = type.indexOf("function(") == 0;
        var row = Palette.createChild("div", table);
        row.onmouseover = function(source, title, type, body, e) {
          return function(e) {
            palette.tooltip.show(source, e, title, type, body);
          };
        } (row, opt, type, Dygraph.OPTIONS_REFERENCE[opt].description);
        row.onmouseout = function() { palette.tooltip.hide(); };

        var div = Palette.createChild("span", row);
        div.innerText = opt;
        div.className = "name";

        var value = Palette.createChild("span", row);
        value.className = "option";

        if (isFunction) {
           var input = Palette.createChild("button", value);
           input.onclick = function(opt, palette) {
             return function(event) {
               var entry = palette.model[opt];
               var inputValue = entry.functionString;
               if (inputValue == null || inputValue.length == 0) {
                 inputValue = opts[opt].type + "{ }";
               }
               var value = prompt("enter function", inputValue);
               if (value != null) {
                 if (value.length == 0) {
                   value = null;
                 }
                 if (value != inputValue) {
                   entry.functionString = value;
                   entry.input.innerText = value ? "defined" : "not defined";
                   palette.onchange();
                 }
               }
             }
           }(opt, this);
        } else {
          var input = Palette.createChild("input", value);
          input.onkeypress = function(event) {
            var keycode = event.which;
            if (keycode == 13 || keycode == 8) {
              palette.onchange();
            }
          }

          input.type="text";
        }
        this.model[opt] = { input: input, row: row };
      }
    } catch(err) {
      throw "For option " + opt + ":" + err;
    }
  }
  this.filter("");
}

// TODO: replace semicolon parsing with comma parsing, and supporting quotes.
Palette.parseStringArray = function(value) {
  if (value == null || value.length == 0) {
    return null;
  }
  return value.split(";");
}

Palette.parseBooleanArray = function(value) {
  if (value == null || value.length == 0) {
    return null;
  }
  return value.split(',').map(function(x) { return x.trim() == "true"; });
}

Palette.parseFloatArray = function(value) {
  if (value == null || value.length == 0) {
    return null;
  }
  return value.split(',').map(function(x) { return parseFloat(x); });
}

Palette.parseIntArray = function(value) {
  if (value == null || value.length == 0) {
    return null;
  }
  return value.split(',').map(function(x) { return parseInt(x); });
}

Palette.prototype.read = function() {
  var results = {};
  for (var opt in this.model) {
    if (this.model.hasOwnProperty(opt)) {
      var type = opts[opt].type;
      var isFunction = type.indexOf("function(") == 0;
      var input = this.model[opt].input;
      var value = isFunction ? this.model[opt].functionString : input.value;
      if (value && value.length != 0) {
        if (type == "boolean") {
          results[opt] = value == "true";
        } else if (type == "int") {
          results[opt] = parseInt(value);
        } else if (type == "float") {
          results[opt] = parseFloat(value);
        } else if (type == "array<string>") {
          results[opt] = Palette.parseStringArray(value);
        } else if (type == "array<float>") {
          results[opt] = Palette.parseFloatArray(value);
        } else if (type == "array<boolean>") {
          results[opt] = Palette.parseBooleanArray(value);
        } else if (type == "array<Date>") {
          results[opt] = Palette.parseIntArray(value);
        } else if (isFunction) {
          var localVariable = null;
          eval("localVariable = " + value);
          results[opt] = localVariable;
        } else {
          results[opt] = value;
        }
      }
    }
  }
  return results;
}

/**
 * Write to input elements.
 */
Palette.prototype.write = function(hash) {
  var results = {};
  for (var opt in this.model) {
    //  && hash.hasOwnProperty(opt)
    if (this.model.hasOwnProperty(opt)) {
      var input = this.model[opt].input;
      var type = opts[opt].type;
      var value = hash[opt];
      if (type == "array<string>") {
        if (value) {
          input.value = value.join("; ");
        }
      } else if (type.indexOf("array") == 0) {
        if (value) {
          input.value = value.join(", ");
        }
      } else if (type.indexOf("function(") == 0) {
        input.innerText = value ? "defined" : "not defined";
        this.model[opt].functionString = value ? value.toString() : null;
      } else {
        if (value) {
          input.value = value;
        }
      }
    }
  }
}

Palette.prototype.filter = function(pattern) {
  pattern = pattern.toLowerCase();
  var even = true;
  for (var opt in this.model) {
    if (this.model.hasOwnProperty(opt)) {
      var row = this.model[opt].row;
      var matches = opt.toLowerCase().indexOf(pattern) >= 0;
      row.style.display = matches ? "block" : "none";
      if (matches) {
        row.className = even ? "even" : "odd";
        even = !even;
      }
    }
  }
}
<commit_msg>Filter bar input is now type "search" which looks sexy on mac.<commit_after>// Copyright (c) 2011 Google, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 * @fileoverview Dygraphs options palette.
 *
 * @author konigsberg@google.com (Robert Konigsberg)
 */
"use strict";

function Palette() {
  this.model = {};
  this.onchange = function() {};
  this.filterBar = null;
}

Palette.createChild = function(type, parentElement) {
  var element = document.createElement(type);
  parentElement.appendChild(element);
  return element;
};

function Tooltip(parent) {
  if (!parent) {
    parent = document.getElementsByTagName("body")[0];
  }
  this.elem = Palette.createChild("div", parent);
  this.title = Palette.createChild("div", this.elem);
  this.elem.className = "tooltip";
  this.title.className = "title";
  this.type = Palette.createChild("div", this.elem);
  this.type.className = "type";
  this.body = Palette.createChild("div", this.elem);
  this.body.className = "body";
  this.hide();
}

Tooltip.prototype.show = function(source, event, title, type, body) {
  this.title.innerHTML = title;
  this.body.innerHTML = body;
  this.type.innerText = type; // innerText for arrays.

  var getTopLeft = function(element) {
    var x = element.offsetLeft;
    var y = element.offsetTop;
    element = element.offsetParent;

    while(element != null) {
      x = parseInt(x) + parseInt(element.offsetLeft);
      y = parseInt(y) + parseInt(element.offsetTop);
      element = element.offsetParent;
    }
    return [y, x];
  }

  this.elem.style.height = source.style.height;
  this.elem.style.width = "280";
  var topLeft = getTopLeft(source);
  this.elem.style.top = parseInt(topLeft[0] + source.offsetHeight) + 'px';
  this.elem.style.left = parseInt(topLeft[1] + 10) + 'px';
  this.elem.style.visibility = "visible";
}

Tooltip.prototype.hide = function() {
  this.elem.style.visibility = "hidden";
}

Palette.prototype.create = function(document, parentElement) {
  var palette = this;

  var table = Palette.createChild("div", parentElement);
  table.className = "palette";
  table.width="300px";

  this.tooltip = new Tooltip();

  var row = Palette.createChild("div", table);
  row.style.visibility = "visible";
  row.className = "header";

  Palette.createChild("span", row).innerText = "Filter:";
  this.filterBar = Palette.createChild("input", Palette.createChild("span", row));
  this.filterBar.type = "search";
  this.filterBar.onkeyup = function() {
    palette.filter(palette.filterBar.value)
  };
  this.filterBar.onclick = this.filterBar.onkeyup;
  var go = document.createElement("button");
  Palette.createChild("span", row).appendChild(go);
  go.innerText = "Redraw"
  go.onclick = function() {
    palette.onchange();
  };

  for (var opt in opts) {
    try {
      if (opts.hasOwnProperty(opt)) {
        var type = opts[opt].type;
        var isFunction = type.indexOf("function(") == 0;
        var row = Palette.createChild("div", table);
        row.onmouseover = function(source, title, type, body, e) {
          return function(e) {
            palette.tooltip.show(source, e, title, type, body);
          };
        } (row, opt, type, Dygraph.OPTIONS_REFERENCE[opt].description);
        row.onmouseout = function() { palette.tooltip.hide(); };

        var div = Palette.createChild("span", row);
        div.innerText = opt;
        div.className = "name";

        var value = Palette.createChild("span", row);
        value.className = "option";

        if (isFunction) {
           var input = Palette.createChild("button", value);
           input.onclick = function(opt, palette) {
             return function(event) {
               var entry = palette.model[opt];
               var inputValue = entry.functionString;
               if (inputValue == null || inputValue.length == 0) {
                 inputValue = opts[opt].type + "{ }";
               }
               var value = prompt("enter function", inputValue);
               if (value != null) {
                 if (value.length == 0) {
                   value = null;
                 }
                 if (value != inputValue) {
                   entry.functionString = value;
                   entry.input.innerText = value ? "defined" : "not defined";
                   palette.onchange();
                 }
               }
             }
           }(opt, this);
        } else {
          var input = Palette.createChild("input", value);
          input.onkeypress = function(event) {
            var keycode = event.which;
            if (keycode == 13 || keycode == 8) {
              palette.onchange();
            }
          }

          input.type="text";
        }
        this.model[opt] = { input: input, row: row };
      }
    } catch(err) {
      throw "For option " + opt + ":" + err;
    }
  }
  this.filter("");
}

// TODO: replace semicolon parsing with comma parsing, and supporting quotes.
Palette.parseStringArray = function(value) {
  if (value == null || value.length == 0) {
    return null;
  }
  return value.split(";");
}

Palette.parseBooleanArray = function(value) {
  if (value == null || value.length == 0) {
    return null;
  }
  return value.split(',').map(function(x) { return x.trim() == "true"; });
}

Palette.parseFloatArray = function(value) {
  if (value == null || value.length == 0) {
    return null;
  }
  return value.split(',').map(function(x) { return parseFloat(x); });
}

Palette.parseIntArray = function(value) {
  if (value == null || value.length == 0) {
    return null;
  }
  return value.split(',').map(function(x) { return parseInt(x); });
}

Palette.prototype.read = function() {
  var results = {};
  for (var opt in this.model) {
    if (this.model.hasOwnProperty(opt)) {
      var type = opts[opt].type;
      var isFunction = type.indexOf("function(") == 0;
      var input = this.model[opt].input;
      var value = isFunction ? this.model[opt].functionString : input.value;
      if (value && value.length != 0) {
        if (type == "boolean") {
          results[opt] = value == "true";
        } else if (type == "int") {
          results[opt] = parseInt(value);
        } else if (type == "float") {
          results[opt] = parseFloat(value);
        } else if (type == "array<string>") {
          results[opt] = Palette.parseStringArray(value);
        } else if (type == "array<float>") {
          results[opt] = Palette.parseFloatArray(value);
        } else if (type == "array<boolean>") {
          results[opt] = Palette.parseBooleanArray(value);
        } else if (type == "array<Date>") {
          results[opt] = Palette.parseIntArray(value);
        } else if (isFunction) {
          var localVariable = null;
          eval("localVariable = " + value);
          results[opt] = localVariable;
        } else {
          results[opt] = value;
        }
      }
    }
  }
  return results;
}

/**
 * Write to input elements.
 */
Palette.prototype.write = function(hash) {
  var results = {};
  for (var opt in this.model) {
    //  && hash.hasOwnProperty(opt)
    if (this.model.hasOwnProperty(opt)) {
      var input = this.model[opt].input;
      var type = opts[opt].type;
      var value = hash[opt];
      if (type == "array<string>") {
        if (value) {
          input.value = value.join("; ");
        }
      } else if (type.indexOf("array") == 0) {
        if (value) {
          input.value = value.join(", ");
        }
      } else if (type.indexOf("function(") == 0) {
        input.innerText = value ? "defined" : "not defined";
        this.model[opt].functionString = value ? value.toString() : null;
      } else {
        if (value) {
          input.value = value;
        }
      }
    }
  }
}

Palette.prototype.filter = function(pattern) {
  pattern = pattern.toLowerCase();
  var even = true;
  for (var opt in this.model) {
    if (this.model.hasOwnProperty(opt)) {
      var row = this.model[opt].row;
      var matches = opt.toLowerCase().indexOf(pattern) >= 0;
      row.style.display = matches ? "block" : "none";
      if (matches) {
        row.className = even ? "even" : "odd";
        even = !even;
      }
    }
  }
}
<|endoftext|>


<commit_before>import firebase from "firebase/app";
import "firebase/auth";
import firebaseConfig from "./config/firebaseConfig";
import "regenerator-runtime/runtime";

firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);

const postIdTokenToAuth = (idToken) => {
  return fetch("/authentication", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: idToken,
  });
}

const googleProvider = new firebase.auth.GoogleAuthProvider();
const signIn = (callback) => {
  firebase.auth().signInWithPopup(googleProvider).then(result => {
    let user = result.user;
    user.getIdToken().then(idToken => {
      postIdTokenToAuth(idToken).then((res) => {
        callback(res.ok, {
          email: user.email,
          displayName: user.displayName,
          id: 1, // TEMPORARY
        })
      })
    })
  })
};

const signOut = () => {
  return firebase.auth().currentUser.getIdToken(true).then(() => {
    return fetch("/authentication", {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
      }
    });
  });
};

const persistLoginStatus = (user) => {
  // save user details to localstorage
  localStorage.setItem("user", JSON.stringify(user));
};

const loadLoginStatus = () => {
  // read user details from localstorage
  const user = JSON.parse(localStorage.getItem("user"));
  if (user) {
    return {
      isLoggedIn: true,
      userInfo: user,
    };
  } else {
    return {
      isLoggedIn: false,
    };
  }
};

const clearPersistedLoginStatus = () => {
  // clear user details from localstorage
  localStorage.removeItem("user");
};

export default {
  signIn: signIn,
  signOut: signOut,
  persistLoginStatus: persistLoginStatus,
  loadLoginStatus: loadLoginStatus,
  clearPersistedLoginStatus: clearPersistedLoginStatus,
};
<commit_msg>rebase<commit_after>import firebase from "firebase/app";
import "firebase/auth";
import firebaseConfig from "./config/firebaseConfig";
import "regenerator-runtime/runtime";

firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);

const postIdTokenToAuth = (idToken) => {
  return fetch("/authentication", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: idToken,
  });
};

const googleProvider = new firebase.auth.GoogleAuthProvider();
const signIn = (callback) => {
  firebase
    .auth()
    .signInWithPopup(googleProvider)
    .then((result) => {
      let user = result.user;
      user.getIdToken().then((idToken) => {
        postIdTokenToAuth(idToken).then((res) => {
          callback(res.ok, {
            email: user.email,
            displayName: user.displayName,
            id: 1, // TEMPORARY
          });
        });
      });
    });
};

const signOut = () => {
  return firebase
    .auth()
    .currentUser.getIdToken(true)
    .then(() => {
      return fetch("/authentication", {
        method: "DELETE",
        headers: {
          "Content-Type": "application/json",
        },
      });
    });
  });
};

const persistLoginStatus = (user) => {
  // save user details to localstorage
  localStorage.setItem("user", JSON.stringify(user));
};

const loadLoginStatus = () => {
  // read user details from localstorage
  const user = JSON.parse(localStorage.getItem("user"));
  if (user) {
    return {
      isLoggedIn: true,
      userInfo: user,
    };
  } else {
    return {
      isLoggedIn: false,
    };
  }
};

const clearPersistedLoginStatus = () => {
  // clear user details from localstorage
  localStorage.removeItem("user");
};

export default {
  signIn: signIn,
  signOut: signOut,
  persistLoginStatus: persistLoginStatus,
  loadLoginStatus: loadLoginStatus,
  clearPersistedLoginStatus: clearPersistedLoginStatus,
};
<|endoftext|>


<commit_before>/** @jsx React.DOM */
var React = require('react');
var Router = require('react-router');
var Route = Router.Route;
var Routes = Router.Routes;
var Link = Router.Link;

var App = React.createClass({

  mixins: [ Router.Navigation ],

  getInitialState: function () {
    return {
      tacos: [
        { name: 'duck confit' },
        { name: 'carne asada' },
        { name: 'shrimp' }
      ]
    };
  },

  addTaco: function () {
    var name = prompt('taco name?');
    this.setState({
      tacos: this.state.tacos.concat({name: name})
    });
  },

  handleRemoveTaco: function (removedTaco) {
    var tacos = this.state.tacos.filter(function (taco) {
      return taco.name != removedTaco;
    });
    this.setState({tacos: tacos});
    this.transitionTo('/');
  },

  render: function () {
    var links = this.state.tacos.map(function (taco) {
      return
<Link to="taco" params={taco}>{taco.name}</Link>

    });
    return (

        <button onClick={this.addTaco}>Add Taco</button>

          {links}

          <this.props.activeRouteHandler onRemoveTaco={this.handleRemoveTaco} />

    );
  }
});

var Taco = React.createClass({
  remove: function () {
    this.props.onRemoveTaco(this.props.params.name);
  },

  render: function () {
    return (

{this.props.params.name}

        <button onClick={this.remove}>remove</button>

    );
  }
});

var routes = (
  <Routes>
    <Route handler={App}>
      <Route name="taco" path="taco/:name" handler={Taco}/>
    </Route>
  </Routes>
);

React.renderComponent(routes, document.getElementById('example'));
<commit_msg>Update data-flow example<commit_after>var React = require('react');
var Router = require('react-router');
var { Route, RouteHandler, Link } = Router;

var App = React.createClass({

  mixins: [ Router.Navigation ],

  getInitialState: function () {
    return {
      tacos: [
        { name: 'duck confit' },
        { name: 'carne asada' },
        { name: 'shrimp' }
      ]
    };
  },

  addTaco: function () {
    var name = prompt('taco name?');
    this.setState({
      tacos: this.state.tacos.concat({name: name})
    });
  },

  handleRemoveTaco: function (removedTaco) {
    var tacos = this.state.tacos.filter(function (taco) {
      return taco.name != removedTaco;
    });
    this.setState({tacos: tacos});
    this.transitionTo('/');
  },

  render: function () {
    var links = this.state.tacos.map(function (taco) {
      return
<Link to="taco" params={taco}>{taco.name}</Link>

    });
    return (

        <button onClick={this.addTaco}>Add Taco</button>

          {links}

          <RouteHandler onRemoveTaco={this.handleRemoveTaco}/>

    );
  }
});

var Taco = React.createClass({
  mixins: [ Router.State ],

  remove: function () {
    this.props.onRemoveTaco(this.getParams().name);
  },

  render: function () {
    return (

{this.getParams().name}

        <button onClick={this.remove}>remove</button>

    );
  }
});

var routes = (
  <Route handler={App}>
    <Route name="taco" path="taco/:name" handler={Taco}/>
  </Route>
);

Router.run(routes, function (Handler) {
  React.render(<Handler/>, document.getElementById('example'));
});
<|endoftext|>


<commit_before>/* eslint-disable no-import-assign */
import * as babelTypes from "@babel/types";
import builder from "@babel/types/lib/builders/builder";
import defineType from "@babel/types/lib/definitions/utils";
import * as generatedValidators from "@babel/types/lib/validators/generated";
import * as referencedValidators from "@babel/types/lib/validators/isReferenced";
import definitions, { MARKO_TYPES, MARKO_ALIAS_TYPES } from "./definitions";

const {
  TYPES,
  VISITOR_KEYS,
  FLIPPED_ALIAS_KEYS,
  DEPRECATED_KEYS,
  is,
  getBindingIdentifiers
} = babelTypes;

getBindingIdentifiers.keys["MarkoTag"] = ["var"];
getBindingIdentifiers.keys["MarkoTagBody"] = ["params"];

MARKO_TYPES.forEach(typeName => {
  defineType(typeName, definitions[typeName]);
});

for (const type of [
  ...Object.keys(VISITOR_KEYS),
  ...Object.keys(FLIPPED_ALIAS_KEYS),
  ...Object.keys(DEPRECATED_KEYS)
]) {
  if (!TYPES.includes(type)) TYPES.push(type);
}

MARKO_TYPES.forEach(typeName => {
  const lowerName = typeName[0].toLowerCase() + typeName.slice(1);
  const checkKey = `is${typeName}`;
  const assertKey = `assert${typeName}`;
  babelTypes[checkKey] = (node, opts) => is(typeName, node, opts);
  babelTypes[assertKey] = (node, opts) => assert(typeName, node, opts);
  babelTypes[typeName] = babelTypes[lowerName] = function () {
    return builder.apply(typeName, arguments);
  };
});

MARKO_ALIAS_TYPES.forEach(aliasName => {
  const checkKey = `is${aliasName}`;
  const originalCheck = generatedValidators[checkKey];
  generatedValidators[checkKey] = (node, opts) =>
    is(aliasName, node, opts) || originalCheck(node, opts);
});

const originalIsReferenced = referencedValidators.default;
referencedValidators.default = (node, parent, grandparent) => {
  if (parent.type === "MarkoTag" || parent.type === "MarkoTagBody") {
    return false;
  }
  return originalIsReferenced(node, parent, grandparent);
};

function assert(typeName, node, opts) {
  if (!is(typeName, node, opts)) {
    throw new Error(
      `Expected type "${typeName}" with option ${JSON.stringify(
        opts
      )}, but instead got "${node.type}".`
    );
  }
}
<commit_msg>fix: issue with dynamic tag names not tracking references<commit_after>/* eslint-disable no-import-assign */
import * as babelTypes from "@babel/types";
import builder from "@babel/types/lib/builders/builder";
import defineType from "@babel/types/lib/definitions/utils";
import * as generatedValidators from "@babel/types/lib/validators/generated";
import * as referencedValidators from "@babel/types/lib/validators/isReferenced";
import definitions, { MARKO_TYPES, MARKO_ALIAS_TYPES } from "./definitions";

const {
  TYPES,
  VISITOR_KEYS,
  FLIPPED_ALIAS_KEYS,
  DEPRECATED_KEYS,
  is,
  getBindingIdentifiers
} = babelTypes;

getBindingIdentifiers.keys["MarkoTag"] = ["var"];
getBindingIdentifiers.keys["MarkoTagBody"] = ["params"];

MARKO_TYPES.forEach(typeName => {
  defineType(typeName, definitions[typeName]);
});

for (const type of [
  ...Object.keys(VISITOR_KEYS),
  ...Object.keys(FLIPPED_ALIAS_KEYS),
  ...Object.keys(DEPRECATED_KEYS)
]) {
  if (!TYPES.includes(type)) TYPES.push(type);
}

MARKO_TYPES.forEach(typeName => {
  const lowerName = typeName[0].toLowerCase() + typeName.slice(1);
  const checkKey = `is${typeName}`;
  const assertKey = `assert${typeName}`;
  babelTypes[checkKey] = (node, opts) => is(typeName, node, opts);
  babelTypes[assertKey] = (node, opts) => assert(typeName, node, opts);
  babelTypes[typeName] = babelTypes[lowerName] = function () {
    return builder.apply(typeName, arguments);
  };
});

MARKO_ALIAS_TYPES.forEach(aliasName => {
  const checkKey = `is${aliasName}`;
  const originalCheck = generatedValidators[checkKey];
  generatedValidators[checkKey] = (node, opts) =>
    is(aliasName, node, opts) || originalCheck(node, opts);
});

const originalIsReferenced = referencedValidators.default;
referencedValidators.default = (node, parent, grandparent) => {
  switch (parent.type) {
    case "MarkoTag":
      return parent.var !== node;
    case "MarkoTagBody":
      return false;
    default:
      return originalIsReferenced(node, parent, grandparent);
  }
};

function assert(typeName, node, opts) {
  if (!is(typeName, node, opts)) {
    throw new Error(
      `Expected type "${typeName}" with option ${JSON.stringify(
        opts
      )}, but instead got "${node.type}".`
    );
  }
}
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * StepBackButton button is generally used along side play/pause and forward buttons.
 * Though the listener is generic, the button is typically used to step back in time frame
 *
 * This class uses the same drawing code as StepButton but differs in the following ways
 * The triangle's path is rotated to 180 degrees
 * The order of adding bar and triangle is reversed
 * The content is center aligned by shifting it leftwards
 *
 * @author Sharfudeen Ashraf
 *
 *  @see StepButton.js
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var RoundPushButton = require( 'SUN/buttons/RoundPushButton' );
  var Shape = require( 'KITE/Shape' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var HBox = require( 'SCENERY/nodes/HBox' );

  var DEFAULT_RADIUS = 20;

  /**
   *
   * @param stepFunction
   * @param {Property.<boolean>} playProperty
   * @param {Object} [options]
   * @constructor
   */
  function StepBackButton( stepFunction, playProperty, options ) {
    var stepBackButton = this;
    options = _.extend( {
      radius: DEFAULT_RADIUS
    }, options );

    // step symbol is sized relative to the radius
    var barWidth = options.radius * 0.15;
    var barHeight = options.radius * 0.9;
    var triangleWidth = options.radius * 0.65;
    var triangleHeight = barHeight;

    var barPath = new Rectangle( 0, 0, barWidth, barHeight, { fill: 'black' } );
    var trianglePath = new Path( new Shape().moveTo( 0, triangleHeight / 2 ).lineTo( triangleWidth, 0 ).lineTo( 0, -triangleHeight / 2 ).close(), { fill: 'black' } );
    trianglePath.mutate( { rotation: Math.PI } );

    RoundPushButton.call( this, _.extend( {
      content: new HBox( { children: [ trianglePath, barPath ], spacing: barWidth } ),
      listener: stepFunction,
      radius: options.radius,
      //left shift the content to center align
      xContentOffset: -options.radius * 0.15
    }, options ) );
    this.enabled = false;

    playProperty.link( function( value ) { stepBackButton.enabled = !value; } );
  }

  return inherit( RoundPushButton, StepBackButton );
} );<commit_msg>Added fire on hold to StepBackButton, see https://github.com/phetsims/sun/issues/203<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * StepBackButton button is generally used along side play/pause and forward buttons.
 * Though the listener is generic, the button is typically used to step back in time frame
 *
 * This class uses the same drawing code as StepButton but differs in the following ways
 * The triangle's path is rotated to 180 degrees
 * The order of adding bar and triangle is reversed
 * The content is center aligned by shifting it leftwards
 *
 * @author Sharfudeen Ashraf
 *
 *  @see StepButton.js
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var RoundPushButton = require( 'SUN/buttons/RoundPushButton' );
  var Shape = require( 'KITE/Shape' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var HBox = require( 'SCENERY/nodes/HBox' );

  var DEFAULT_RADIUS = 20;

  /**
   *
   * @param stepFunction
   * @param {Property.<boolean>} playProperty
   * @param {Object} [options]
   * @constructor
   */
  function StepBackButton( stepFunction, playProperty, options ) {
    var stepBackButton = this;
    options = _.extend( {
      radius: DEFAULT_RADIUS,
      fireOnHold: true
    }, options );

    // step symbol is sized relative to the radius
    var barWidth = options.radius * 0.15;
    var barHeight = options.radius * 0.9;
    var triangleWidth = options.radius * 0.65;
    var triangleHeight = barHeight;

    var barPath = new Rectangle( 0, 0, barWidth, barHeight, { fill: 'black' } );
    var trianglePath = new Path( new Shape().moveTo( 0, triangleHeight / 2 ).lineTo( triangleWidth, 0 ).lineTo( 0, -triangleHeight / 2 ).close(), { fill: 'black' } );
    trianglePath.mutate( { rotation: Math.PI } );

    RoundPushButton.call( this, _.extend( {
      content: new HBox( { children: [ trianglePath, barPath ], spacing: barWidth } ),
      listener: stepFunction,
      radius: options.radius,
      //left shift the content to center align
      xContentOffset: -options.radius * 0.15
    }, options ) );
    this.enabled = false;

    playProperty.link( function( value ) { stepBackButton.enabled = !value; } );
  }

  return inherit( RoundPushButton, StepBackButton );
} );<|endoftext|>


<commit_before>'use strict';

describe('Dashboard Directive tests', function() {

    var $compile,
        $rootScope,
        $scope,
        directive;

    // Load the myApp module, which contains the directive
    beforeEach(module('adf'));

    // Store references to $rootScope and $compile
    // so they are available to all tests in this describe block
    beforeEach(inject(function(_$compile_, _$rootScope_){
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        directive = '<adf-dashboard name="{{name}}" collapsible="{{collapsible}}" maximizable="{{maximizable}}" structure="4-8" adf-model="model" />';

        $scope.name = 'sample-01';
        $scope.model = {
            title: "Sample 01",
            structure: "4-8",
            rows: [{
                columns: [{
                    styleClass: "col-md-4",
                    widgets: []
                }]
            }]
        };
        $scope.collapsible = false;
        $scope.maximizable = false;

    }));

    function compileTemplate(template) {
        // Compile a piece of HTML containing the directive
        var el = $compile(template)($scope);
        $scope.$digest();
        return el;
    }

    it('should have the proper name in the h1 element (default template)', function() {

        var element = compileTemplate(directive);
        expect(element.find("h1").text().trim()).toBe('Sample 01');
    });

    it('should not change the name when the title changes (default template)', function() {

        var element = compileTemplate(directive);
        expect(element.find("h1").text().trim()).toBe('Sample 01');

        // Change the name of the dashboard
        $scope.name = 'Sample 02';
        expect(element.find("h1").text().trim()).toBe('Sample 01');
    });

    it('should not change the name when the title changes (default template)', function() {

        var element = compileTemplate(directive);
        expect(element.find("h1").text().trim()).toBe('Sample 01');

        // Change the name of the dashboard
        $scope.name = 'Sample 02';
        expect(element.find("h1").text().trim()).toBe('Sample 01');
    });

    it('should toggle edit mode correctly', function() {

        var element = compileTemplate(directive);
        expect(element.controller).not.toBeUndefined();
        expect($scope).not.toBeUndefined();

        var isolatedScope = element.isolateScope();

        // By default it is false
        expect(isolatedScope.editMode).toBeFalsy();

        // Enable edit mode
        isolatedScope.toggleEditMode();
        expect(isolatedScope.editMode).toBeTruthy();

        // Disable edit mode
        isolatedScope.toggleEditMode();
        expect(isolatedScope.editMode).toBeFalsy();
    });

    it('should cancel edit mode correctly', function() {

        var element = compileTemplate(directive);
        expect(element.controller).not.toBeUndefined();
        expect($scope).not.toBeUndefined();

        var isolatedScope = element.isolateScope();

        // By default it is false
        expect(isolatedScope.editMode).toBeFalsy();

        // Enable edit mode
        isolatedScope.toggleEditMode();
        expect(isolatedScope.editMode).toBeTruthy();

        // Cancel edit mode
        isolatedScope.cancelEditMode();
        expect(isolatedScope.editMode).toBeFalsy();
    });

    it('should dispatch the `dfDashboardCollapseExapand` event downwards to all child scopes (and their children)', function() {

        var element = compileTemplate(directive);
        expect(element.controller).not.toBeUndefined();
        expect($scope).not.toBeUndefined();

        var isolatedScope = element.isolateScope();
        spyOn($rootScope, '$broadcast');

        // Enable edit mode
        isolatedScope.collapseAll(1);
        expect($rootScope.$broadcast).toHaveBeenCalledWith('adfDashboardCollapseExapand',{collapseExpandStatus : 1});
    });

});
<commit_msg>added missing license header<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2015, Sebastian Sdorra
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

describe('Dashboard Directive tests', function() {

    var $compile,
        $rootScope,
        $scope,
        directive;

    // Load the myApp module, which contains the directive
    beforeEach(module('adf'));

    // Store references to $rootScope and $compile
    // so they are available to all tests in this describe block
    beforeEach(inject(function(_$compile_, _$rootScope_){
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        directive = '<adf-dashboard name="{{name}}" collapsible="{{collapsible}}" maximizable="{{maximizable}}" structure="4-8" adf-model="model" />';

        $scope.name = 'sample-01';
        $scope.model = {
            title: "Sample 01",
            structure: "4-8",
            rows: [{
                columns: [{
                    styleClass: "col-md-4",
                    widgets: []
                }]
            }]
        };
        $scope.collapsible = false;
        $scope.maximizable = false;

    }));

    function compileTemplate(template) {
        // Compile a piece of HTML containing the directive
        var el = $compile(template)($scope);
        $scope.$digest();
        return el;
    }

    it('should have the proper name in the h1 element (default template)', function() {

        var element = compileTemplate(directive);
        expect(element.find("h1").text().trim()).toBe('Sample 01');
    });

    it('should not change the name when the title changes (default template)', function() {

        var element = compileTemplate(directive);
        expect(element.find("h1").text().trim()).toBe('Sample 01');

        // Change the name of the dashboard
        $scope.name = 'Sample 02';
        expect(element.find("h1").text().trim()).toBe('Sample 01');
    });

    it('should not change the name when the title changes (default template)', function() {

        var element = compileTemplate(directive);
        expect(element.find("h1").text().trim()).toBe('Sample 01');

        // Change the name of the dashboard
        $scope.name = 'Sample 02';
        expect(element.find("h1").text().trim()).toBe('Sample 01');
    });

    it('should toggle edit mode correctly', function() {

        var element = compileTemplate(directive);
        expect(element.controller).not.toBeUndefined();
        expect($scope).not.toBeUndefined();

        var isolatedScope = element.isolateScope();

        // By default it is false
        expect(isolatedScope.editMode).toBeFalsy();

        // Enable edit mode
        isolatedScope.toggleEditMode();
        expect(isolatedScope.editMode).toBeTruthy();

        // Disable edit mode
        isolatedScope.toggleEditMode();
        expect(isolatedScope.editMode).toBeFalsy();
    });

    it('should cancel edit mode correctly', function() {

        var element = compileTemplate(directive);
        expect(element.controller).not.toBeUndefined();
        expect($scope).not.toBeUndefined();

        var isolatedScope = element.isolateScope();

        // By default it is false
        expect(isolatedScope.editMode).toBeFalsy();

        // Enable edit mode
        isolatedScope.toggleEditMode();
        expect(isolatedScope.editMode).toBeTruthy();

        // Cancel edit mode
        isolatedScope.cancelEditMode();
        expect(isolatedScope.editMode).toBeFalsy();
    });

    it('should dispatch the `dfDashboardCollapseExapand` event downwards to all child scopes (and their children)', function() {

        var element = compileTemplate(directive);
        expect(element.controller).not.toBeUndefined();
        expect($scope).not.toBeUndefined();

        var isolatedScope = element.isolateScope();
        spyOn($rootScope, '$broadcast');

        // Enable edit mode
        isolatedScope.collapseAll(1);
        expect($rootScope.$broadcast).toHaveBeenCalledWith('adfDashboardCollapseExapand',{collapseExpandStatus : 1});
    });

});
<|endoftext|>