<commit_before>// Delete the existing definitions of these course wizard modules
// So that we can redefine/customize them.
delete require.s.contexts._.defined['jsx/course_wizard/ListItems'];
delete require.s.contexts._.defined['jsx/course_wizard/Checklist'];
delete require.s.contexts._.defined['jsx/course_wizard/CourseWizard'];

define('jsx/course_wizard/ListItems', ['i18n!course_wizard'], function() {
	return [{
            key: "content_import",
            complete: ENV.COURSE_WIZARD.checklist_states.import_step,
            title: "Import Content",
            text: "If you've been using another course management system, you probably have stuff in there that you're going to want moved over to Canvas. We can walk you through the process of easily migrating your content into Canvas.",
            url: ENV.COURSE_WIZARD.urls.content_import,
            iconClass: "icon-upload"
        }, {
            key: "publish_course",
            complete: ENV.COURSE_WIZARD.checklist_states.publish_step,
            title: "Publish the Course",
            text: "All finished?  Time to publish your course!  Click the button below to make it official! Publishing will allow the users to begin participating in the course.",
            non_registered_text: "This course is claimed and ready, but you'll need to finish the registration process before you can publish the course.  You should have received an email from Canvas with a link to finish the process.  Be sure to check your spam box.",
            iconClass: "icon-publish"
        }];
});

define('jsx/course_wizard/Checklist', ['react', './ChecklistItem', './ListItems'], function(e, a, s) {
	var t = e.createClass({
		displayName: "Checklist",
		getInitialState: function() {
			return {
				selectedItem: this.props.selectedItem || ""
			}
		},
		componentWillReceiveProps: function(e) {
			this.setState({
				selectedItem: e.selectedItem
			})
		},
		renderChecklist: function() {
			return s.map(function(e) {
				var s = this.state.selectedItem === e.key,
					t = "wizard_" + e.key;
				return a({
					complete: e.complete,
					id: t,
					key: e.key,
					stepKey: e.key,
					title: e.title,
					onClick: this.props.clickHandler,
					isSelected: s
				})
			}.bind(this))
		},
		render: function() {
			var a = this.renderChecklist();
			return e.DOM.div({
				className: this.props.className
			}, a)
		}
	});
	return t;
});

define("jsx/course_wizard/CourseWizard", [
  'jquery',
  'react',
  'i18n!course_wizard',
  'react-modal',
  './InfoFrame',
  './Checklist',
  'compiled/userSettings',
  'compiled/jquery.rails_flash_notifications'
], function($, React, I18n, ReactModal, InfoFrame, Checklist, userSettings) {

  var CourseWizard = React.createClass({
      displayName: 'CourseWizard',

      propTypes: {
        showWizard: React.PropTypes.bool,
        overlayClassName: React.PropTypes.string
      },

      getInitialState: function () {
        return {
          showWizard: this.props.showWizard,
          selectedItem: false
        };
      },

      componentDidMount: function () {
        this.refs.closeLink.getDOMNode().focus();
        $(this.refs.wizardBox.getDOMNode()).removeClass('ic-wizard-box--is-closed');
        $.screenReaderFlashMessageExclusive(I18n.t("Course Setup Wizard is showing."));
      },

      componentWillReceiveProps: function (nextProps) {
        this.setState({
          showWizard: nextProps.showWizard
        }, () => {
          $(this.refs.wizardBox.getDOMNode()).removeClass('ic-wizard-box--is-closed');
          if (this.state.showWizard) {
            this.refs.closeLink.getDOMNode().focus();
          }
        });
      },

      /**
       * Handles what should happen when a checklist item is clicked.
       */
      checklistClickHandler: function (itemToShowKey) {
        this.setState({
          selectedItem: itemToShowKey
        });
      },

      closeModal: function (event) {
        if (event) {
          event.preventDefault()
        };

        var pathname = window.location.pathname;
        userSettings.set('hide_wizard_' + pathname, true);

        this.setState({
          showWizard: false
        })
      },

      render: function () {
          return (
              React.createElement(ReactModal, {
                isOpen: this.state.showWizard,
                onRequestClose: this.closeModal,
                overlayClassName: this.props.overlayClassName
              },
                React.createElement("div", {ref: "wizardBox", className: "ic-wizard-box"},
                  React.createElement("div", {className: "ic-wizard-box__header"},
                    React.createElement("a", {href: "/", className: "ic-wizard-box__logo-link"},
                      React.createElement("span", {className: "screenreader-only"}, I18n.t("My dashboard"))
                    ),
                    React.createElement(Checklist, {className: "ic-wizard-box__nav",
                               selectedItem: this.state.selectedItem,
                               clickHandler: this.checklistClickHandler}
                    )
                  ),
                  React.createElement("div", {className: "ic-wizard-box__main"},
                    React.createElement("div", {className: "ic-wizard-box__close"},
                      React.createElement("div", {className: "ic-Expand-link ic-Expand-link--Secondary ic-Expand-link--from-right"},
                        React.createElement("a", {ref: "closeLink", href: "#", className: "ic-Expand-link__trigger", onClick: this.closeModal},
                          React.createElement("div", {className: "ic-Expand-link__layout"},
                            React.createElement("i", {className: "icon-x ic-Expand-link__icon"}),
                            React.createElement("span", {className: "ic-Expand-link__text"}, I18n.t("Close and return to Canvas"))
                          )
                        )
                      )
                    ),
                    React.createElement(InfoFrame, {className: "ic-wizard-box__content", itemToShow: this.state.selectedItem, closeModal: this.closeModal})
                  )
                )
              )
          );
      }
  });

  return CourseWizard;
});

require(['jquery', 'react'], function($, React) {
    /*
     * This essentially unmounts the existing React CourseWizard Component
	 * bound to the onclick handler of the "Setup Checklist" button.
     */
	React.unmountComponentAtNode($("#wizard_box")[0]);
    $(".wizard_popup_link").off("click");
});

require(['jquery', 'react', 'compiled/userSettings', 'jsx/course_wizard/CourseWizard'], function($, React, userSettings, CourseWizard) {
   /*
    * This essentially handles binding the button events and calling out to the
    * CourseWizard React component that is the actual wizard.
    */
  var $wizard_box, courseWizardFactory, pathname;
  $wizard_box = $("#wizard_box");
  pathname = window.location.pathname;
  courseWizardFactory = React.createFactory(CourseWizard);
  return $(".wizard_popup_link").click(function(event) {
    return React.render(courseWizardFactory({
      overlayClassName: 'CourseWizard__modalOverlay',
      showWizard: true
    }), $wizard_box[0]);
  });
});
<commit_msg>Updated overrides.<commit_after>// Delete the existing definitions of these course wizard modules
// So that we can redefine/customize them.
delete require.s.contexts._.defined['jsx/course_wizard/ListItems'];
delete require.s.contexts._.defined['jsx/course_wizard/Checklist'];
delete require.s.contexts._.defined['jsx/course_wizard/CourseWizard'];

define('jsx/course_wizard/ListItems', ['i18n!course_wizard'], function() {
	return [{
            key: "content_import",
            complete: ENV.COURSE_WIZARD.checklist_states.import_step,
            title: "Import Content",
            text: "If you've been using another course management system, you probably have stuff in there that you're going to want moved over to Canvas. We can walk you through the process of easily migrating your content into Canvas.",
            url: ENV.COURSE_WIZARD.urls.content_import,
            iconClass: "icon-upload"
        }, {
            key: "publish_course",
            complete: ENV.COURSE_WIZARD.checklist_states.publish_step,
            title: "Publish the Course",
            text: "All finished?  Time to publish your course!  Click the button below to make it official! Publishing will allow the users to begin participating in the course.",
            non_registered_text: "This course is claimed and ready, but you'll need to finish the registration process before you can publish the course.  You should have received an email from Canvas with a link to finish the process.  Be sure to check your spam box.",
            iconClass: "icon-publish"
        }];
});

define('jsx/course_wizard/Checklist', ['react', './ChecklistItem', './ListItems'], function(e, a, s) {
	var t = e.createClass({
		displayName: "Checklist",
		getInitialState: function() {
			return {
				selectedItem: this.props.selectedItem || ""
			}
		},
		componentWillReceiveProps: function(e) {
			this.setState({
				selectedItem: e.selectedItem
			})
		},
		renderChecklist: function() {
			return s.map(function(e) {
				var s = this.state.selectedItem === e.key,
					t = "wizard_" + e.key;
				return a({
					complete: e.complete,
					id: t,
					key: e.key,
					stepKey: e.key,
					title: e.title,
					onClick: this.props.clickHandler,
					isSelected: s
				})
			}.bind(this))
		},
		render: function() {
			var a = this.renderChecklist();
			return e.DOM.div({
				className: this.props.className
			}, a)
		}
	});
	return t;
});

define("jsx/course_wizard/CourseWizard", [
  'jquery',
  'react',
  'i18n!course_wizard',
  'react-modal',
  './InfoFrame',
  './Checklist',
  'compiled/userSettings',
  'compiled/jquery.rails_flash_notifications'
], function($, React, I18n, ReactModal, InfoFrame, Checklist, userSettings) {

  var CourseWizard = React.createClass({
      displayName: 'CourseWizard',

      propTypes: {
        showWizard: React.PropTypes.bool,
        overlayClassName: React.PropTypes.string
      },

      getInitialState: function () {
        return {
          showWizard: this.props.showWizard,
          selectedItem: false
        };
      },

      componentDidMount: function () {
        this.refs.closeLink.getDOMNode().focus();
        $(this.refs.wizardBox.getDOMNode()).removeClass('ic-wizard-box--is-closed');
        $.screenReaderFlashMessageExclusive(I18n.t("Course Setup Wizard is showing."));
      },

      componentWillReceiveProps: function (nextProps) {
        this.setState({
          showWizard: nextProps.showWizard
        }, function() {
          $(this.refs.wizardBox.getDOMNode()).removeClass('ic-wizard-box--is-closed');
          if (this.state.showWizard) {
            this.refs.closeLink.getDOMNode().focus();
          }
        });
      },

      /**
       * Handles what should happen when a checklist item is clicked.
       */
      checklistClickHandler: function (itemToShowKey) {
        this.setState({
          selectedItem: itemToShowKey
        });
      },

      closeModal: function (event) {
        if (event) {
          event.preventDefault()
        };

        var pathname = window.location.pathname;
        userSettings.set('hide_wizard_' + pathname, true);

        this.setState({
          showWizard: false
        })
      },

      render: function () {
          return (
              React.createElement(ReactModal, {
                isOpen: this.state.showWizard,
                onRequestClose: this.closeModal,
                overlayClassName: this.props.overlayClassName
              },
                React.createElement("div", {ref: "wizardBox", className: "ic-wizard-box"},
                  React.createElement("div", {className: "ic-wizard-box__header"},
                    React.createElement("a", {href: "/", className: "ic-wizard-box__logo-link"},
                      React.createElement("span", {className: "screenreader-only"}, I18n.t("My dashboard"))
                    ),
                    React.createElement(Checklist, {className: "ic-wizard-box__nav",
                               selectedItem: this.state.selectedItem,
                               clickHandler: this.checklistClickHandler}
                    )
                  ),
                  React.createElement("div", {className: "ic-wizard-box__main"},
                    React.createElement("div", {className: "ic-wizard-box__close"},
                      React.createElement("div", {className: "ic-Expand-link ic-Expand-link--Secondary ic-Expand-link--from-right"},
                        React.createElement("a", {ref: "closeLink", href: "#", className: "ic-Expand-link__trigger", onClick: this.closeModal},
                          React.createElement("div", {className: "ic-Expand-link__layout"},
                            React.createElement("i", {className: "icon-x ic-Expand-link__icon"}),
                            React.createElement("span", {className: "ic-Expand-link__text"}, I18n.t("Close and return to Canvas"))
                          )
                        )
                      )
                    ),
                    React.createElement(InfoFrame, {className: "ic-wizard-box__content", itemToShow: this.state.selectedItem, closeModal: this.closeModal})
                  )
                )
              )
          );
      }
  });

  return CourseWizard;
});

require(['jquery', 'react'], function($, React) {
    /*
     * This essentially unmounts the existing React CourseWizard Component
	 * bound to the onclick handler of the "Setup Checklist" button.
     */
	React.unmountComponentAtNode($("#wizard_box")[0]);
    $(".wizard_popup_link").off("click");
});

require(['jquery', 'react', 'compiled/userSettings', 'jsx/course_wizard/CourseWizard'], function($, React, userSettings, CourseWizard) {
   /*
    * This essentially handles binding the button events and calling out to the
    * CourseWizard React component that is the actual wizard.
    */
  var $wizard_box, courseWizardFactory, pathname;
  $wizard_box = $("#wizard_box");
  pathname = window.location.pathname;
  courseWizardFactory = React.createFactory(CourseWizard);
  return $(".wizard_popup_link").click(function(event) {
    return React.render(courseWizardFactory({
      overlayClassName: 'CourseWizard__modalOverlay',
      showWizard: true
    }), $wizard_box[0]);
  });
});
<|endoftext|>


<commit_before>// Delete the existing definitions of these course wizard modules
// So that we can redefine/customize them.
delete require.s.contexts._.defined['jsx/course_wizard/ListItems'];
delete require.s.contexts._.defined['jsx/course_wizard/Checklist'];
delete require.s.contexts._.defined['jsx/course_wizard/CourseWizard'];

define(['i18n!course_wizard'], function (I18n) {
    /**
     * Returns an array containing all the possible items for the checklist
     */
    return [
      {
        key:'content_import',
        complete: ENV.COURSE_WIZARD.checklist_states.import_step,
        title: I18n.t("Import Content"),
        text: I18n.t("If you've been using another course management system, you probably have stuff in there that you're going to want moved over to Canvas. We can walk you through the process of easily migrating your content into Canvas."),
        url: ENV.COURSE_WIZARD.urls.content_import,
        iconClass: 'icon-upload'
      },
      {
        key:'add_assignments',
        complete: ENV.COURSE_WIZARD.checklist_states.assignment_step,
        title: I18n.t("Add Course Assignments"),
        text: I18n.t("Add your assignments.  You can just make a long list, or break them up into groups - and even specify weights for each assignment group."),
        url: ENV.COURSE_WIZARD.urls.add_assignments,
        iconClass: 'icon-assignment'
      },
// NOTE: Removing this menu item.
//      {
//        key:'add_students',
//        complete: ENV.COURSE_WIZARD.checklist_states.add_student_step,
//        title: I18n.t("Add Students to the Course"),
//        text: I18n.t("You'll definitely want some of these.  What's the fun of teaching a course if nobody's even listening?"),
//        url: ENV.COURSE_WIZARD.urls.add_students,
//        iconClass: 'icon-group-new'
//      },
      {
        key:'add_files',
        complete: ENV.COURSE_WIZARD.checklist_states.import_step, /* Super odd in the existing wizard this is set to display: none */
        title: I18n.t("Add Files to the Course"),
        text: I18n.t("The Files tab is the place to share lecture slides, example documents, study helps -- anything your students will want to download.  Uploading and organizing your files is easy with Canvas.  We'll show you how."),
        url: ENV.COURSE_WIZARD.urls.add_files,
        iconClass: 'icon-note-light'
      },
      {
        key:'select_navigation',
        complete: ENV.COURSE_WIZARD.checklist_states.navigation_step,
        title: I18n.t("Select Navigation Links"),
        text: I18n.t("By default all links are enabled for a course.  Students won't see links to sections that don't have content.  For example, if you haven't created any quizzes, they won't see the quizzes link.  You can sort and explicitly disable these links if there are areas of the course you don't want your students accessing."),
        url: ENV.COURSE_WIZARD.urls.select_navigation,
        iconClass: 'icon-hamburger'
      },
      {
        key:'home_page',
        complete: ENV.COURSE_WIZARD.checklist_states.home_page_step,
        title: I18n.t("Choose a Course Home Page"),
        text: I18n.t("When people visit the course, this is the page they'll see.  You can set it to show an activity stream, the list of course modules, a syllabus, or a custom page you write yourself.  The default is the course activity stream."),
        iconClass: 'icon-home'
      },
      {
        key:'course_calendar',
        complete: ENV.COURSE_WIZARD.checklist_states.calendar_event_step,
        title: I18n.t("Add Course Calendar Events"),
        text: I18n.t("Here's a great chance to get to know the calendar and add any non-assignment events you might have to the course. Don't worry, we'll help you through it."),
        url: ENV.COURSE_WIZARD.urls.course_calendar,
        iconClass: 'icon-calendar-month'
      },
// NOTE: Changed text: all instances of "TAs" changed to "TFs"
      {
        key:'add_tas',
        complete: ENV.COURSE_WIZARD.checklist_states.add_ta_step,
        title: I18n.t("Add TFs to the Course"),
        text: I18n.t("You may want to assign some TFs to help you with the course.  TFs can grade student submissions, help moderate the discussions and even update due dates and assignment details for you."),
        url: ENV.COURSE_WIZARD.urls.add_tas,
        iconClass: 'icon-educators'
      },
// NOTE: Added item for customizing the academic integrity policy for the course
      {
        key:'policy_wizard',
        complete: ENV.COURSE_WIZARD.checklist_states.publish_step,
        title: I18n.t("Customize academic integrity policy"),
        text: I18n.t("Customize the academic integrity policy for your course."),
        url: "https://canvas.harvard.edu/courses/39/external_tools/1513",
        iconClass: 'icon-educators'
	  },
      {
        key:'publish_course',
        complete: ENV.COURSE_WIZARD.checklist_states.publish_step,
        title: I18n.t("Publish the Course"),
        text: I18n.t("All finished?  Time to publish your course!  Click the button below to make it official! Publishing will allow the users to begin participating in the course."),
        non_registered_text: I18n.t("This course is claimed and ready, but you'll need to finish the registration process before you can publish the course.  You should have received an email from Canvas with a link to finish the process.  Be sure to check your spam box."),
        iconClass: 'icon-publish'
      }
    ]
});

define('jsx/course_wizard/Checklist', ['react', './ChecklistItem', './ListItems'], function(e, a, s) {
	var t = e.createClass({
		displayName: "Checklist",
		getInitialState: function() {
			return {
				selectedItem: this.props.selectedItem || ""
			}
		},
		componentWillReceiveProps: function(e) {
			this.setState({
				selectedItem: e.selectedItem
			})
		},
		renderChecklist: function() {
			return s.map(function(e) {
				var s = this.state.selectedItem === e.key,
					t = "wizard_" + e.key;
				return a({
					complete: e.complete,
					id: t,
					key: e.key,
					stepKey: e.key,
					title: e.title,
					onClick: this.props.clickHandler,
					isSelected: s
				})
			}.bind(this))
		},
		render: function() {
			var a = this.renderChecklist();
			return e.DOM.div({
				className: this.props.className
			}, a)
		}
	});
	return t;
});

define("jsx/course_wizard/CourseWizard", [
  'jquery',
  'react',
  'i18n!course_wizard',
  'react-modal',
  './InfoFrame',
  './Checklist',
  'compiled/userSettings',
  'compiled/jquery.rails_flash_notifications'
], function($, React, I18n, ReactModal, InfoFrame, Checklist, userSettings) {

  var CourseWizard = React.createClass({
      displayName: 'CourseWizard',

      propTypes: {
        showWizard: React.PropTypes.bool,
        overlayClassName: React.PropTypes.string
      },

      getInitialState: function () {
        return {
          showWizard: this.props.showWizard,
          selectedItem: false
        };
      },

      componentDidMount: function () {
        this.refs.closeLink.getDOMNode().focus();
        $(this.refs.wizardBox.getDOMNode()).removeClass('ic-wizard-box--is-closed');
        $.screenReaderFlashMessageExclusive(I18n.t("Course Setup Wizard is showing."));
      },

      componentWillReceiveProps: function (nextProps) {
        this.setState({
          showWizard: nextProps.showWizard
        }, function() {
          $(this.refs.wizardBox.getDOMNode()).removeClass('ic-wizard-box--is-closed');
          if (this.state.showWizard) {
            this.refs.closeLink.getDOMNode().focus();
          }
        });
      },

      /**
       * Handles what should happen when a checklist item is clicked.
       */
      checklistClickHandler: function (itemToShowKey) {
        this.setState({
          selectedItem: itemToShowKey
        });
      },

      closeModal: function (event) {
        if (event) {
          event.preventDefault()
        };

        var pathname = window.location.pathname;
        userSettings.set('hide_wizard_' + pathname, true);

        this.setState({
          showWizard: false
        })
      },

      render: function () {
          return (
              React.createElement(ReactModal, {
                isOpen: this.state.showWizard,
                onRequestClose: this.closeModal,
                overlayClassName: this.props.overlayClassName
              },
                React.createElement("div", {ref: "wizardBox", className: "ic-wizard-box"},
                  React.createElement("div", {className: "ic-wizard-box__header"},
                    React.createElement("a", {href: "/", className: "ic-wizard-box__logo-link"},
                      React.createElement("span", {className: "screenreader-only"}, I18n.t("My dashboard"))
                    ),
                    React.createElement(Checklist, {className: "ic-wizard-box__nav",
                               selectedItem: this.state.selectedItem,
                               clickHandler: this.checklistClickHandler}
                    )
                  ),
                  React.createElement("div", {className: "ic-wizard-box__main"},
                    React.createElement("div", {className: "ic-wizard-box__close"},
                      React.createElement("div", {className: "ic-Expand-link ic-Expand-link--Secondary ic-Expand-link--from-right"},
                        React.createElement("a", {ref: "closeLink", href: "#", className: "ic-Expand-link__trigger", onClick: this.closeModal},
                          React.createElement("div", {className: "ic-Expand-link__layout"},
                            React.createElement("i", {className: "icon-x ic-Expand-link__icon"}),
                            React.createElement("span", {className: "ic-Expand-link__text"}, I18n.t("Close and return to Canvas"))
                          )
                        )
                      )
                    ),
                    React.createElement(InfoFrame, {className: "ic-wizard-box__content", itemToShow: this.state.selectedItem, closeModal: this.closeModal})
                  )
                )
              )
          );
      }
  });

  return CourseWizard;
});

require(['jquery', 'react'], function($, React) {
    /*
     * This essentially unmounts the existing React CourseWizard Component
	 * bound to the onclick handler of the "Setup Checklist" button.
     */
	React.unmountComponentAtNode($("#wizard_box")[0]);
    $(".wizard_popup_link").off("click");
});

require(['jquery', 'react', 'compiled/userSettings', 'jsx/course_wizard/CourseWizard'], function($, React, userSettings, CourseWizard) {
   /*
    * This essentially handles binding the button events and calling out to the
    * CourseWizard React component that is the actual wizard.
    */
  var $wizard_box, courseWizardFactory, pathname;
  $wizard_box = $("#wizard_box");
  pathname = window.location.pathname;
  courseWizardFactory = React.createFactory(CourseWizard);
  return $(".wizard_popup_link").click(function(event) {
    return React.render(courseWizardFactory({
      overlayClassName: 'CourseWizard__modalOverlay',
      showWizard: true
    }), $wizard_box[0]);
  });
});
<commit_msg>Updated overrides.<commit_after>// Delete the existing definitions of these course wizard modules
// So that we can redefine/customize them.
delete require.s.contexts._.defined['jsx/course_wizard/ListItems'];
delete require.s.contexts._.defined['jsx/course_wizard/Checklist'];
delete require.s.contexts._.defined['jsx/course_wizard/CourseWizard'];

define('jsx/course_wizard/ListItems', ['i18n!course_wizard'], function (I18n) {
    /**
     * Returns an array containing all the possible items for the checklist
     */
    return [
      {
        key:'content_import',
        complete: ENV.COURSE_WIZARD.checklist_states.import_step,
        title: I18n.t("Import Content"),
        text: I18n.t("If you've been using another course management system, you probably have stuff in there that you're going to want moved over to Canvas. We can walk you through the process of easily migrating your content into Canvas."),
        url: ENV.COURSE_WIZARD.urls.content_import,
        iconClass: 'icon-upload'
      },
      {
        key:'add_assignments',
        complete: ENV.COURSE_WIZARD.checklist_states.assignment_step,
        title: I18n.t("Add Course Assignments"),
        text: I18n.t("Add your assignments.  You can just make a long list, or break them up into groups - and even specify weights for each assignment group."),
        url: ENV.COURSE_WIZARD.urls.add_assignments,
        iconClass: 'icon-assignment'
      },
// NOTE: Removing this menu item.
//      {
//        key:'add_students',
//        complete: ENV.COURSE_WIZARD.checklist_states.add_student_step,
//        title: I18n.t("Add Students to the Course"),
//        text: I18n.t("You'll definitely want some of these.  What's the fun of teaching a course if nobody's even listening?"),
//        url: ENV.COURSE_WIZARD.urls.add_students,
//        iconClass: 'icon-group-new'
//      },
      {
        key:'add_files',
        complete: ENV.COURSE_WIZARD.checklist_states.import_step, /* Super odd in the existing wizard this is set to display: none */
        title: I18n.t("Add Files to the Course"),
        text: I18n.t("The Files tab is the place to share lecture slides, example documents, study helps -- anything your students will want to download.  Uploading and organizing your files is easy with Canvas.  We'll show you how."),
        url: ENV.COURSE_WIZARD.urls.add_files,
        iconClass: 'icon-note-light'
      },
      {
        key:'select_navigation',
        complete: ENV.COURSE_WIZARD.checklist_states.navigation_step,
        title: I18n.t("Select Navigation Links"),
        text: I18n.t("By default all links are enabled for a course.  Students won't see links to sections that don't have content.  For example, if you haven't created any quizzes, they won't see the quizzes link.  You can sort and explicitly disable these links if there are areas of the course you don't want your students accessing."),
        url: ENV.COURSE_WIZARD.urls.select_navigation,
        iconClass: 'icon-hamburger'
      },
      {
        key:'home_page',
        complete: ENV.COURSE_WIZARD.checklist_states.home_page_step,
        title: I18n.t("Choose a Course Home Page"),
        text: I18n.t("When people visit the course, this is the page they'll see.  You can set it to show an activity stream, the list of course modules, a syllabus, or a custom page you write yourself.  The default is the course activity stream."),
        iconClass: 'icon-home'
      },
      {
        key:'course_calendar',
        complete: ENV.COURSE_WIZARD.checklist_states.calendar_event_step,
        title: I18n.t("Add Course Calendar Events"),
        text: I18n.t("Here's a great chance to get to know the calendar and add any non-assignment events you might have to the course. Don't worry, we'll help you through it."),
        url: ENV.COURSE_WIZARD.urls.course_calendar,
        iconClass: 'icon-calendar-month'
      },
// NOTE: Changed text: all instances of "TAs" changed to "TFs"
      {
        key:'add_tas',
        complete: ENV.COURSE_WIZARD.checklist_states.add_ta_step,
        title: I18n.t("Add TFs to the Course"),
        text: I18n.t("You may want to assign some TFs to help you with the course.  TFs can grade student submissions, help moderate the discussions and even update due dates and assignment details for you."),
        url: ENV.COURSE_WIZARD.urls.add_tas,
        iconClass: 'icon-educators'
      },
// NOTE: Added item for customizing the academic integrity policy for the course
      {
        key:'policy_wizard',
        complete: ENV.COURSE_WIZARD.checklist_states.publish_step,
        title: I18n.t("Customize academic integrity policy"),
        text: I18n.t("Customize the academic integrity policy for your course."),
        url: "https://canvas.harvard.edu/courses/39/external_tools/1513",
        iconClass: 'icon-educators'
	  },
      {
        key:'publish_course',
        complete: ENV.COURSE_WIZARD.checklist_states.publish_step,
        title: I18n.t("Publish the Course"),
        text: I18n.t("All finished?  Time to publish your course!  Click the button below to make it official! Publishing will allow the users to begin participating in the course."),
        non_registered_text: I18n.t("This course is claimed and ready, but you'll need to finish the registration process before you can publish the course.  You should have received an email from Canvas with a link to finish the process.  Be sure to check your spam box."),
        iconClass: 'icon-publish'
      }
    ]
});

define('jsx/course_wizard/Checklist', ['react', './ChecklistItem', './ListItems'], function(e, a, s) {
	var t = e.createClass({
		displayName: "Checklist",
		getInitialState: function() {
			return {
				selectedItem: this.props.selectedItem || ""
			}
		},
		componentWillReceiveProps: function(e) {
			this.setState({
				selectedItem: e.selectedItem
			})
		},
		renderChecklist: function() {
			return s.map(function(e) {
				var s = this.state.selectedItem === e.key,
					t = "wizard_" + e.key;
				return a({
					complete: e.complete,
					id: t,
					key: e.key,
					stepKey: e.key,
					title: e.title,
					onClick: this.props.clickHandler,
					isSelected: s
				})
			}.bind(this))
		},
		render: function() {
			var a = this.renderChecklist();
			return e.DOM.div({
				className: this.props.className
			}, a)
		}
	});
	return t;
});

define("jsx/course_wizard/CourseWizard", [
  'jquery',
  'react',
  'i18n!course_wizard',
  'react-modal',
  './InfoFrame',
  './Checklist',
  'compiled/userSettings',
  'compiled/jquery.rails_flash_notifications'
], function($, React, I18n, ReactModal, InfoFrame, Checklist, userSettings) {

  var CourseWizard = React.createClass({
      displayName: 'CourseWizard',

      propTypes: {
        showWizard: React.PropTypes.bool,
        overlayClassName: React.PropTypes.string
      },

      getInitialState: function () {
        return {
          showWizard: this.props.showWizard,
          selectedItem: false
        };
      },

      componentDidMount: function () {
        this.refs.closeLink.getDOMNode().focus();
        $(this.refs.wizardBox.getDOMNode()).removeClass('ic-wizard-box--is-closed');
        $.screenReaderFlashMessageExclusive(I18n.t("Course Setup Wizard is showing."));
      },

      componentWillReceiveProps: function (nextProps) {
        this.setState({
          showWizard: nextProps.showWizard
        }, function() {
          $(this.refs.wizardBox.getDOMNode()).removeClass('ic-wizard-box--is-closed');
          if (this.state.showWizard) {
            this.refs.closeLink.getDOMNode().focus();
          }
        });
      },

      /**
       * Handles what should happen when a checklist item is clicked.
       */
      checklistClickHandler: function (itemToShowKey) {
        this.setState({
          selectedItem: itemToShowKey
        });
      },

      closeModal: function (event) {
        if (event) {
          event.preventDefault()
        };

        var pathname = window.location.pathname;
        userSettings.set('hide_wizard_' + pathname, true);

        this.setState({
          showWizard: false
        })
      },

      render: function () {
          return (
              React.createElement(ReactModal, {
                isOpen: this.state.showWizard,
                onRequestClose: this.closeModal,
                overlayClassName: this.props.overlayClassName
              },
                React.createElement("div", {ref: "wizardBox", className: "ic-wizard-box"},
                  React.createElement("div", {className: "ic-wizard-box__header"},
                    React.createElement("a", {href: "/", className: "ic-wizard-box__logo-link"},
                      React.createElement("span", {className: "screenreader-only"}, I18n.t("My dashboard"))
                    ),
                    React.createElement(Checklist, {className: "ic-wizard-box__nav",
                               selectedItem: this.state.selectedItem,
                               clickHandler: this.checklistClickHandler}
                    )
                  ),
                  React.createElement("div", {className: "ic-wizard-box__main"},
                    React.createElement("div", {className: "ic-wizard-box__close"},
                      React.createElement("div", {className: "ic-Expand-link ic-Expand-link--Secondary ic-Expand-link--from-right"},
                        React.createElement("a", {ref: "closeLink", href: "#", className: "ic-Expand-link__trigger", onClick: this.closeModal},
                          React.createElement("div", {className: "ic-Expand-link__layout"},
                            React.createElement("i", {className: "icon-x ic-Expand-link__icon"}),
                            React.createElement("span", {className: "ic-Expand-link__text"}, I18n.t("Close and return to Canvas"))
                          )
                        )
                      )
                    ),
                    React.createElement(InfoFrame, {className: "ic-wizard-box__content", itemToShow: this.state.selectedItem, closeModal: this.closeModal})
                  )
                )
              )
          );
      }
  });

  return CourseWizard;
});

require(['jquery', 'react'], function($, React) {
    /*
     * This essentially unmounts the existing React CourseWizard Component
	 * bound to the onclick handler of the "Setup Checklist" button.
     */
	React.unmountComponentAtNode($("#wizard_box")[0]);
    $(".wizard_popup_link").off("click");
});

require(['jquery', 'react', 'compiled/userSettings', 'jsx/course_wizard/CourseWizard'], function($, React, userSettings, CourseWizard) {
   /*
    * This essentially handles binding the button events and calling out to the
    * CourseWizard React component that is the actual wizard.
    */
  var $wizard_box, courseWizardFactory, pathname;
  $wizard_box = $("#wizard_box");
  pathname = window.location.pathname;
  courseWizardFactory = React.createFactory(CourseWizard);
  return $(".wizard_popup_link").click(function(event) {
    return React.render(courseWizardFactory({
      overlayClassName: 'CourseWizard__modalOverlay',
      showWizard: true
    }), $wizard_box[0]);
  });
});
<|endoftext|>


<commit_before>/*global sinon, describe, it, before, beforeEach*/
'use strict';

var expect = require('expect.js');
var dispatchEvent = require('../src/js/utils').dispatchEvent;
var forEach = require('../src/js/utils').forEach;
var AppHeader = require('../src/js/AppHeader');

describe('AppHeader', function () {

	var sandbox, session;

	before(function () {
		sandbox = sinon.sandbox.create();

		session = window.session = {
			login: function (redirectUrl) {},
			logout: function (redirectUrl) {},
			hasValidSession: function (gracePeriodSeconds) {},
			on: function (eventType, handler) {},
			off: function (eventType, handler) {},
			// Events
			SessionStateKnownEvent: 'sessionstateknown',
			LoginEvent: 'login',
			LogoutEvent: 'logout',
			// States
			Success: 'success',
			NoToken: 'notoken',
			NoSession: 'nosession',
			Unknown: 'unknown'
		};

		var config = {
			session: 'session',
			user: { givenName: 'FooBar' }
		};
		var configEl = document.createElement('script');
		configEl.setAttribute('data-o-app-header-config', '');
		configEl.type = 'application/json';
		configEl.innerHTML = JSON.stringify(config);
		document.head.appendChild(configEl);
	});

	beforeEach(function () {
		document.body.innerHTML = '';
		sandbox.restore();
	});

	describe('o.DOMContentLoaded', function () {

		require('../main');

		it('should prepend to document.body', function (done) {
			document.addEventListener('o.DOMContentLoaded', function () {
				var appHeaderEl = document.body.firstChild;

				expect(document.body.children.length).to.be(1);
				expect(appHeaderEl).to.not.be(null);
				expect(appHeaderEl.nodeName.toLowerCase()).to.be('header');
				done();
			});

			var ready = document.createEvent('Event');
			ready.initEvent('o.DOMContentLoaded');
			document.dispatchEvent(ready);
		});

	});

	describe('#init(element)', function () {

		it('should prepend to document.body when element is undefined', function () {
			AppHeader.init();

			var appHeaderEl = document.body.firstChild;

			expect(document.body.children.length).to.be(1);
			expect(appHeaderEl).to.not.be(null);
			expect(appHeaderEl.nodeName.toLowerCase()).to.be('header');
		});

		it('should replace element when element is an instance of HTMLElement', function () {
			document.body.appendChild(document.createElement('div'));

			var el = document.createElement('div');
			document.body.appendChild(el);

			AppHeader.init(el);

			var appHeaderEl = document.body.childNodes[1];

			expect(document.body.children.length).to.be(2);
			expect(appHeaderEl).to.not.be(null);
			expect(appHeaderEl.nodeName.toLowerCase()).to.be('header');
		});

		it('should replace element when element is an instance of string', function () {
			document.body.appendChild(document.createElement('div'));

			var el = document.createElement('div');
			el.id = 'app-header';
			document.body.appendChild(el);

			AppHeader.init('#app-header');

			var appHeaderEl = document.body.childNodes[1];

			expect(document.body.children.length).to.be(2);
			expect(appHeaderEl).to.not.be(null);
			expect(appHeaderEl.nodeName.toLowerCase()).to.be('header');
		});

		it('should set aria-role="banner"', function () {
			AppHeader.init();

			var appHeaderEl = getHeaderEl();

			expect(appHeaderEl.getAttribute('aria-role')).to.be('banner');
		});

		it('should resolve the nav links', function () {
			var consoleBaseUrl = 'https://example.org';
			AppHeader.init({ consoleBaseUrl: consoleBaseUrl });

			var appHeaderEl = getHeaderEl();

			function resolveLink(key) {
				return AppHeader.linkMap[key].replace('{consoleBaseUrl}', consoleBaseUrl);
			}

			expect(appHeaderEl.querySelector('[data-link="my-account"]').href).to.be(resolveLink('my-account'));
			expect(appHeaderEl.querySelector('[data-link="home"]').href).to.be(resolveLink('home'));
		});

		it('should emit oAppHeader.help.toggle when the Help nav item is clicked', function (done) {
			AppHeader.init();

			var appHeaderEl = getHeaderEl();
			var helpNavEl = appHeaderEl.querySelector('[data-link="help"]');

			appHeaderEl.addEventListener('oAppHeader.help.toggle', done.bind(null, null));

			dispatchEvent(helpNavEl, 'click');
		});

		it('should insert the page nav', function () {
			var navEl = document.createElement('nav');
			navEl.classList.add('o-app-header__page-nav');
			navEl.innerHTML = '

Item 1

Item 2

';
			document.body.appendChild(navEl);

			AppHeader.init();

			var appHeaderEl = getHeaderEl();
			var appHeaderNavEl = appHeaderEl.querySelector('.o-app-header__page-nav-container .o-header__nav');

			expect(appHeaderNavEl.querySelector('ul').childElementCount).to.be(2);
		});

	});

	describe('.setNav(navElement)', function () {

		it('should find the nav element on the page when the navElement argument is undefined', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.classList.add('o-app-header__page-nav');
			navEl.innerHTML = '

2ee29043

';
			document.body.appendChild(navEl);

			AppHeader.setNav();

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navContainerEl.childNodes[0].childNodes[0].textContent).to.be('2ee29043');
		});

		it('should build the nav element when the navElement argument is an object', function () {
			var nav = {
				navItems: {
					Foo: 'http://example.com/foo',
					Bar: 'http://example.com/bar'
				}
			};

			AppHeader.init();
			AppHeader.setNav(nav);

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);
			var navListEl = navContainerEl.querySelector('.o-header__nav ul');

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navListEl.childElementCount).to.be(2);
			expect(navListEl.childNodes[0].textContent).to.be('Foo');
			expect(navListEl.childNodes[0].firstChild.href).to.be(nav.navItems.Foo);
			expect(navListEl.childNodes[1].textContent).to.be('Bar');
			expect(navListEl.childNodes[1].firstChild.href).to.be(nav.navItems.Bar);
		});

		it('should add a click event listener when the navElement argument is an object and the navItems key value is a function', function () {
			var nav = {
				navItems: {
					Foo: 'http://example.com/foo',
					Bar: sinon.spy()
				}
			};

			AppHeader.init();
			AppHeader.setNav(nav);

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);
			var navListEl = navContainerEl.querySelector('ul');

			dispatchEvent(navListEl.childNodes[1].querySelector('a'), 'click');

			expect(nav.navItems.Bar.calledOnce).to.be(true);
		});

		it('should use the provided element when the navElement argument is an instance of HTMLElement', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.innerHTML = 'a8f4af5D';

			AppHeader.setNav(navEl);

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navContainerEl.childNodes[0].textContent).to.be('a8f4af5D');
		});

		it('should select the element when the navElement argument is a string', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.id = 'a25642c2';
			navEl.innerHTML = 'a25642c2';
			document.body.appendChild(navEl);

			AppHeader.setNav('#a25642c2');

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navContainerEl.firstChild.textContent).to.be('a25642c2');
		});

		it('should replace the existing content of the container', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.innerHTML = '

Item 1

';
			AppHeader.setNav(navEl);

			// Create a new nav element
			navEl = document.createElement('nav');
			navEl.innerHTML = '

Item A

Item B

';
			AppHeader.setNav(navEl);

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navContainerEl.querySelector('.o-header__nav ul').childElementCount).to.be(2);
		});

		it('should remove the id from the cloned node', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.id = 'ad1527b9';
			document.body.appendChild(navEl);

			AppHeader.setNav('#ad1527b9');

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.firstChild.id).to.be('');
		});

	});

	describe('session', function () {

		it('should sign the user in when the Sign In nav item is clicked', function () {
			AppHeader.init();
			var headerEl = getHeaderEl();
			var signInEl = headerEl.querySelector('[data-action="sign-in"]');
			sandbox.stub(session, 'login');

			dispatchEvent(signInEl, 'click');

			expect(session.login.calledWith(window.location.href)).to.be(true);
		});

		it('should sign the user out when the Sign Out dropdown menu item is clicked', function () {
			AppHeader.init();
			var headerEl = getHeaderEl();
			var signOutEl = headerEl.querySelector('[data-action="sign-out"]');
			sandbox.stub(session, 'logout');

			dispatchEvent(signOutEl, 'click');

			expect(session.logout.calledWith(window.location.href)).to.be(true);
		});

		it('should be in the initializing state when the session state is not Success, NoToken, or NoSession', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.Unknown);
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'initializing')).to.be(true);
		});

		it('should be in the signed in state when the session state is Success', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.Success);
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-in')).to.be(true);
		});

		it('should be in the signed out state when the session state is NoSession', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.NoSession);
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-out')).to.be(true);
		});

		it('should be in the signed out state when the session state is NoToken', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.NoToken);
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-out')).to.be(true);
		});

		it('should be in the signed in state when a session SessionStateKnownEvent is emitted and session state is Success', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.Success);
			sandbox.stub(session, 'on').withArgs(session.SessionStateKnownEvent).yields();
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-in')).to.be(true);
		});

		it('should be in the signed in state when a session SessionStateKnownEvent is emitted and session state is Success', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.NoSession);
			sandbox.stub(session, 'on').withArgs(session.SessionStateKnownEvent).yields();
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-out')).to.be(true);
		});

		it('should be in the signed in state when a session LoginEvent is emitted', function () {
			sandbox.stub(session, 'on').withArgs(session.LoginEvent).yields();
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-in')).to.be(true);
		});

		it('should be in the signed out state when a session LogoutEvent is emitted', function () {
			sandbox.stub(session, 'on').withArgs(session.LogoutEvent).yields();
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-out')).to.be(true);
		});

	});

});

function getHeaderEl() {
	return document.querySelector('[data-o-component="o-header"]');
}

function getNavContainerEl(headerEl) {
	return headerEl.querySelector('.o-app-header__page-nav-container');
}

function isHeaderInState(headerEl, state) {
	var selector = '[data-show="state:signed-in"],[data-show="state:signed-out"]';
	var elements = headerEl.querySelectorAll(selector);
	var isInState = true;

	if (state === 'initializing') {
		forEach(elements, function (idx, element) {
			if (element.style.display !== 'none') isInState = false;
		});
	} else if (state === 'signed-in') {
		forEach(elements, function (idx, element) {
			if (element.getAttribute('data-show') === 'state:signed-in' && element.style.display === 'none') isInState = false;
			if (element.getAttribute('data-show') === 'state:signed-out' && element.style.display !== 'none') isInState = false;
		});
	} else if (state === 'signed-out') {
		forEach(elements, function (idx, element) {
			if (element.getAttribute('data-show') === 'state:signed-in' && element.style.display !== 'none') isInState = false;
			if (element.getAttribute('data-show') === 'state:signed-out' && element.style.display === 'none') isInState = false;
		});
	}

	return isInState;
}
<commit_msg>chore: fix test for Firefox<commit_after>/*global sinon, describe, it, before, beforeEach*/
'use strict';

var expect = require('expect.js');
var dispatchEvent = require('../src/js/utils').dispatchEvent;
var forEach = require('../src/js/utils').forEach;
var AppHeader = require('../src/js/AppHeader');

describe('AppHeader', function () {

	var sandbox, session;

	before(function () {
		sandbox = sinon.sandbox.create();

		session = window.session = {
			login: function (redirectUrl) {},
			logout: function (redirectUrl) {},
			hasValidSession: function (gracePeriodSeconds) {},
			on: function (eventType, handler) {},
			off: function (eventType, handler) {},
			// Events
			SessionStateKnownEvent: 'sessionstateknown',
			LoginEvent: 'login',
			LogoutEvent: 'logout',
			// States
			Success: 'success',
			NoToken: 'notoken',
			NoSession: 'nosession',
			Unknown: 'unknown'
		};

		var config = {
			session: 'session',
			user: { givenName: 'FooBar' }
		};
		var configEl = document.createElement('script');
		configEl.setAttribute('data-o-app-header-config', '');
		configEl.type = 'application/json';
		configEl.innerHTML = JSON.stringify(config);
		document.head.appendChild(configEl);
	});

	beforeEach(function () {
		document.body.innerHTML = '';
		sandbox.restore();
	});

	describe('o.DOMContentLoaded', function () {

		require('../main');

		it('should prepend to document.body', function (done) {
			document.addEventListener('o.DOMContentLoaded', function () {
				var appHeaderEl = document.body.firstChild;

				expect(document.body.children.length).to.be(1);
				expect(appHeaderEl).to.not.be(null);
				expect(appHeaderEl.nodeName.toLowerCase()).to.be('header');
				done();
			});

			var ready = document.createEvent('Event');
			ready.initEvent('o.DOMContentLoaded', true, true);
			document.dispatchEvent(ready);
		});

	});

	describe('#init(element)', function () {

		it('should prepend to document.body when element is undefined', function () {
			AppHeader.init();

			var appHeaderEl = document.body.firstChild;

			expect(document.body.children.length).to.be(1);
			expect(appHeaderEl).to.not.be(null);
			expect(appHeaderEl.nodeName.toLowerCase()).to.be('header');
		});

		it('should replace element when element is an instance of HTMLElement', function () {
			document.body.appendChild(document.createElement('div'));

			var el = document.createElement('div');
			document.body.appendChild(el);

			AppHeader.init(el);

			var appHeaderEl = document.body.childNodes[1];

			expect(document.body.children.length).to.be(2);
			expect(appHeaderEl).to.not.be(null);
			expect(appHeaderEl.nodeName.toLowerCase()).to.be('header');
		});

		it('should replace element when element is an instance of string', function () {
			document.body.appendChild(document.createElement('div'));

			var el = document.createElement('div');
			el.id = 'app-header';
			document.body.appendChild(el);

			AppHeader.init('#app-header');

			var appHeaderEl = document.body.childNodes[1];

			expect(document.body.children.length).to.be(2);
			expect(appHeaderEl).to.not.be(null);
			expect(appHeaderEl.nodeName.toLowerCase()).to.be('header');
		});

		it('should set aria-role="banner"', function () {
			AppHeader.init();

			var appHeaderEl = getHeaderEl();

			expect(appHeaderEl.getAttribute('aria-role')).to.be('banner');
		});

		it('should resolve the nav links', function () {
			var consoleBaseUrl = 'https://example.org';
			AppHeader.init({ consoleBaseUrl: consoleBaseUrl });

			var appHeaderEl = getHeaderEl();

			function resolveLink(key) {
				return AppHeader.linkMap[key].replace('{consoleBaseUrl}', consoleBaseUrl);
			}

			expect(appHeaderEl.querySelector('[data-link="my-account"]').href).to.be(resolveLink('my-account'));
			expect(appHeaderEl.querySelector('[data-link="home"]').href).to.be(resolveLink('home'));
		});

		it('should emit oAppHeader.help.toggle when the Help nav item is clicked', function (done) {
			AppHeader.init();

			var appHeaderEl = getHeaderEl();
			var helpNavEl = appHeaderEl.querySelector('[data-link="help"]');

			appHeaderEl.addEventListener('oAppHeader.help.toggle', done.bind(null, null));

			dispatchEvent(helpNavEl, 'click');
		});

		it('should insert the page nav', function () {
			var navEl = document.createElement('nav');
			navEl.classList.add('o-app-header__page-nav');
			navEl.innerHTML = '

Item 1

Item 2

';
			document.body.appendChild(navEl);

			AppHeader.init();

			var appHeaderEl = getHeaderEl();
			var appHeaderNavEl = appHeaderEl.querySelector('.o-app-header__page-nav-container .o-header__nav');

			expect(appHeaderNavEl.querySelector('ul').childElementCount).to.be(2);
		});

	});

	describe('.setNav(navElement)', function () {

		it('should find the nav element on the page when the navElement argument is undefined', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.classList.add('o-app-header__page-nav');
			navEl.innerHTML = '

2ee29043

';
			document.body.appendChild(navEl);

			AppHeader.setNav();

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navContainerEl.childNodes[0].childNodes[0].textContent).to.be('2ee29043');
		});

		it('should build the nav element when the navElement argument is an object', function () {
			var nav = {
				navItems: {
					Foo: 'http://example.com/foo',
					Bar: 'http://example.com/bar'
				}
			};

			AppHeader.init();
			AppHeader.setNav(nav);

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);
			var navListEl = navContainerEl.querySelector('.o-header__nav ul');

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navListEl.childElementCount).to.be(2);
			expect(navListEl.childNodes[0].textContent).to.be('Foo');
			expect(navListEl.childNodes[0].firstChild.href).to.be(nav.navItems.Foo);
			expect(navListEl.childNodes[1].textContent).to.be('Bar');
			expect(navListEl.childNodes[1].firstChild.href).to.be(nav.navItems.Bar);
		});

		it('should add a click event listener when the navElement argument is an object and the navItems key value is a function', function () {
			var nav = {
				navItems: {
					Foo: 'http://example.com/foo',
					Bar: sinon.spy()
				}
			};

			AppHeader.init();
			AppHeader.setNav(nav);

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);
			var navListEl = navContainerEl.querySelector('ul');

			dispatchEvent(navListEl.childNodes[1].querySelector('a'), 'click');

			expect(nav.navItems.Bar.calledOnce).to.be(true);
		});

		it('should use the provided element when the navElement argument is an instance of HTMLElement', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.innerHTML = 'a8f4af5D';

			AppHeader.setNav(navEl);

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navContainerEl.childNodes[0].textContent).to.be('a8f4af5D');
		});

		it('should select the element when the navElement argument is a string', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.id = 'a25642c2';
			navEl.innerHTML = 'a25642c2';
			document.body.appendChild(navEl);

			AppHeader.setNav('#a25642c2');

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navContainerEl.firstChild.textContent).to.be('a25642c2');
		});

		it('should replace the existing content of the container', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.innerHTML = '

Item 1

';
			AppHeader.setNav(navEl);

			// Create a new nav element
			navEl = document.createElement('nav');
			navEl.innerHTML = '

Item A

Item B

';
			AppHeader.setNav(navEl);

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.childElementCount).to.be(1);
			expect(navContainerEl.querySelector('.o-header__nav ul').childElementCount).to.be(2);
		});

		it('should remove the id from the cloned node', function () {
			AppHeader.init();
			var navEl = document.createElement('nav');
			navEl.id = 'ad1527b9';
			document.body.appendChild(navEl);

			AppHeader.setNav('#ad1527b9');

			var headerEl = getHeaderEl();
			var navContainerEl = getNavContainerEl(headerEl);

			expect(navContainerEl.firstChild.id).to.be('');
		});

	});

	describe('session', function () {

		it('should sign the user in when the Sign In nav item is clicked', function () {
			AppHeader.init();
			var headerEl = getHeaderEl();
			var signInEl = headerEl.querySelector('[data-action="sign-in"]');
			sandbox.stub(session, 'login');

			dispatchEvent(signInEl, 'click');

			expect(session.login.calledWith(window.location.href)).to.be(true);
		});

		it('should sign the user out when the Sign Out dropdown menu item is clicked', function () {
			AppHeader.init();
			var headerEl = getHeaderEl();
			var signOutEl = headerEl.querySelector('[data-action="sign-out"]');
			sandbox.stub(session, 'logout');

			dispatchEvent(signOutEl, 'click');

			expect(session.logout.calledWith(window.location.href)).to.be(true);
		});

		it('should be in the initializing state when the session state is not Success, NoToken, or NoSession', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.Unknown);
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'initializing')).to.be(true);
		});

		it('should be in the signed in state when the session state is Success', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.Success);
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-in')).to.be(true);
		});

		it('should be in the signed out state when the session state is NoSession', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.NoSession);
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-out')).to.be(true);
		});

		it('should be in the signed out state when the session state is NoToken', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.NoToken);
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-out')).to.be(true);
		});

		it('should be in the signed in state when a session SessionStateKnownEvent is emitted and session state is Success', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.Success);
			sandbox.stub(session, 'on').withArgs(session.SessionStateKnownEvent).yields();
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-in')).to.be(true);
		});

		it('should be in the signed in state when a session SessionStateKnownEvent is emitted and session state is Success', function () {
			sandbox.stub(session, 'hasValidSession').returns(session.NoSession);
			sandbox.stub(session, 'on').withArgs(session.SessionStateKnownEvent).yields();
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-out')).to.be(true);
		});

		it('should be in the signed in state when a session LoginEvent is emitted', function () {
			sandbox.stub(session, 'on').withArgs(session.LoginEvent).yields();
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-in')).to.be(true);
		});

		it('should be in the signed out state when a session LogoutEvent is emitted', function () {
			sandbox.stub(session, 'on').withArgs(session.LogoutEvent).yields();
			AppHeader.init();
			var headerEl = getHeaderEl();

			expect(isHeaderInState(headerEl, 'signed-out')).to.be(true);
		});

	});

});

function getHeaderEl() {
	return document.querySelector('[data-o-component="o-header"]');
}

function getNavContainerEl(headerEl) {
	return headerEl.querySelector('.o-app-header__page-nav-container');
}

function isHeaderInState(headerEl, state) {
	var selector = '[data-show="state:signed-in"],[data-show="state:signed-out"]';
	var elements = headerEl.querySelectorAll(selector);
	var isInState = true;

	if (state === 'initializing') {
		forEach(elements, function (idx, element) {
			if (element.style.display !== 'none') isInState = false;
		});
	} else if (state === 'signed-in') {
		forEach(elements, function (idx, element) {
			if (element.getAttribute('data-show') === 'state:signed-in' && element.style.display === 'none') isInState = false;
			if (element.getAttribute('data-show') === 'state:signed-out' && element.style.display !== 'none') isInState = false;
		});
	} else if (state === 'signed-out') {
		forEach(elements, function (idx, element) {
			if (element.getAttribute('data-show') === 'state:signed-in' && element.style.display !== 'none') isInState = false;
			if (element.getAttribute('data-show') === 'state:signed-out' && element.style.display === 'none') isInState = false;
		});
	}

	return isInState;
}
<|endoftext|>


<commit_before>var expect = require('chai').expect,
    InjectorClient = require('../lib/InjectorClient').InjectorClient,
    launcher = require('./helpers/launcher.js');

describe('InjectorClient', function() {
  describe('with inject=false', function() {
    var injectorClient, debuggerClient, breakedObject;

    function setupInjector(done) {
      // increase the timeout for Travis CI
      this.timeout(5000);

      launcher.runPeriodicConsoleLog(false, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({inject: false}, debuggerClient);
        debuggerClient.once('break', function(obj) {
          breakedObject = obj;
          done();
        });
        injectorClient._pause();
      });
    }

    before(setupInjector);

    it('ignores break events not created by the injector', function() {
      var pausedByInjector = injectorClient.containsInjectorMark('wrongInvocationText');
      expect(pausedByInjector, 'invocation text not equal to PAUSE_CHECK').to.equal(false);
    });

    it('checks that application paused by injector', function() {
      var pausedByInjector = injectorClient.containsInjectorMark(breakedObject.invocationText);
      expect(pausedByInjector, 'invocation text equal to PAUSE_CHECK').to.equal(true);
    });

    it('breaks the injection flow with injected=false', function(done) {
      injectorClient.once('inject', function(injected) {
        expect(injected, 'injection command discarded').to.equal(false);
        done();
      });
      injectorClient.inject();
    });
  });

  describe('with inject=true', function() {
    before(setupInjector);
    var injectorClient, debuggerClient, serverPort;

    function setupInjector(done) {
      // increase the timeout for Travis CI
      this.timeout(5000);

      launcher.runPeriodicConsoleLog(false, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({}, debuggerClient);
        injectorClient._pause();
        debuggerClient.once('break', function(obj) {
          injectorClient._appPausedByInjector = injectorClient.containsInjectorMark(obj.invocationText);
          done();
        });
      });
    }

    it('is ready to inject', function() {
      expect(injectorClient.needsInject, 'injection is needed').to.equal(true);
    });

    it('inject server', function(done) {
      injectorClient.once('inject', function(injected) {
        expect(injected).to.equal(true);
        if (injected) done();
      });
      injectorClient.once('error', function(error) {
        done(error);
      });
      injectorClient.inject();
    });

    it('does not need to inject if already injected', function() {
      expect(injectorClient.needsInject, 'injection is not needed').to.equal(false);
    });

    it('notify that is already injected', function(done) {
      injectorClient.once('inject', function(injected) {
        expect(injected, 'is already injected').to.equal(true);
        done();
      });
      injectorClient.inject();
    });

    it('would close on "close" debuggerClient', function(done) {
      injectorClient.once('close', function() {
        expect(injectorClient._injected).to.equal(false);
        expect(injectorClient._appPausedByInjector).to.equal(false);
        done();
      });
      debuggerClient.close();
    });

    it('is ready to inject after close', function() {
      expect(injectorClient.needsInject, 'injection is needed').to.equal(true);
    });
  });

  describe('with inject=true and debug-brk flag', function() {
    before(setupInjector);
    var injectorClient, debuggerClient;

    function setupInjector(done) {
      launcher.runPeriodicConsoleLog(true, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({}, debuggerClient);
        done();
      });
    }

    it('connects to server', function(done) {
      injectorClient.once('inject', function(injected) {
        expect(injected, 'is injected').to.equal(true);
        done();
      });
      injectorClient.inject();
    });
  });

  describe('works with events.', function() {
    before(setupInjector);
    var injectorClient, debuggerClient;

    function setupInjector(done) {
      launcher.runPeriodicConsoleLog(true, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({}, debuggerClient);
        injectorClient.once('inject', function(injected) {
          if (injected) done();
        });
        injectorClient.once('error', function(error) {
          done(error);
        });
        injectorClient.inject();
      });
    }

    it('Register event handle in app and emits it', function(done) {
      var injection = function(require, debug, options) {
        debug.register('console', function(request, response) {
          debug.commandToEvent(request, response);
        });

        console.log = (function(fn) {
          return function() {
            var message = arguments[0];

            debug.command('console', {
              level: 'log',
              message: options.message + message
            });

            return fn.apply(console, arguments);
          };
        })(console.log);

        console.log('test');
      };

      debuggerClient.registerDebuggerEventHandlers('console');
      debuggerClient.once('console', function(message) {
        expect(message.level).to.equal('log');
        expect(message.message).to.equal('testtest');
        done();
      });

      injectorClient.injection(
        injection,
        { message: 'test' },
        function(error, result) {
          if (error) return done(error);
        }
      );
    });
  });

  describe('works with commands.', function() {
    before(setupInjector);
    var injectorClient, debuggerClient;

    function setupInjector(done) {
      launcher.runPeriodicConsoleLog(true, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({}, debuggerClient);
        injectorClient.once('inject', function(injected) {
          if (injected) done();
        });
        injectorClient.once('error', function(error) {
          done(error);
        });
        injectorClient.inject();
      });
    }

    it('Registers command in app and responds to it', function(done) {
      var injection = function(require, debug, options) {
        debug.register('testcommand', function(request, response) {
          response.body = request.arguments;
        });
      };

      injectorClient.injection(
        injection,
        {},
        function(error, result) {
          if (error) return done(error);

          debuggerClient.request(
            'testcommand',
            {
              param: 'test'
            },
            function(error, result) {
              expect(error).to.equal(null);
              expect(result).to.have.property('param', 'test');
              done();
            }
          );
        }
      );
    });
  });
});
<commit_msg>test: increase test timeout in InjectorClient<commit_after>var expect = require('chai').expect,
    InjectorClient = require('../lib/InjectorClient').InjectorClient,
    launcher = require('./helpers/launcher.js');

describe('InjectorClient', function() {
  describe('with inject=false', function() {
    var injectorClient, debuggerClient, breakedObject;

    function setupInjector(done) {
      // increase the timeout for Travis CI
      this.timeout(5000);

      launcher.runPeriodicConsoleLog(false, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({inject: false}, debuggerClient);
        debuggerClient.once('break', function(obj) {
          breakedObject = obj;
          done();
        });
        injectorClient._pause();
      });
    }

    before(setupInjector);

    it('ignores break events not created by the injector', function() {
      var pausedByInjector = injectorClient.containsInjectorMark('wrongInvocationText');
      expect(pausedByInjector, 'invocation text not equal to PAUSE_CHECK').to.equal(false);
    });

    it('checks that application paused by injector', function() {
      var pausedByInjector = injectorClient.containsInjectorMark(breakedObject.invocationText);
      expect(pausedByInjector, 'invocation text equal to PAUSE_CHECK').to.equal(true);
    });

    it('breaks the injection flow with injected=false', function(done) {
      injectorClient.once('inject', function(injected) {
        expect(injected, 'injection command discarded').to.equal(false);
        done();
      });
      injectorClient.inject();
    });
  });

  describe('with inject=true', function() {
    before(setupInjector);
    var injectorClient, debuggerClient, serverPort;

    function setupInjector(done) {
      // increase the timeout for Travis CI
      this.timeout(5000);

      launcher.runPeriodicConsoleLog(false, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({}, debuggerClient);
        injectorClient._pause();
        debuggerClient.once('break', function(obj) {
          injectorClient._appPausedByInjector = injectorClient.containsInjectorMark(obj.invocationText);
          done();
        });
      });
    }

    it('is ready to inject', function() {
      expect(injectorClient.needsInject, 'injection is needed').to.equal(true);
    });

    it('inject server', function(done) {
      injectorClient.once('inject', function(injected) {
        expect(injected).to.equal(true);
        if (injected) done();
      });
      injectorClient.once('error', function(error) {
        done(error);
      });
      injectorClient.inject();
    });

    it('does not need to inject if already injected', function() {
      expect(injectorClient.needsInject, 'injection is not needed').to.equal(false);
    });

    it('notify that is already injected', function(done) {
      injectorClient.once('inject', function(injected) {
        expect(injected, 'is already injected').to.equal(true);
        done();
      });
      injectorClient.inject();
    });

    it('would close on "close" debuggerClient', function(done) {
      injectorClient.once('close', function() {
        expect(injectorClient._injected).to.equal(false);
        expect(injectorClient._appPausedByInjector).to.equal(false);
        done();
      });
      debuggerClient.close();
    });

    it('is ready to inject after close', function() {
      expect(injectorClient.needsInject, 'injection is needed').to.equal(true);
    });
  });

  describe('with inject=true and debug-brk flag', function() {
    before(setupInjector);
    var injectorClient, debuggerClient;

    function setupInjector(done) {
      // increase the timeout for Travis CI
      this.timeout(5000);

      launcher.runPeriodicConsoleLog(true, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({}, debuggerClient);
        done();
      });
    }

    it('connects to server', function(done) {
      injectorClient.once('inject', function(injected) {
        expect(injected, 'is injected').to.equal(true);
        done();
      });
      injectorClient.inject();
    });
  });

  describe('works with events.', function() {
    before(setupInjector);
    var injectorClient, debuggerClient;

    function setupInjector(done) {
      // increase the timeout for Travis CI
      this.timeout(5000);

      launcher.runPeriodicConsoleLog(true, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({}, debuggerClient);
        injectorClient.once('inject', function(injected) {
          if (injected) done();
        });
        injectorClient.once('error', function(error) {
          done(error);
        });
        injectorClient.inject();
      });
    }

    it('Register event handle in app and emits it', function(done) {
      var injection = function(require, debug, options) {
        debug.register('console', function(request, response) {
          debug.commandToEvent(request, response);
        });

        console.log = (function(fn) {
          return function() {
            var message = arguments[0];

            debug.command('console', {
              level: 'log',
              message: options.message + message
            });

            return fn.apply(console, arguments);
          };
        })(console.log);

        console.log('test');
      };

      debuggerClient.registerDebuggerEventHandlers('console');
      debuggerClient.once('console', function(message) {
        expect(message.level).to.equal('log');
        expect(message.message).to.equal('testtest');
        done();
      });

      injectorClient.injection(
        injection,
        { message: 'test' },
        function(error, result) {
          if (error) return done(error);
        }
      );
    });
  });

  describe('works with commands.', function() {
    before(setupInjector);
    var injectorClient, debuggerClient;

    function setupInjector(done) {
      // increase the timeout for Travis CI
      this.timeout(5000);

      launcher.runPeriodicConsoleLog(true, function(childProcess, client) {
        debuggerClient = client;
        injectorClient = new InjectorClient({}, debuggerClient);
        injectorClient.once('inject', function(injected) {
          if (injected) done();
        });
        injectorClient.once('error', function(error) {
          done(error);
        });
        injectorClient.inject();
      });
    }

    it('Registers command in app and responds to it', function(done) {
      var injection = function(require, debug, options) {
        debug.register('testcommand', function(request, response) {
          response.body = request.arguments;
        });
      };

      injectorClient.injection(
        injection,
        {},
        function(error, result) {
          if (error) return done(error);

          debuggerClient.request(
            'testcommand',
            {
              param: 'test'
            },
            function(error, result) {
              expect(error).to.equal(null);
              expect(result).to.have.property('param', 'test');
              done();
            }
          );
        }
      );
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

const RawModule = require("../lib/RawModule");
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;
const RequestShortener = require("../lib/RequestShortener");
const should = require("should");
const path = require("path");

describe("RawModule", () => {
	let myRawModule;

	before(() => {
		const source = "sourceStr attribute";
		const identifier = "identifierStr attribute";
		const readableIdentifier = "readableIdentifierStr attribute";
		myRawModule = new RawModule(source, identifier, readableIdentifier);
	});

	describe("identifier", () => {
		it("returns value for identifierStr attribute", () =>
			should(myRawModule.identifier()).be.exactly("identifierStr attribute"));
	});

	describe("size", () => {
		it("returns value for sourceStr attribute\"s length property", () => {
			const sourceStrLength = myRawModule.sourceStr.length;
			should(myRawModule.size()).be.exactly(sourceStrLength);
		});
	});

	describe("readableIdentifier", () => {
		it("returns result of calling provided requestShortener\"s shorten method\
     on readableIdentifierStr attribute", () => {
			const requestShortener = new RequestShortener(path.resolve());
			should.exist(myRawModule.readableIdentifier(requestShortener));
		});
	});

	describe("needRebuild", () => {
		it("returns false", () => should(myRawModule.needRebuild()).be.false());
	});

	describe("source", () => {
		it("returns a new OriginalSource instance with sourceStr attribute and\
        return value of identifier() function provided as constructor arguments",
			() => {
				const originalSource = new OriginalSource(myRawModule.sourceStr, myRawModule.identifier());
				myRawModule.useSourceMap = true;
				myRawModule.source().should.match(originalSource);
			});

		it("returns a new RawSource instance with sourceStr attribute provided\
        as constructor argument if useSourceMap is falsey", () => {
			const rawSource = new RawSource(myRawModule.sourceStr);
			myRawModule.useSourceMap = false;
			myRawModule.source().should.match(rawSource);
		});
	});
});
<commit_msg>replace multi line string with concat<commit_after>"use strict";

const RawModule = require("../lib/RawModule");
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;
const RequestShortener = require("../lib/RequestShortener");
const should = require("should");
const path = require("path");

describe("RawModule", () => {
	let myRawModule;

	before(() => {
		const source = "sourceStr attribute";
		const identifier = "identifierStr attribute";
		const readableIdentifier = "readableIdentifierStr attribute";
		myRawModule = new RawModule(source, identifier, readableIdentifier);
	});

	describe("identifier", () => {
		it("returns value for identifierStr attribute", () =>
			should(myRawModule.identifier()).be.exactly("identifierStr attribute"));
	});

	describe("size", () => {
		it("returns value for sourceStr attribute\"s length property", () => {
			const sourceStrLength = myRawModule.sourceStr.length;
			should(myRawModule.size()).be.exactly(sourceStrLength);
		});
	});

	describe("readableIdentifier", () => {
		it("returns result of calling provided requestShortener\"s shorten method " +
			"on readableIdentifierStr attribute", () => {
			const requestShortener = new RequestShortener(path.resolve());
			should.exist(myRawModule.readableIdentifier(requestShortener));
		});
	});

	describe("needRebuild", () => {
		it("returns false", () => should(myRawModule.needRebuild()).be.false());
	});

	describe("source", () => {
		it("returns a new OriginalSource instance with sourceStr attribute and " +
			"return value of identifier() function provided as constructor arguments",
			() => {
				const originalSource = new OriginalSource(myRawModule.sourceStr, myRawModule.identifier());
				myRawModule.useSourceMap = true;
				myRawModule.source().should.match(originalSource);
			});

		it("returns a new RawSource instance with sourceStr attribute provided " +
			"as constructor argument if useSourceMap is falsey", () => {
			const rawSource = new RawSource(myRawModule.sourceStr);
			myRawModule.useSourceMap = false;
			myRawModule.source().should.match(rawSource);
		});
	});
});
<|endoftext|>


<commit_before>/*globals describe, it*/
let CodeGenerator = require('../lib/contracts/code_generator.js');
let assert = require('assert');

function replaceCRLF(string) {
  return string.replace(/\r\n/g, '\n');
}

// TODO: instead 'eval' the code with a fake web3 object
// and check the generate code interacts as expected
describe('embark.CodeGenerator', function() {
  this.timeout(0);
  describe('#generateProvider', function() {
    let generator = new CodeGenerator({contractsConfig: {"dappConnection": [ "$WEB3", "http://somehost:1234" ] }, contractsManager: {}});

    it('should generate code to connect to a provider', function() {
      var providerCode = 'function __reduce(arr, memo, iteratee, cb) {\n  if (typeof cb !== \'function\') {\n    if (typeof memo === \'function\' && typeof iteratee === \'function\') {\n      cb = iteratee;\n      iteratee = memo;\n      memo = [];\n    } else {\n      throw new TypeError(\'expected callback to be a function\');\n    }\n  }\n\n  if (!Array.isArray(arr)) {\n    cb(new TypeError(\'expected an array\'));\n    return;\n  }\n\n  if (typeof iteratee !== \'function\') {\n    cb(new TypeError(\'expected iteratee to be a function\'));\n    return;\n  }\n\n  (function next(i, acc) {\n    if (i === arr.length) {\n      cb(null, acc);\n      return;\n    }\n\n    iteratee(acc, arr[i], function(err, val) {\n      if (err) {\n        cb(err);\n        return;\n      }\n      next(i + 1, val);\n    });\n  })(0, memo);\n};\nvar __mainContext = __mainContext || this;\n__mainContext.__LoadManager = function() { this.list = []; this.done = false; }\n__mainContext.__LoadManager.prototype.execWhenReady = function(cb) { if (this.done) { cb(); } else { this.list.push(cb) } }\n__mainContext.__LoadManager.prototype.doFirst = function(todo) { var self = this; todo(function() { self.done = true; self.list.map((x) => x.apply()) }) }\n__mainContext.__loadManagerInstance = new __mainContext.__LoadManager();\nvar whenEnvIsLoaded = function(cb) {\n  if (typeof document !== \'undefined\' && document !== null && !/comp|inter|loaded/.test(document.readyState)) {\n      document.addEventListener(\'DOMContentLoaded\', cb);\n  } else {\n    cb();\n  }\n}\nwhenEnvIsLoaded(function(){\n  __mainContext.__loadManagerInstance.doFirst(function(done) {\n    __mainContext.web3 = undefined;\n__reduce(["$WEB3","http://somehost:1234"],function(prev, value, next) {\n  if (prev === false) {\n    return next(null, false);\n  }\n\n  if (value === \'$WEB3\' && (typeof web3 !== \'undefined\' && typeof Web3 !== \'undefined\')) {\n    web3.setProvider(web3.givenProvider);\n  } else if (value !== \'$WEB3\' && (typeof Web3 !== \'undefined\' && ((typeof web3 === \'undefined\') || (typeof web3 !== \'undefined\' && (!web3.isConnected || (web3.isConnected && !web3.isConnected())))))) {\n    if (value.indexOf(\'ws://\') >= 0) {\n      web3.setProvider(new Web3.providers.WebsocketProvider(value));\n    } else {\n      web3.setProvider(new Web3.providers.HttpProvider(value));\n    }\n  } else if (value === \'$WEB3\') {\n    return next(null, \'\');\n  }\n\n  web3.eth.getAccounts(function(err, account) {\n    if (err) {\n      next(null, true)\n    } else {\n      next(null, false)\n    }\n  });\n}, function(err, _result) {\n  web3.eth.getAccounts(function(err, accounts) {\n    web3.eth.defaultAccount = accounts[0];\n    done();\n  });\n});\n\n  })\n});\n\n';

      assert.strictEqual(replaceCRLF(generator.generateProvider()), providerCode);
    });
  });

  describe('#generateContracts', function() {
    let generator = new CodeGenerator({blockchainConfig: {}, contractsManager: {
      contracts: {
        SimpleStorage: {
          abiDefinition: [{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}],
          gasEstimates: 12000,
          deployedAddress: "0x123",
          code: '12345'
        },
        Foo: {
          abiDefinition: [{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}],
          gasEstimates: 12000,
          deployedAddress: "0x124",
          code: '123456'
        }
      }
    }});

    describe('with EmbarkJS', function() {
      let withEmbarkJS = true;

      it('should generate contract code', function() {
        var contractCode = "\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n  __mainContext.SimpleStorage = new EmbarkJS.Contract({abi: [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}], address: '0x123', code: '12345', gasEstimates: 12000});\n\n});\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n  __mainContext.Foo = new EmbarkJS.Contract({abi: [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}], address: '0x124', code: '123456', gasEstimates: 12000});\n\n});\n";
        assert.strictEqual(replaceCRLF(generator.generateContracts(withEmbarkJS)), contractCode);
      });
    });

    describe('with default interface', function() {
      let withEmbarkJS = false;

      it('should generate contract code', function() {
        var contractCode = "\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n  SimpleStorageAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nSimpleStorage = new web3.eth.Contract(SimpleStorageAbi);\nSimpleStorage.options.address = '0x123';\nSimpleStorage.address = '0x123';\nSimpleStorage.options.from = web3.eth.defaultAccount;\n\n\n});\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n  FooAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nFoo = new web3.eth.Contract(FooAbi);\nFoo.options.address = '0x124';\nFoo.address = '0x124';\nFoo.options.from = web3.eth.defaultAccount;\n\n\n});\n";
        assert.strictEqual(replaceCRLF(generator.generateContracts(withEmbarkJS)), contractCode);
      });
    });

  });

  //describe('#generateABI', function() {
  //});
});
<commit_msg>update tests<commit_after>/*globals describe, it*/
let CodeGenerator = require('../lib/contracts/code_generator.js');
let assert = require('assert');

function replaceCRLF(string) {
  return string.replace(/\r\n/g, '\n');
}

// TODO: instead 'eval' the code with a fake web3 object
// and check the generate code interacts as expected
describe('embark.CodeGenerator', function() {
  this.timeout(0);
  describe('#generateProvider', function() {
    let generator = new CodeGenerator({contractsConfig: {"dappConnection": [ "$WEB3", "http://somehost:1234" ] }, contractsManager: {}});

    it('should generate code to connect to a provider', function() {
      var providerCode = 'function __reduce(arr, memo, iteratee, cb) {\n  if (typeof cb !== \'function\') {\n    if (typeof memo === \'function\' && typeof iteratee === \'function\') {\n      cb = iteratee;\n      iteratee = memo;\n      memo = [];\n    } else {\n      throw new TypeError(\'expected callback to be a function\');\n    }\n  }\n\n  if (!Array.isArray(arr)) {\n    cb(new TypeError(\'expected an array\'));\n    return;\n  }\n\n  if (typeof iteratee !== \'function\') {\n    cb(new TypeError(\'expected iteratee to be a function\'));\n    return;\n  }\n\n  (function next(i, acc) {\n    if (i === arr.length) {\n      cb(null, acc);\n      return;\n    }\n\n    iteratee(acc, arr[i], function(err, val) {\n      if (err) {\n        cb(err);\n        return;\n      }\n      next(i + 1, val);\n    });\n  })(0, memo);\n};\n\nfunction __isNewWeb3_1() {\n  return (typeof(web3.version) === \"string\");\n};\n\nfunction __getAccounts(cb) {\n  if (__isNewWeb3_1()) {\n    web3.eth.getAccounts().then(function(accounts) {\n      cb(null, accounts);\n    }).catch(function(err) {\n      cb(err);\n    });\n    return;\n  }\n  web3.eth.getAccounts(cb);\n};\n\nvar __mainContext = __mainContext || this;\n__mainContext.__LoadManager = function() { this.list = []; this.done = false; }\n__mainContext.__LoadManager.prototype.execWhenReady = function(cb) { if (this.done) { cb(); } else { this.list.push(cb) } }\n__mainContext.__LoadManager.prototype.doFirst = function(todo) { var self = this; todo(function() { self.done = true; self.list.map((x) => x.apply()) }) }\n__mainContext.__loadManagerInstance = new __mainContext.__LoadManager();\nvar whenEnvIsLoaded = function(cb) {\n  if (typeof document !== \'undefined\' && document !== null && !/comp|inter|loaded/.test(document.readyState)) {\n      document.addEventListener(\'DOMContentLoaded\', cb);\n  } else {\n    cb();\n  }\n}\nwhenEnvIsLoaded(function(){\n  __mainContext.__loadManagerInstance.doFirst(function(done) {\n    __mainContext.web3 = undefined;\n__reduce([\"$WEB3\",\"http://somehost:1234\"],function(prev, value, next) {\n  if (prev === false) {\n    return next(null, false);\n  }\n\n  if (value === \'$WEB3\' && (typeof web3 !== \'undefined\' && typeof Web3 !== \'undefined\')) {\n    web3.setProvider(web3.givenProvider);\n  } else if (value !== \'$WEB3\' && (typeof Web3 !== \'undefined\' && ((typeof web3 === \'undefined\') || (typeof web3 !== \'undefined\' && (!web3.isConnected || (web3.isConnected && !web3.isConnected())))))) {\n    if (value.indexOf(\'ws://\') >= 0) {\n      web3.setProvider(new Web3.providers.WebsocketProvider(value));\n    } else {\n      web3.setProvider(new Web3.providers.HttpProvider(value));\n    }\n  } else if (value === \'$WEB3\') {\n    return next(null, \'\');\n  }\n\n  __getAccounts(function(err, account) {\n    if (err) {\n      next(null, true)\n    } else {\n      next(null, false)\n    }\n  });\n}, function(err, _result) {\n  __getAccounts(function(err, accounts) {\n    web3.eth.defaultAccount = accounts[0];\n    done();\n  });\n});\n\n  })\n});\n\n';

      assert.strictEqual(replaceCRLF(generator.generateProvider()), providerCode);
    });
  });

  describe('#generateContracts', function() {
    let generator = new CodeGenerator({blockchainConfig: {}, contractsManager: {
      contracts: {
        SimpleStorage: {
          abiDefinition: [{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}],
          gasEstimates: 12000,
          deployedAddress: "0x123",
          code: '12345'
        },
        Foo: {
          abiDefinition: [{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}],
          gasEstimates: 12000,
          deployedAddress: "0x124",
          code: '123456'
        }
      }
    }});

    describe('with EmbarkJS', function() {
      let withEmbarkJS = true;

      it('should generate contract code', function() {
        var contractCode = "\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n  __mainContext.SimpleStorage = new EmbarkJS.Contract({abi: [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}], address: '0x123', code: '12345', gasEstimates: 12000});\n\n});\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n  __mainContext.Foo = new EmbarkJS.Contract({abi: [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}], address: '0x124', code: '123456', gasEstimates: 12000});\n\n});\n";
        assert.strictEqual(replaceCRLF(generator.generateContracts(withEmbarkJS)), contractCode);
      });
    });

    describe('with default interface', function() {
      let withEmbarkJS = false;

      it('should generate contract code', function() {
        var contractCode = "\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n  SimpleStorageAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nSimpleStorage = new web3.eth.Contract(SimpleStorageAbi);\nSimpleStorage.options.address = '0x123';\nSimpleStorage.address = '0x123';\nSimpleStorage.options.from = web3.eth.defaultAccount;\n\n\n});\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n  FooAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nFoo = new web3.eth.Contract(FooAbi);\nFoo.options.address = '0x124';\nFoo.address = '0x124';\nFoo.options.from = web3.eth.defaultAccount;\n\n\n});\n";
        assert.strictEqual(replaceCRLF(generator.generateContracts(withEmbarkJS)), contractCode);
      });
    });

  });

  //describe('#generateABI', function() {
  //});
});
<|endoftext|>