<commit_before>import { createWidget, applyDecorators } from 'discourse/widgets/widget';
import { h } from 'virtual-dom';

createWidget('admin-menu-button', {
  html(attrs) {
    let className = 'btn';
    if (attrs.buttonClass) { className += ' ' + attrs.buttonClass; }

    return h('li', { className: attrs.className }, this.attach('button', {
      className,
      action: attrs.action,
      icon: attrs.icon,
      label: `topic.${attrs.label}`,
      secondaryAction: 'hideAdminMenu'
    }));
  }
});

createWidget('topic-admin-menu-button', {
  tagName: 'span',
  buildKey: () => `topic-admin-menu-button`,

  defaultState() {
    return { expanded: false, position: null };
  },

  html(attrs, state) {
    if (!this.currentUser || !this.currentUser.get('canManageTopic')) { return; }

    const result = [];
    result.push(this.attach('button', {
      className: 'btn no-text' + (attrs.fixed ? " show-topic-admin" : ""),
      title: 'topic_admin_menu',
      icon: 'wrench',
      action: 'showAdminMenu',
      sendActionEvent: true
    }));

    if (state.expanded) {
      result.push(this.attach('topic-admin-menu', { position: state.position,
                                                    fixed: attrs.fixed,
                                                    topic: attrs.topic,
                                                    openUpwards: attrs.openUpwards }));
    }

    return result;
  },

  hideAdminMenu() {
    this.state.expanded = false;
    this.state.position = null;
  },

  showAdminMenu(e) {
    this.state.expanded = true;

    const $button = $(e.target).closest('button');
    const position = $button.position();
    position.left = position.left;

    if (this.attrs.fixed) {
      position.left += $button.width() - 203;
    }
    this.state.position = position;
  }
});

export default createWidget('topic-admin-menu', {
  tagName: 'div.popup-menu.topic-admin-popup-menu',

  buildAttributes(attrs) {
    const { top, left } = attrs.position;
    const position = attrs.fixed ? 'fixed' : 'absolute';

    if (attrs.openUpwards) {
      const bottom = $(document).height() - top;
      return { style: `position: ${position}; bottom: ${bottom}px; left: ${left}px;` };
    } else {
      return { style: `position: ${position}; top: ${top}px; left: ${left}px;` };
    }
  },

  html(attrs) {
    const buttons = [];
    buttons.push({ className: 'topic-admin-multi-select',
                   action: 'toggleMultiSelect',
                   icon: 'tasks',
                   label: 'actions.multi_select' });

    const topic = attrs.topic;
    const details = topic.get('details');
    if (details.get('can_delete')) {
      buttons.push({ className: 'topic-admin-delete',
                     buttonClass: 'btn-danger',
                     action: 'deleteTopic',
                     icon: 'trash-o',
                     label: 'actions.delete' });
    }

    if (topic.get('deleted') && details.get('can_recover')) {
      buttons.push({ className: 'topic-admin-recover',
                     action: 'recoverTopic',
                     icon: 'undo',
                     label: 'actions.recover' });
    }

    if (topic.get('closed')) {
      buttons.push({ className: 'topic-admin-open',
                     action: 'toggleClosed',
                     icon: 'unlock',
                     label: 'actions.open' });
    } else {
      buttons.push({ className: 'topic-admin-close',
                     action: 'toggleClosed',
                     icon: 'lock',
                     label: 'actions.close' });
      buttons.push({ className: 'topic-admin-autoclose',
                     action: 'showAutoClose',
                     icon: 'clock-o',
                     label: 'actions.auto_close' });
    }

    const isPrivateMessage = topic.get('isPrivateMessage');

    if (!isPrivateMessage && topic.get('visible')) {
      const featured = topic.get('pinned_at') || topic.get('isBanner');
      buttons.push({ className: 'topic-admin-pin',
                     action: 'showFeatureTopic',
                     icon: 'thumb-tack',
                     label: featured ? 'actions.unpin' : 'actions.pin' });
    }
    buttons.push({ className: 'topic-admin-change-timestamp',
                   action: 'showChangeTimestamp',
                   icon: 'calendar',
                   label: 'change_timestamp.title' });

    if (!isPrivateMessage) {
      buttons.push({ className: 'topic-admin-archive',
                     action: 'toggleArchived',
                     icon: 'folder',
                     label: topic.get('archived') ? 'actions.unarchive' : 'actions.archive' });
    }

    const visible = topic.get('visible');
    buttons.push({ className: 'topic-admin-visible',
                   action: 'toggleVisibility',
                   icon: visible ? 'eye' : 'eye-slash',
                   label: visible ? 'actions.invisible' : 'actions.visible' });

    if (this.currentUser.get('staff')) {
      buttons.push({ className: 'topic-admin-convert',
                     action: isPrivateMessage ? 'convertToPublicTopic' : 'convertToPrivateMessage',
                     icon: isPrivateMessage ? 'comment' : 'envelope',
                     label: isPrivateMessage ? 'actions.make_public' : 'actions.make_private' });
    }

    const extraButtons = applyDecorators(this, 'adminMenuButtons', this.attrs, this.state);

    return [ h('h3', I18n.t('admin_title')),
             h('ul', buttons.concat(extraButtons).map(b => this.attach('admin-menu-button', b))) ];
  },

  clickOutside() {
    this.sendWidgetAction('hideAdminMenu');
  }
});
<commit_msg>FIX: Wrench should take into account the custom header height<commit_after>import { createWidget, applyDecorators } from 'discourse/widgets/widget';
import { h } from 'virtual-dom';

createWidget('admin-menu-button', {
  html(attrs) {
    let className = 'btn';
    if (attrs.buttonClass) { className += ' ' + attrs.buttonClass; }

    return h('li', { className: attrs.className }, this.attach('button', {
      className,
      action: attrs.action,
      icon: attrs.icon,
      label: `topic.${attrs.label}`,
      secondaryAction: 'hideAdminMenu'
    }));
  }
});

createWidget('topic-admin-menu-button', {
  tagName: 'span',
  buildKey: () => `topic-admin-menu-button`,

  defaultState() {
    return { expanded: false, position: null };
  },

  html(attrs, state) {
    if (!this.currentUser || !this.currentUser.get('canManageTopic')) { return; }

    const result = [];
    result.push(this.attach('button', {
      className: 'btn no-text' + (attrs.fixed ? " show-topic-admin" : ""),
      title: 'topic_admin_menu',
      icon: 'wrench',
      action: 'showAdminMenu',
      sendActionEvent: true
    }));

    if (state.expanded) {
      result.push(this.attach('topic-admin-menu', { position: state.position,
                                                    fixed: attrs.fixed,
                                                    topic: attrs.topic,
                                                    openUpwards: attrs.openUpwards }));
    }

    return result;
  },

  hideAdminMenu() {
    this.state.expanded = false;
    this.state.position = null;
  },

  showAdminMenu(e) {
    this.state.expanded = true;

    const $button = $(e.target).closest('button');
    const position = $button.position();
    position.left = position.left;

    if (this.attrs.fixed) {
      position.left += $button.width() - 203;
    }
    this.state.position = position;
  }
});

export default createWidget('topic-admin-menu', {
  tagName: 'div.popup-menu.topic-admin-popup-menu',

  buildAttributes(attrs) {
    const { top, left } = attrs.position;
    const position = attrs.fixed ? 'fixed' : 'absolute';

    if (attrs.openUpwards) {
      const bottom = $(document).height() - top - $('#main').offset().top;
      return { style: `position: ${position}; bottom: ${bottom}px; left: ${left}px;` };
    } else {
      return { style: `position: ${position}; top: ${top}px; left: ${left}px;` };
    }
  },

  html(attrs) {
    const buttons = [];
    buttons.push({ className: 'topic-admin-multi-select',
                   action: 'toggleMultiSelect',
                   icon: 'tasks',
                   label: 'actions.multi_select' });

    const topic = attrs.topic;
    const details = topic.get('details');
    if (details.get('can_delete')) {
      buttons.push({ className: 'topic-admin-delete',
                     buttonClass: 'btn-danger',
                     action: 'deleteTopic',
                     icon: 'trash-o',
                     label: 'actions.delete' });
    }

    if (topic.get('deleted') && details.get('can_recover')) {
      buttons.push({ className: 'topic-admin-recover',
                     action: 'recoverTopic',
                     icon: 'undo',
                     label: 'actions.recover' });
    }

    if (topic.get('closed')) {
      buttons.push({ className: 'topic-admin-open',
                     action: 'toggleClosed',
                     icon: 'unlock',
                     label: 'actions.open' });
    } else {
      buttons.push({ className: 'topic-admin-close',
                     action: 'toggleClosed',
                     icon: 'lock',
                     label: 'actions.close' });
      buttons.push({ className: 'topic-admin-autoclose',
                     action: 'showAutoClose',
                     icon: 'clock-o',
                     label: 'actions.auto_close' });
    }

    const isPrivateMessage = topic.get('isPrivateMessage');

    if (!isPrivateMessage && topic.get('visible')) {
      const featured = topic.get('pinned_at') || topic.get('isBanner');
      buttons.push({ className: 'topic-admin-pin',
                     action: 'showFeatureTopic',
                     icon: 'thumb-tack',
                     label: featured ? 'actions.unpin' : 'actions.pin' });
    }
    buttons.push({ className: 'topic-admin-change-timestamp',
                   action: 'showChangeTimestamp',
                   icon: 'calendar',
                   label: 'change_timestamp.title' });

    if (!isPrivateMessage) {
      buttons.push({ className: 'topic-admin-archive',
                     action: 'toggleArchived',
                     icon: 'folder',
                     label: topic.get('archived') ? 'actions.unarchive' : 'actions.archive' });
    }

    const visible = topic.get('visible');
    buttons.push({ className: 'topic-admin-visible',
                   action: 'toggleVisibility',
                   icon: visible ? 'eye' : 'eye-slash',
                   label: visible ? 'actions.invisible' : 'actions.visible' });

    if (this.currentUser.get('staff')) {
      buttons.push({ className: 'topic-admin-convert',
                     action: isPrivateMessage ? 'convertToPublicTopic' : 'convertToPrivateMessage',
                     icon: isPrivateMessage ? 'comment' : 'envelope',
                     label: isPrivateMessage ? 'actions.make_public' : 'actions.make_private' });
    }

    const extraButtons = applyDecorators(this, 'adminMenuButtons', this.attrs, this.state);

    return [ h('h3', I18n.t('admin_title')),
             h('ul', buttons.concat(extraButtons).map(b => this.attach('admin-menu-button', b))) ];
  },

  clickOutside() {
    this.sendWidgetAction('hideAdminMenu');
  }
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require dataTables/extras/dataTables.responsive
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//
// Selectize is used by Array builder in application_helper#editable_field_html
//= require microplugin
//= require sifter
//= require selectize
// End selectize dependencies
//
//= require_tree .
<commit_msg>Require bootstrap javascript for collapse plugin to work for mobile menu.<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require dataTables/extras/dataTables.responsive
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require bootstrap-sprockets
//
// Selectize is used by Array builder in application_helper#editable_field_html
//= require microplugin
//= require sifter
//= require selectize
// End selectize dependencies
//
//= require_tree .
<|endoftext|>


<commit_before>
define([
  'backbone',
  'static-pages/views/SliderView'
], function(Backbone, SliderView) {

  'use strict';

  var SmallGrantsFundView = Backbone.View.extend({

    el: '#small-grunts-fund',

    initialize: function() {

      if(! !!this.el) {
        return;
      }

      this._setSlides();
    },

    _setSlides: function() {

      var sliders = [{
        slideOptions: {
          el: '#SFGSliderView',
          options: {
            defaultSlider: {
              autoplay: true,
              navigation: false
            }
          }
        }
      },{
        slideOptions: {
          el: '#GrantesForestSliderView',
          options: {
            defaultSlider: {
              infinite: false,
              navigation: false
            }
          }
        }
      }]

      sliders.forEach(function(slider) {
        new SliderView(slider.slideOptions);
      });
    }

  });

  return SmallGrantsFundView;

});
<commit_msg>Fix: Small Grants - Disable slider<commit_after>
define([
  'backbone',
  'static-pages/views/SliderView'
], function(Backbone, SliderView) {

  'use strict';

  var SmallGrantsFundView = Backbone.View.extend({

    el: '#small-grunts-fund',

    initialize: function() {

      if(! !!this.el) {
        return;
      }

      this._setSlides();
    },

    _setSlides: function() {

      var sliders = [{
        slideOptions: {
          el: '#SFGSliderView',
          options: {
            defaultSlider: {
              autoplay: false,
              navigation: false
            }
          }
        }
      },{
        slideOptions: {
          el: '#GrantesForestSliderView',
          options: {
            defaultSlider: {
              infinite: false,
              navigation: false
            }
          }
        }
      }]

      sliders.forEach(function(slider) {
        new SliderView(slider.slideOptions);
      });
    }

  });

  return SmallGrantsFundView;

});
<|endoftext|>


<commit_before>const INDENT_REGEXP = /\n\s+/gm;

function trimLast(str) {
  return str.replace(/\s+$/, "");
}

function changeIndent(str, diff) {
  return str.replace(INDENT_REGEXP, matched => "\n" + " ".repeat(matched.length + diff));
}

// TODO: source map support

export default
function render(indentLevel) {
  const indent = indentLevel * 2;
  return function (strings, ...values) {

    const indents = strings.map(trimLast).map(s => s.match(INDENT_REGEXP) || []).reduce((a, b) => a.concat(b), []);
    const origIndent = Math.min(...indents, 0);

    const indentedStrings = strings.map(s => changeIndent(s, indent - origIndent));

    let ret = "";

    for (let i = 0; i < strings.length; ++i) {
      ret += indentedStrings[i];
      if (i < values.length) {
        ret += String(values[i]);
      }
    }
    return ret;
  }
}
<commit_msg>Improve render<commit_after>const INDENT_REGEXP = /\n\s+/gm;

function trimLast(strings) {
  return strings.map((s, i) => {
    if (i == strings.length - 1) {
      return s.replace(/\s+$/, "");
    } else {
      return s;
    }
  });
}

function changeIndent(str, diff) {
  return str.replace(INDENT_REGEXP, matched => "\n" + " ".repeat(matched.length + diff));
}

function indents(strings) {
  return strings.map(s => (s.match(INDENT_REGEXP) || []).length);
}

// TODO: source map support

export default
function render(indentLevel) {
  const indent = indentLevel * 2;
  return function (strings, ...values) {

    const origIndent = Math.min(...indents(trimLast(strings)), 0);
    const indentedStrings = strings.map(s => changeIndent(s, indent - origIndent));

    let ret = "";

    for (let i = 0; i < strings.length; ++i) {
      ret += indentedStrings[i];
      if (i < values.length) {
        ret += String(values[i]);
      }
    }
    return ret;
  }
}
<|endoftext|>


<commit_before>import common from './common';
import sequencer from './sequencer';
import ReferenceMap from './reference.map';
import {TAG_PROPERTIES, TAG_METHODS} from './constants';

const defaultSegregation = {
    local: {},
    external: {},
    global: {},
};

/**
 * gives state default values of {
 *      methods: { local: {}, external: {}, global: {} }
 *      props: { local: {}, external: {}, global: {} }
 * }
 * @param state
 * @returns {*}
 * @private
 */
const _defaultState = (state) => {
    const defaultAttributes = {
        methods: {},
        props: {},
    };
    let newState = Object.assign({}, defaultAttributes, state);
    newState.methods = Object.assign({}, defaultSegregation, newState.methods);
    newState.props = Object.assign({}, defaultSegregation, newState.props);
    return newState;
};

/**
 * retrieves object with values derived from global data
 * @param globals - the props.global definition of the original state
 * @param root - to gain access to the global data
 * @returns {} - key-value pairs object
 * @private
 */
const _buildGlobalProps = (globals, root) => {
    let _props = {};
    if (!globals) return {};

    //takes global from datas
    for (let prop in globals) {
        //will need to retrieve the relevant data from datas to the prop

        //will create: arr[0] - data name, arr[1] - data property
        const dataName = globals[prop].data;
        const dataKey = globals[prop].key;

        if (!root.datas[dataName]) {
            console.warn(`no such data as ${dataName} defined`);
        }
        else {
            _props[prop] = root.datas[dataName].getProp(dataKey);
        }
    }
    return JSON.parse(JSON.stringify(_props));
};

/**
 * gets a state's segregated methods and returns a given method (by its name) that holds down all chained sequence
 * @param methods[Object] - all segregated state methods
 * @param seg[String] - current segment - 'local'/'external'/'global'
 * @param name[String] - current method name
 * @returns {method}
 */
const chainMethods = (methods, seg, name) => {
    let callStack = [];
    let hasLocal = false;

    switch (seg) {
        case 'global':
            if(methods.global[name]) {
                callStack.push(methods.global[name]);
            }
            /* falls through */
        case 'external':
            if(methods.external[name]) {
                callStack.push(methods.external[name]);
            }
            /* falls through */
        case 'local':
            if(methods.local[name]) {
                hasLocal = true;
                callStack.push(methods.local[name]);
            }
            /* falls through */
    }

    let method = function () {
        let tempCallStack = Object.assign([], callStack);
        let _this = this;
        let args = [].slice.call(arguments);
        let res;

        function next() {
            args = [].slice.call(arguments);
            while (tempCallStack.length > 0) {
                tempCallStack.pop().apply(_this, args);
            }
        }

        if(hasLocal) {
            res = tempCallStack.pop().apply(_this, [next].concat(args));
        }
        else {
            while (tempCallStack.length > 0) {
                tempCallStack.pop().apply(_this, args);
            }
        }
        return res;
    };
    return method;
};

const changeBindedProps = (state, props) => {
    for (let prop in props) {
        if (state.bindings[prop]) {
            state.bindings[prop].forEach((bindedState) => {
                bindedState.component.onReferenceChange({[prop]: props[prop]});
            });
        }
    }
};

/**
 *
 * @param state (will also be used as the meta-data reference, e.g. for global properties and external methods)
 * @param root
 * @returns new component-instance-state{*}
 */
export default class ComponentState {
    constructor(state, component, root) {
        this.root = root;
        this.definition = common.clone(_defaultState(state));
        this.scoped = common.clone(this.definition);

        for (let methodName in this.scoped.methods.local) {
            this.scoped.methods.local[methodName].bind(this.scoped);
        }

        for (let methodName in this.scoped.methods.external) {
            this.scoped.methods.external[methodName].bind(this.scoped);
        }

        for (let methodName in this.definition.methods.global) {
            this.scoped.methods.global[methodName] = function () {
                const originalArgs = [].slice.call(arguments);
                let mergedArgs = [this.definition.methods.global[methodName].modifier, this.definition.methods.global[methodName].key];
                if (this.definition.methods.global[methodName].pass) {
                    const passedArgs = this.definition.methods.global[methodName].pass.apply(this.scoped, originalArgs);
                    mergedArgs = mergedArgs.concat(passedArgs);
                    this.root.executeModifier.apply(this.root, mergedArgs);
                }
                else {
                    mergedArgs = mergedArgs.concat(originalArgs);
                    this.root.executeModifier.apply(this.root, mergedArgs);
                }
            }.bind(this);
        }

        this.scoped.setProps = (props, silent) => {
            const changedProps = common.setChanges(this.scoped.props.local, props, silent, true);
            if (silent) {
                this.updateLocalProps(changedProps);
                return;
            }
            if (Object.keys(changedProps).length > 0) {
                this.component.onStateChange(changedProps);
            }
        };

        this.scoped.router = this.root.router;
        this.scoped.execute = this.root.executeModifier.bind(this.root);
        this.scoped.id = component.scoped.id;

        this.component = component;

        this.reference = Object.assign({}, defaultSegregation);
        this.bindings = {};
    }

    /**
     * pass state props to the component instance (without local-external-global segregation)
     * @returns {*}
     */
    getProps() {
        const props = common.clone(this.scoped.props);
        let flatProps = Object.assign({}, props.local, props.external, props.global);
        return flatProps;
    }

    /**
     * pass state methods to the component instance (without local-external-global segregation)
     * on duplications of methodNames in different scopes, will execute all in this order:
     * local.method(); external.method(); global.method();
     * @returns {*}
     */
    getMethods() {
        const methods = common.clone(this.scoped.methods);
        const segs = ['global', 'external' ,'local'];
        let combinedMethods = {};

        for(let i in segs) {
            const seg = segs[i];
            for (let methodName in methods[seg]) {
                if (!combinedMethods[methodName]) {
                    combinedMethods[methodName] = chainMethods(methods, seg, methodName).bind(this.scoped);
                }
            }
        }
        return combinedMethods;
    }

    getGlobalDef() {
        let globals = {};
        if (this.definition.props.global) {
            Object.assign(globals, this.definition.props.global);
        }
        if (this.reference.global) {
            Object.assign(globals, this.reference.global);
        }
        if (Object.keys(globals).length > 0) {
            return JSON.parse(JSON.stringify(globals));
        }
        return null;
    }

    getGlobalStatePropName(originalProp) {
        const globals = this.getGlobalDef();
        for (let prop in globals) {
            if (globals[prop].key === originalProp) {
                return prop;
            }
        }
    }

    getGlobalStatePropNames(props) {
        let localMap = {};
        for (let prop in props) {
            const localProp = this.getGlobalStatePropName(prop);
            if (localProp !== undefined) localMap[localProp] = props[prop];
        }
        return localMap;
    }

    getReferenceStatePropName(originalProp) {
        const segs = ['global', 'external' ,'local'];
        for(let i in segs) {
            const seg = segs[i];
            for (let prop in this.reference[seg]) {
                if (this.reference[seg][prop].key === originalProp) {
                    return prop;
                }
            }
        }
    }

    getReferenceStatePropNames(props) {
        let localMap = {};
        for (let prop in props) {
            const localProp = this.getReferenceStatePropName(prop);
            if (localProp !== undefined) localMap[localProp] = props[prop];
        }
        return localMap;
    }

    updateLocalProps(changed) {
        for (let prop in changed) {
            this.scoped.props.local[prop] = changed[prop].newValue;
            changeBindedProps(this, changed);
        }
    }

    updateReferencedProps() {
        if (!this.reference.parent) return;
        let props = {
            global: {},
            external: {},
            local: {},
        };
        props.global = _buildGlobalProps(this.reference.global, this.root);
        for (let prop in this.reference.external) {
            const parentStateKey = this.reference.external[prop].key;
            props.external[prop] = this.reference.parent.props.external[parentStateKey];
        }
        for (let prop in this.reference.local) {
            const bindToRelevantAncestor = (node, prop) => {
                if (!node) {
                    return null;
                }
                if (!node.reference.local[prop]) {
                    if (node.scoped.props.local[prop]) {
                        return node.scoped.props.local[prop];
                    }
                    return bindToRelevantAncestor(node.reference.parent, prop);
                }
                const parentStateKey = node.reference.local[prop].key;
                if (node.reference.parent.scoped.props.local[parentStateKey]) {
                    return node.reference.parent.scoped.props.local[parentStateKey];
                }
                return bindToRelevantAncestor(node.reference.parent, parentStateKey);
            };
            props.local[prop] = bindToRelevantAncestor(this, prop);
        }
        const flatProps = Object.assign({}, props.local, props.external, props.global);
        Object.assign(this.scoped.props.external, flatProps);
    }

    updateGlobalProps() {
        this.scoped.props.global = _buildGlobalProps(this.definition.props.global, this.root);
        if (this.reference.parent) {
            Object.assign(this.scoped.props.external, _buildGlobalProps(this.reference.global, this.root));
        }
    }

    /**
     * sets state external properties and methods
     */
    setExternals() {
        if (this.component.mapItem.external.props || this.component.mapItem.external.methods) { //getting all external properties
            const parentComponent = this.component.parent ? this.component.parent.component : null;
            const parentState = parentComponent ? parentComponent.state : null;

            if(this.component.mapItem.external.props) {
                this.setExternalProperties(this.component.mapItem.external.props, parentState);
            }
            if(this.component.mapItem.external.methods) {
                this.setExternalMethods(this.component.mapItem.external.methods, parentComponent, parentState);
            }
        }
        if (this.component.mapItem.external.html) {
            this.scoped.html = this.component.mapItem.external.html;
        }
        if (this.component.mapItem.external.children) {
            this.scoped.children = this.component.mapItem.external.children;
        }
    }
    setExternalProperties(props, parentState) {
        let externalsProperties = {};
        let externalReferences = {
            global: {},
            external: {},
            local: {},
            parent: parentState
        };
        for (const prop in props) {
            const valueObject = props[prop];
            if (valueObject.reference) {
                this.setExternalReferencedProperty({
                    name: prop,
                    value: props[prop].reference
                }, externalReferences, parentState);
            }
            else {
                this.setExternalProperty({
                    name: prop,
                    value: props[prop].value
                }, externalsProperties);
            }
        }
        this.scoped.props.external = externalsProperties;
        this.reference = externalReferences;
    }
    setExternalProperty(item, externalProperties) {
        externalProperties[item.name] = ReferenceMap.get(item.value);
    }
    setExternalReferencedProperty(item, externalReferences, parentState) {
        const key = item.name;
        let path = item.value.split('.');
        const stateKey = path[0]; //base property in store
        path.shift();
        path = path.join('.');

        if (externalReferences.parent.reference.global.hasOwnProperty(stateKey)) {
            externalReferences.global[key] = externalReferences.parent.reference.global[item.value];
        }
        else if (externalReferences.parent.reference.external.hasOwnProperty(stateKey)) {
            externalReferences.external[key] = externalReferences.parent.reference.external[item.value];
        }
        else if (externalReferences.parent.reference.local.hasOwnProperty(stateKey)) {
            externalReferences.local[key] = externalReferences.parent.reference.local[item.value];
            const bindToRelevantAncestor = (node, prop) => {
                if (!node) {
                    return null;
                }
                if (!node.reference.local[prop]) {
                    if (node.scoped.props.local[prop]) {
                        node.bind(prop, this);
                    }
                    else {
                        bindToRelevantAncestor(node.reference.parent, prop);
                    }
                }
                else {
                    const parentStateKey = node.reference.local[prop].key;
                    if (node.reference.parent.scoped.props.local[parentStateKey]) {
                        node.reference.parent.bind(parentStateKey, this);
                    }
                    else {
                        bindToRelevantAncestor(node.reference.parent, parentStateKey);
                    }
                }
            };
            bindToRelevantAncestor(externalReferences.parent, stateKey);
        }
        else if (externalReferences.parent.scoped.props.global.hasOwnProperty(stateKey)) {
            externalReferences.global[key] = parentState.getGlobalDef()[stateKey];
            externalReferences.global[key].key += '.' + path;
        }
        else if (externalReferences.parent.scoped.props.external.hasOwnProperty(stateKey)) {
            externalReferences.external[key] = {key: item.value};
        }
        else {
            externalReferences.local[key] = {key: item.value};
            parentState.bind(stateKey, this);
        }
    }

    setExternalMethods(methods, parentComponent, parentState) {
        let externalMethods = {};

        for (const method in methods) {
            const valueObject = methods[method];
            if (valueObject.reference) {
                this.setExternalReferenceMethod({
                    name: method,
                    value: methods[method]
                }, externalMethods, parentComponent, parentState);
            }
            else {
                this.setExternalMethod({
                    name: method,
                    value: methods[method].value
                }, externalMethods);
            }
        }
        this.scoped.methods.external = Object.assign({}, this.definition.methods.external, externalMethods);
    }
    setExternalMethod(item, externalMethods) {
        externalMethods[item.name] = ReferenceMap.get(item.value);
    }
    setExternalReferenceMethod(item, externalMethods, parentComponent, parentState) {
        const parentMethods = parentState.getMethods();
        let methodParams = item.value;
        if (parentMethods[methodParams.reference]) {
            const methodName = item.name;
            externalMethods[methodName] = function () {
                parentMethods[methodParams.reference].apply(parentComponent, arguments);
            };
        }
    }

    bind(prop, state) {
        if(!this.bindings[prop]) {
            this.bindings[prop] = [];
        }
        this.bindings[prop].push(state);
    }

    addRoutes() {
        if (this.definition.routes) {
            this.definition.routes.forEach(i => this.root.router.add(i, this.scoped));
        }
    }

    removeRoutes() {
        if (this.definition.routes) {
            this.root.router.remove(this.scoped);
        }
    }
}<commit_msg>fix of global reference issue<commit_after>import common from './common';
import sequencer from './sequencer';
import ReferenceMap from './reference.map';
import {TAG_PROPERTIES, TAG_METHODS} from './constants';

const defaultSegregation = {
    local: {},
    external: {},
    global: {},
};

/**
 * gives state default values of {
 *      methods: { local: {}, external: {}, global: {} }
 *      props: { local: {}, external: {}, global: {} }
 * }
 * @param state
 * @returns {*}
 * @private
 */
const _defaultState = (state) => {
    const defaultAttributes = {
        methods: {},
        props: {},
    };
    let newState = Object.assign({}, defaultAttributes, state);
    newState.methods = Object.assign({}, defaultSegregation, newState.methods);
    newState.props = Object.assign({}, defaultSegregation, newState.props);
    return newState;
};

/**
 * retrieves object with values derived from global data
 * @param globals - the props.global definition of the original state
 * @param root - to gain access to the global data
 * @returns {} - key-value pairs object
 * @private
 */
const _buildGlobalProps = (globals, root) => {
    let _props = {};
    if (!globals) return {};

    //takes global from datas
    for (let prop in globals) {
        //will need to retrieve the relevant data from datas to the prop

        //will create: arr[0] - data name, arr[1] - data property
        const dataName = globals[prop].data;
        const dataKey = globals[prop].key;

        if (!root.datas[dataName]) {
            console.warn(`no such data as ${dataName} defined`);
        }
        else {
            _props[prop] = root.datas[dataName].getProp(dataKey);
        }
    }
    return JSON.parse(JSON.stringify(_props));
};

/**
 * gets a state's segregated methods and returns a given method (by its name) that holds down all chained sequence
 * @param methods[Object] - all segregated state methods
 * @param seg[String] - current segment - 'local'/'external'/'global'
 * @param name[String] - current method name
 * @returns {method}
 */
const chainMethods = (methods, seg, name) => {
    let callStack = [];
    let hasLocal = false;

    switch (seg) {
        case 'global':
            if(methods.global[name]) {
                callStack.push(methods.global[name]);
            }
            /* falls through */
        case 'external':
            if(methods.external[name]) {
                callStack.push(methods.external[name]);
            }
            /* falls through */
        case 'local':
            if(methods.local[name]) {
                hasLocal = true;
                callStack.push(methods.local[name]);
            }
            /* falls through */
    }

    let method = function () {
        let tempCallStack = Object.assign([], callStack);
        let _this = this;
        let args = [].slice.call(arguments);
        let res;

        function next() {
            args = [].slice.call(arguments);
            while (tempCallStack.length > 0) {
                tempCallStack.pop().apply(_this, args);
            }
        }

        if(hasLocal) {
            res = tempCallStack.pop().apply(_this, [next].concat(args));
        }
        else {
            while (tempCallStack.length > 0) {
                tempCallStack.pop().apply(_this, args);
            }
        }
        return res;
    };
    return method;
};

const changeBindedProps = (state, props) => {
    for (let prop in props) {
        if (state.bindings[prop]) {
            state.bindings[prop].forEach((bindedState) => {
                bindedState.component.onReferenceChange({[prop]: props[prop]});
            });
        }
    }
};

/**
 *
 * @param state (will also be used as the meta-data reference, e.g. for global properties and external methods)
 * @param root
 * @returns new component-instance-state{*}
 */
export default class ComponentState {
    constructor(state, component, root) {
        this.root = root;
        this.definition = common.clone(_defaultState(state));
        this.scoped = common.clone(this.definition);

        for (let methodName in this.scoped.methods.local) {
            this.scoped.methods.local[methodName].bind(this.scoped);
        }

        for (let methodName in this.scoped.methods.external) {
            this.scoped.methods.external[methodName].bind(this.scoped);
        }

        for (let methodName in this.definition.methods.global) {
            this.scoped.methods.global[methodName] = function () {
                const originalArgs = [].slice.call(arguments);
                let mergedArgs = [this.definition.methods.global[methodName].modifier, this.definition.methods.global[methodName].key];
                if (this.definition.methods.global[methodName].pass) {
                    const passedArgs = this.definition.methods.global[methodName].pass.apply(this.scoped, originalArgs);
                    mergedArgs = mergedArgs.concat(passedArgs);
                    this.root.executeModifier.apply(this.root, mergedArgs);
                }
                else {
                    mergedArgs = mergedArgs.concat(originalArgs);
                    this.root.executeModifier.apply(this.root, mergedArgs);
                }
            }.bind(this);
        }

        this.scoped.setProps = (props, silent) => {
            const changedProps = common.setChanges(this.scoped.props.local, props, silent, true);
            if (silent) {
                this.updateLocalProps(changedProps);
                return;
            }
            if (Object.keys(changedProps).length > 0) {
                this.component.onStateChange(changedProps);
            }
        };

        this.scoped.router = this.root.router;
        this.scoped.execute = this.root.executeModifier.bind(this.root);
        this.scoped.id = component.scoped.id;

        this.component = component;

        this.reference = Object.assign({}, defaultSegregation);
        this.bindings = {};
    }

    /**
     * pass state props to the component instance (without local-external-global segregation)
     * @returns {*}
     */
    getProps() {
        const props = common.clone(this.scoped.props);
        let flatProps = Object.assign({}, props.local, props.external, props.global);
        return flatProps;
    }

    /**
     * pass state methods to the component instance (without local-external-global segregation)
     * on duplications of methodNames in different scopes, will execute all in this order:
     * local.method(); external.method(); global.method();
     * @returns {*}
     */
    getMethods() {
        const methods = common.clone(this.scoped.methods);
        const segs = ['global', 'external' ,'local'];
        let combinedMethods = {};

        for(let i in segs) {
            const seg = segs[i];
            for (let methodName in methods[seg]) {
                if (!combinedMethods[methodName]) {
                    combinedMethods[methodName] = chainMethods(methods, seg, methodName).bind(this.scoped);
                }
            }
        }
        return combinedMethods;
    }

    getGlobalDef() {
        let globals = {};
        if (this.definition.props.global) {
            Object.assign(globals, this.definition.props.global);
        }
        if (this.reference.global) {
            Object.assign(globals, this.reference.global);
        }
        if (Object.keys(globals).length > 0) {
            return JSON.parse(JSON.stringify(globals));
        }
        return null;
    }

    getGlobalStatePropName(originalProp) {
        const globals = this.getGlobalDef();
        for (let prop in globals) {
            if (globals[prop].key === originalProp) {
                return prop;
            }
        }
    }

    getGlobalStatePropNames(props) {
        let localMap = {};
        for (let prop in props) {
            const localProp = this.getGlobalStatePropName(prop);
            if (localProp !== undefined) localMap[localProp] = props[prop];
        }
        return localMap;
    }

    getReferenceStatePropName(originalProp) {
        const segs = ['global', 'external' ,'local'];
        for(let i in segs) {
            const seg = segs[i];
            for (let prop in this.reference[seg]) {
                if (this.reference[seg][prop].key === originalProp) {
                    return prop;
                }
            }
        }
    }

    getReferenceStatePropNames(props) {
        let localMap = {};
        for (let prop in props) {
            const localProp = this.getReferenceStatePropName(prop);
            if (localProp !== undefined) localMap[localProp] = props[prop];
        }
        return localMap;
    }

    updateLocalProps(changed) {
        for (let prop in changed) {
            this.scoped.props.local[prop] = changed[prop].newValue;
            changeBindedProps(this, changed);
        }
    }

    updateReferencedProps() {
        if (!this.reference.parent) return;
        let props = {
            global: {},
            external: {},
            local: {},
        };
        props.global = _buildGlobalProps(this.reference.global, this.root);
        for (let prop in this.reference.external) {
            const parentStateKey = this.reference.external[prop].key;
            props.external[prop] = this.reference.parent.props.external[parentStateKey];
        }
        for (let prop in this.reference.local) {
            const bindToRelevantAncestor = (node, prop) => {
                if (!node) {
                    return null;
                }
                if (!node.reference.local[prop]) {
                    if (node.scoped.props.local[prop]) {
                        return node.scoped.props.local[prop];
                    }
                    return bindToRelevantAncestor(node.reference.parent, prop);
                }
                const parentStateKey = node.reference.local[prop].key;
                if (node.reference.parent.scoped.props.local[parentStateKey]) {
                    return node.reference.parent.scoped.props.local[parentStateKey];
                }
                return bindToRelevantAncestor(node.reference.parent, parentStateKey);
            };
            props.local[prop] = bindToRelevantAncestor(this, prop);
        }
        const flatProps = Object.assign({}, props.local, props.external, props.global);
        Object.assign(this.scoped.props.external, flatProps);
    }

    updateGlobalProps() {
        this.scoped.props.global = _buildGlobalProps(this.definition.props.global, this.root);
        if (this.reference.parent) {
            Object.assign(this.scoped.props.external, _buildGlobalProps(this.reference.global, this.root));
        }
    }

    /**
     * sets state external properties and methods
     */
    setExternals() {
        if (this.component.mapItem.external.props || this.component.mapItem.external.methods) { //getting all external properties
            const parentComponent = this.component.parent ? this.component.parent.component : null;
            const parentState = parentComponent ? parentComponent.state : null;

            if(this.component.mapItem.external.props) {
                this.setExternalProperties(this.component.mapItem.external.props, parentState);
            }
            if(this.component.mapItem.external.methods) {
                this.setExternalMethods(this.component.mapItem.external.methods, parentComponent, parentState);
            }
        }
        if (this.component.mapItem.external.html) {
            this.scoped.html = this.component.mapItem.external.html;
        }
        if (this.component.mapItem.external.children) {
            this.scoped.children = this.component.mapItem.external.children;
        }
    }
    setExternalProperties(props, parentState) {
        let externalsProperties = {};
        let externalReferences = {
            global: {},
            external: {},
            local: {},
            parent: parentState
        };
        for (const prop in props) {
            const valueObject = props[prop];
            if (valueObject.reference) {
                this.setExternalReferencedProperty({
                    name: prop,
                    value: props[prop].reference
                }, externalReferences, parentState);
            }
            else {
                this.setExternalProperty({
                    name: prop,
                    value: props[prop].value
                }, externalsProperties);
            }
        }
        this.scoped.props.external = externalsProperties;
        this.reference = externalReferences;
    }
    setExternalProperty(item, externalProperties) {
        externalProperties[item.name] = ReferenceMap.get(item.value);
    }
    setExternalReferencedProperty(item, externalReferences, parentState) {
        const key = item.name;
        let path = item.value.split('.');
        const stateKey = path[0]; //base property in store
        path.shift();
        path = path.join('.');

        if (externalReferences.parent.reference.global.hasOwnProperty(stateKey)) {
            externalReferences.global[key] = externalReferences.parent.reference.global[item.value];
        }
        else if (externalReferences.parent.reference.external.hasOwnProperty(stateKey)) {
            externalReferences.external[key] = externalReferences.parent.reference.external[item.value];
        }
        else if (externalReferences.parent.reference.local.hasOwnProperty(stateKey)) {
            externalReferences.local[key] = externalReferences.parent.reference.local[item.value];
            const bindToRelevantAncestor = (node, prop) => {
                if (!node) {
                    return null;
                }
                if (!node.reference.local[prop]) {
                    if (node.scoped.props.local[prop]) {
                        node.bind(prop, this);
                    }
                    else {
                        bindToRelevantAncestor(node.reference.parent, prop);
                    }
                }
                else {
                    const parentStateKey = node.reference.local[prop].key;
                    if (node.reference.parent.scoped.props.local[parentStateKey]) {
                        node.reference.parent.bind(parentStateKey, this);
                    }
                    else {
                        bindToRelevantAncestor(node.reference.parent, parentStateKey);
                    }
                }
            };
            bindToRelevantAncestor(externalReferences.parent, stateKey);
        }
        else if (externalReferences.parent.scoped.props.global.hasOwnProperty(stateKey)) {
            externalReferences.global[key] = parentState.getGlobalDef()[stateKey];
            if(path) {
                externalReferences.global[key].key += '.' + path;
            }
        }
        else if (externalReferences.parent.scoped.props.external.hasOwnProperty(stateKey)) {
            externalReferences.external[key] = {key: item.value};
        }
        else {
            externalReferences.local[key] = {key: item.value};
            parentState.bind(stateKey, this);
        }
    }

    setExternalMethods(methods, parentComponent, parentState) {
        let externalMethods = {};

        for (const method in methods) {
            const valueObject = methods[method];
            if (valueObject.reference) {
                this.setExternalReferenceMethod({
                    name: method,
                    value: methods[method]
                }, externalMethods, parentComponent, parentState);
            }
            else {
                this.setExternalMethod({
                    name: method,
                    value: methods[method].value
                }, externalMethods);
            }
        }
        this.scoped.methods.external = Object.assign({}, this.definition.methods.external, externalMethods);
    }
    setExternalMethod(item, externalMethods) {
        externalMethods[item.name] = ReferenceMap.get(item.value);
    }
    setExternalReferenceMethod(item, externalMethods, parentComponent, parentState) {
        const parentMethods = parentState.getMethods();
        let methodParams = item.value;
        if (parentMethods[methodParams.reference]) {
            const methodName = item.name;
            externalMethods[methodName] = function () {
                parentMethods[methodParams.reference].apply(parentComponent, arguments);
            };
        }
    }

    bind(prop, state) {
        if(!this.bindings[prop]) {
            this.bindings[prop] = [];
        }
        this.bindings[prop].push(state);
    }

    addRoutes() {
        if (this.definition.routes) {
            this.definition.routes.forEach(i => this.root.router.add(i, this.scoped));
        }
    }

    removeRoutes() {
        if (this.definition.routes) {
            this.root.router.remove(this.scoped);
        }
    }
}<|endoftext|>


<commit_before>module.exports = function (fork) {
  fork.use(require("./es7"));

  var types = fork.use(require("../lib/types"));
  var def = types.Type.def;
  var or = types.Type.or;
  var defaults = fork.use(require("../lib/shared")).defaults;

  def("TSType")
    .bases("Node");

  def("TSTypeReference")
    .bases("TSType")
    .field("typeName", def("Identifier"))
    .field("typeParameters",
           or(def("TSTypeParameterInstantiation"), null),
           defaults["null"]);

  var IdOrQualifiedName = or(
    def("Identifier"),
    def("TSQualifiedName")
  );

  def("TSQualifiedName")
    .bases("Node")
    .build("left", "right")
    .field("left", IdOrQualifiedName)
    .field("right", IdOrQualifiedName);

  def("TSAsExpression")
    .bases("Expression")
    .build("expression")
    .field("expression", def("Expression"))
    .field("typeAnnotation", def("TSType"))
    .field("extra",
           or({ parenthesized: Boolean }, null),
           defaults["null"]);

  def("TSNonNullExpression")
    .bases("Expression")
    .build("expression")
    .field("expression", def("Expression"));

  [ // Define all the simple keyword types.
    "TSAnyKeyword",
    "TSBooleanKeyword",
    "TSNeverKeyword",
    "TSNullKeyword",
    "TSNumberKeyword",
    "TSObjectKeyword",
    "TSStringKeyword",
    "TSSymbolKeyword",
    "TSUndefinedKeyword",
    "TSVoidKeyword",
    "TSThisType",
  ].forEach(keywordType => {
    def(keywordType)
      .bases("TSType")
      .build();
  });

  def("TSArrayType")
    .bases("TSType")
    .build("elementType")
    .field("elementType", def("TSType"))

  def("TSLiteralType")
    .bases("TSType")
    .build("literal")
    .field("literal",
           or(def("NumericLiteral"),
              def("StringLiteral"),
              def("BooleanLiteral")));

  ["TSUnionType",
   "TSIntersectionType",
  ].forEach(typeName => {
    def(typeName)
      .bases("TSType")
      .build("types")
      .field("types", [def("TSType")]);
  });

  def("TSParenthesizedType")
    .bases("TSType")
    .build("typeAnnotation")
    .field("typeAnnotation", def("TSType"));

  var ParametersType = [or(
    def("Identifier"),
    def("RestElement")
  )];

  ["TSFunctionType",
   "TSConstructorType",
  ].forEach(typeName => {
    def(typeName)
      .bases("TSType")
      .build("parameters")
      .field("typeParameters", def("TSTypeParameterDeclaration"))
      .field("parameters", ParametersType)
      .field("typeAnnotation", def("TSTypeAnnotation"));
  });

  def("TSDeclareFunction")
    .bases("Declaration")
    .build("id", "params", "returnType")
    .field("declare", Boolean, defaults["false"])
    .field("async", Boolean, defaults["false"])
    .field("generator", Boolean, defaults["false"])
    .field("id", or(def("Identifier"), null), defaults["null"])
    .field("params", [def("Pattern")])
    // tSFunctionTypeAnnotationCommon
    .field("returnType",
           or(def("TSTypeAnnotation"),
              def("Noop"), // Still used?
              null),
           defaults["null"])
    .field("typeParameters",
           or(def("TSTypeParameterDeclaration"),
              def("Noop"), // Still used?
              null),
           defaults["null"]);

  def("TSDeclareMethod")
    .bases("Declaration")
    .build("key", "params", "returnType")
    .field("async", Boolean, defaults["false"])
    .field("generator", Boolean, defaults["false"])
    .field("params", [def("Pattern")])
    // classMethodOrPropertyCommon
    .field("abstract", Boolean, defaults["false"])
    .field("accessibility",
           or("public", "private", "protected", void 0),
           defaults["undefined"])
    .field("static", Boolean, defaults["false"])
    .field("computed", Boolean, defaults["false"])
    .field("optional", Boolean, defaults["false"])
    .field("key", or(
      def("Identifier"),
      def("StringLiteral"),
      def("NumericLiteral"),
      // Only allowed if .computed is true.
      def("Expression")
    ))
    // classMethodOrDeclareMethodCommon
    .field("kind",
           or("get", "set", "method", "constructor"),
           function getDefault() { return "method"; })
    .field("access", // Not "accessibility"?
           or("public", "private", "protected", void 0),
           defaults["undefined"])
    .field("decorators",
           or([def("Decorator")], null),
           defaults["null"])
    // tSFunctionTypeAnnotationCommon
    .field("returnType",
           or(def("TSTypeAnnotation"),
              def("Noop"), // Still used?
              null),
           defaults["null"])
    .field("typeParameters",
           or(def("TSTypeParameterDeclaration"),
              def("Noop"), // Still used?
              null),
           defaults["null"]);

  def("TSMappedType")
    .bases("TSType")
    .build("typeParameter", "typeAnnotation")
    .field("readonly", Boolean, defaults["false"])
    .field("typeParameter", def("TSTypeParameter"))
    .field("optional", Boolean, defaults["false"])
    .field("typeAnnotation",
           or(def("TSType"), null),
           defaults["null"]);

  def("TSTupleType")
    .bases("TSType")
    .build("elementTypes")
    .field("elementTypes", [def("TSType")]);

  def("TSIndexedAccessType")
    .bases("TSType")
    .build("objectType", "indexType")
    .field("objectType", def("TSType"))
    .field("indexType", def("TSType"))

  def("TSTypeOperator")
    .bases("TSType")
    .build("operator")
    .field("operator", or(def("Literal"), def("StringLiteral")))
    .field("typeAnnotation", def("TSType"));

  def("TSTypeAnnotation")
    .bases("Node")
    .build("typeAnnotation")
    .field("typeAnnotation", def("TSType"));

  def("TSIndexSignature")
    .bases("Node")
    .build("parameters")
    .field("parameters", [def("Identifier")]) // Length === 1
    .field("readonly", Boolean, defaults["false"])
    .field("typeAnnotation", def("TSTypeAnnotation"));

  def("TSPropertySignature")
    .bases("Node")
    .build("key")
    .field("key", def("Expression"))
    .field("computed", Boolean, defaults["false"])
    .field("readonly", Boolean, defaults["false"])
    .field("optional", Boolean, defaults["false"])
    .field("initializer",
           or(def("Expression"), null),
           defaults["null"])
    .field("typeAnnotation", def("TSTypeAnnotation"))

  def("TSMethodSignature")
    .bases("Node")
    .build("key")
    .field("key", def("Identifier"))
    .field("computed", Boolean, defaults["false"])
    .field("optional", Boolean, defaults["false"])
    .field("typeParameters", def("TSTypeParameterDeclaration"))
    .field("parameters", ParametersType)
    .field("typeAnnotation", def("TSTypeAnnotation"));

  def("TSTypePredicate")
    .bases("TSTypeAnnotation")
    .build("parameterName", "typeAnnotation")
    .field("parameterName",
           or(def("Identifier"),
              def("TSThisType")))
    .field("typeAnnotation", def("TSTypeAnnotation"));

  ["TSCallSignatureDeclaration",
   "TSConstructSignatureDeclaration",
  ].forEach(typeName => {
    def(typeName)
      .bases("Declaration")
      .build("parameters")
      .field("typeParameters", def("TSTypeParameterDeclaration"))
      .field("parameters", ParametersType)
      .field("typeAnnotation", def("TSTypeAnnotation"));
  });

  def("TSEnumMember")
    .bases("Node")
    .build("id", "initializer")
    .field("id", or(def("Identifier"), def("StringLiteral")))
    .field("initializer",
           or(def("Expression"), null),
           defaults["null"]);

  def("TSTypeQuery")
    .bases("TSType")
    .build("exprName")
    .field("exprName", def("Identifier"));

  // Inferred from Babylon's tsParseTypeMember method.
  var TSTypeMember = or(
    def("TSCallSignatureDeclaration"),
    def("TSConstructSignatureDeclaration"),
    def("TSIndexSignature"),
    def("TSMethodSignature"),
    def("TSPropertySignature")
  );

  def("TSTypeLiteral")
    .bases("TSType")
    .build("members")
    .field("members", [TSTypeMember]);

  def("TSTypeParameter")
    .bases("Identifier")
    .field("name", or(def("Literal"), def("StringLiteral")))
    .field("constraint", or(def("TSType"), null), defaults["null"])
    .field("default", or(def("TSType"), null), defaults["null"]);

  def("TSTypeAssertion")
    .bases("Expression")
    .build("typeAnnotation", "expression")
    .field("typeAnnotation", def("TSType"))
    .field("expression", def("Expression"))
    .field("extra",
           or({ parenthesized: Boolean }, null),
           defaults["null"]);

  def("TSTypeParameterDeclaration")
    .bases("Declaration")
    .build("params")
    .field("params", [def("TSTypeParameter")]);

  def("TSTypeParameterInstantiation")
    .bases("Node")
    .build("params")
    .field("params", [def("TSType")]);

  def("TSEnumDeclaration")
    .bases("Declaration")
    .build("id", "members")
    .field("id", def("Identifier"))
    .field("const", Boolean, defaults["false"])
    .field("declare", Boolean, defaults["false"])
    .field("members", [def("TSEnumMember")])
    .field("initializer",
           or(def("Expression"), null),
           defaults["null"]);

  def("TSTypeAliasDeclaration")
    .bases("Declaration")
    .build("id")
    .field("id", def("Identifier"))
    .field("declare", Boolean, defaults["false"])
    .field("typeParameters",
           or(def("TSTypeParameterDeclaration"), null),
           defaults["null"])
    .field("typeAnnotation", def("TSType"));

  def("TSModuleBlock")
    .bases("Node")
    .build("body")
    .field("body", [def("Statement")]);

  def("TSModuleDeclaration")
    .bases("Declaration")
    .build("id", "body")
    .field("id", def("Identifier"))
    .field("declare", Boolean, defaults["false"])
    .field("global", Boolean, defaults["false"])
    .field("body", or(def("TSModuleBlock"),
                      def("TSModuleDeclaration")));

  def("TSInterfaceBody")
    .bases("Node")
    .build("body")
    .field("body", [TSTypeMember]);

  def("TSExpressionWithTypeArguments")
    .bases("TSType")
    .build("expression", "typeParameters")
    .field("expression", def("Identifier"))
    .field("typeParameters",
           or(def("TSTypeParameterInstantiation"), null),
           defaults["null"]);

  def("TSInterfaceDeclaration")
    .bases("Declaration")
    .build("id", "body")
    .field("id", def("Identifier"))
    .field("declare", Boolean, defaults["false"])
    .field("typeParameters",
           or(def("TSTypeParameterDeclaration"), null),
           defaults["null"])
    .field("extends",
           or([def("TSExpressionWithTypeArguments")], null),
           defaults["null"])
    .field("body", def("TSInterfaceBody"));

  def("TSParameterProperty")
    .bases("Pattern")
    .build("parameter")
    .field("accessibility",
           or("public", "private", "protected", void 0),
           defaults["undefined"])
    .field("readonly", Boolean, defaults["false"])
    .field("parameter", or(def("Identifier"),
                           def("AssignmentPattern")));
};
<commit_msg>Add TSImportEqualsDeclaration and TSExternalModuleReference.<commit_after>module.exports = function (fork) {
  fork.use(require("./es7"));

  var types = fork.use(require("../lib/types"));
  var def = types.Type.def;
  var or = types.Type.or;
  var defaults = fork.use(require("../lib/shared")).defaults;

  def("TSType")
    .bases("Node");

  def("TSTypeReference")
    .bases("TSType")
    .field("typeName", def("Identifier"))
    .field("typeParameters",
           or(def("TSTypeParameterInstantiation"), null),
           defaults["null"]);

  var IdOrQualifiedName = or(
    def("Identifier"),
    def("TSQualifiedName")
  );

  def("TSQualifiedName")
    .bases("Node")
    .build("left", "right")
    .field("left", IdOrQualifiedName)
    .field("right", IdOrQualifiedName);

  def("TSAsExpression")
    .bases("Expression")
    .build("expression")
    .field("expression", def("Expression"))
    .field("typeAnnotation", def("TSType"))
    .field("extra",
           or({ parenthesized: Boolean }, null),
           defaults["null"]);

  def("TSNonNullExpression")
    .bases("Expression")
    .build("expression")
    .field("expression", def("Expression"));

  [ // Define all the simple keyword types.
    "TSAnyKeyword",
    "TSBooleanKeyword",
    "TSNeverKeyword",
    "TSNullKeyword",
    "TSNumberKeyword",
    "TSObjectKeyword",
    "TSStringKeyword",
    "TSSymbolKeyword",
    "TSUndefinedKeyword",
    "TSVoidKeyword",
    "TSThisType",
  ].forEach(keywordType => {
    def(keywordType)
      .bases("TSType")
      .build();
  });

  def("TSArrayType")
    .bases("TSType")
    .build("elementType")
    .field("elementType", def("TSType"))

  def("TSLiteralType")
    .bases("TSType")
    .build("literal")
    .field("literal",
           or(def("NumericLiteral"),
              def("StringLiteral"),
              def("BooleanLiteral")));

  ["TSUnionType",
   "TSIntersectionType",
  ].forEach(typeName => {
    def(typeName)
      .bases("TSType")
      .build("types")
      .field("types", [def("TSType")]);
  });

  def("TSParenthesizedType")
    .bases("TSType")
    .build("typeAnnotation")
    .field("typeAnnotation", def("TSType"));

  var ParametersType = [or(
    def("Identifier"),
    def("RestElement")
  )];

  ["TSFunctionType",
   "TSConstructorType",
  ].forEach(typeName => {
    def(typeName)
      .bases("TSType")
      .build("parameters")
      .field("typeParameters", def("TSTypeParameterDeclaration"))
      .field("parameters", ParametersType)
      .field("typeAnnotation", def("TSTypeAnnotation"));
  });

  def("TSDeclareFunction")
    .bases("Declaration")
    .build("id", "params", "returnType")
    .field("declare", Boolean, defaults["false"])
    .field("async", Boolean, defaults["false"])
    .field("generator", Boolean, defaults["false"])
    .field("id", or(def("Identifier"), null), defaults["null"])
    .field("params", [def("Pattern")])
    // tSFunctionTypeAnnotationCommon
    .field("returnType",
           or(def("TSTypeAnnotation"),
              def("Noop"), // Still used?
              null),
           defaults["null"])
    .field("typeParameters",
           or(def("TSTypeParameterDeclaration"),
              def("Noop"), // Still used?
              null),
           defaults["null"]);

  def("TSDeclareMethod")
    .bases("Declaration")
    .build("key", "params", "returnType")
    .field("async", Boolean, defaults["false"])
    .field("generator", Boolean, defaults["false"])
    .field("params", [def("Pattern")])
    // classMethodOrPropertyCommon
    .field("abstract", Boolean, defaults["false"])
    .field("accessibility",
           or("public", "private", "protected", void 0),
           defaults["undefined"])
    .field("static", Boolean, defaults["false"])
    .field("computed", Boolean, defaults["false"])
    .field("optional", Boolean, defaults["false"])
    .field("key", or(
      def("Identifier"),
      def("StringLiteral"),
      def("NumericLiteral"),
      // Only allowed if .computed is true.
      def("Expression")
    ))
    // classMethodOrDeclareMethodCommon
    .field("kind",
           or("get", "set", "method", "constructor"),
           function getDefault() { return "method"; })
    .field("access", // Not "accessibility"?
           or("public", "private", "protected", void 0),
           defaults["undefined"])
    .field("decorators",
           or([def("Decorator")], null),
           defaults["null"])
    // tSFunctionTypeAnnotationCommon
    .field("returnType",
           or(def("TSTypeAnnotation"),
              def("Noop"), // Still used?
              null),
           defaults["null"])
    .field("typeParameters",
           or(def("TSTypeParameterDeclaration"),
              def("Noop"), // Still used?
              null),
           defaults["null"]);

  def("TSMappedType")
    .bases("TSType")
    .build("typeParameter", "typeAnnotation")
    .field("readonly", Boolean, defaults["false"])
    .field("typeParameter", def("TSTypeParameter"))
    .field("optional", Boolean, defaults["false"])
    .field("typeAnnotation",
           or(def("TSType"), null),
           defaults["null"]);

  def("TSTupleType")
    .bases("TSType")
    .build("elementTypes")
    .field("elementTypes", [def("TSType")]);

  def("TSIndexedAccessType")
    .bases("TSType")
    .build("objectType", "indexType")
    .field("objectType", def("TSType"))
    .field("indexType", def("TSType"))

  def("TSTypeOperator")
    .bases("TSType")
    .build("operator")
    .field("operator", or(def("Literal"), def("StringLiteral")))
    .field("typeAnnotation", def("TSType"));

  def("TSTypeAnnotation")
    .bases("Node")
    .build("typeAnnotation")
    .field("typeAnnotation", def("TSType"));

  def("TSIndexSignature")
    .bases("Node")
    .build("parameters")
    .field("parameters", [def("Identifier")]) // Length === 1
    .field("readonly", Boolean, defaults["false"])
    .field("typeAnnotation", def("TSTypeAnnotation"));

  def("TSPropertySignature")
    .bases("Node")
    .build("key")
    .field("key", def("Expression"))
    .field("computed", Boolean, defaults["false"])
    .field("readonly", Boolean, defaults["false"])
    .field("optional", Boolean, defaults["false"])
    .field("initializer",
           or(def("Expression"), null),
           defaults["null"])
    .field("typeAnnotation", def("TSTypeAnnotation"))

  def("TSMethodSignature")
    .bases("Node")
    .build("key")
    .field("key", def("Identifier"))
    .field("computed", Boolean, defaults["false"])
    .field("optional", Boolean, defaults["false"])
    .field("typeParameters", def("TSTypeParameterDeclaration"))
    .field("parameters", ParametersType)
    .field("typeAnnotation", def("TSTypeAnnotation"));

  def("TSTypePredicate")
    .bases("TSTypeAnnotation")
    .build("parameterName", "typeAnnotation")
    .field("parameterName",
           or(def("Identifier"),
              def("TSThisType")))
    .field("typeAnnotation", def("TSTypeAnnotation"));

  ["TSCallSignatureDeclaration",
   "TSConstructSignatureDeclaration",
  ].forEach(typeName => {
    def(typeName)
      .bases("Declaration")
      .build("parameters")
      .field("typeParameters", def("TSTypeParameterDeclaration"))
      .field("parameters", ParametersType)
      .field("typeAnnotation", def("TSTypeAnnotation"));
  });

  def("TSEnumMember")
    .bases("Node")
    .build("id", "initializer")
    .field("id", or(def("Identifier"), def("StringLiteral")))
    .field("initializer",
           or(def("Expression"), null),
           defaults["null"]);

  def("TSTypeQuery")
    .bases("TSType")
    .build("exprName")
    .field("exprName", def("Identifier"));

  // Inferred from Babylon's tsParseTypeMember method.
  var TSTypeMember = or(
    def("TSCallSignatureDeclaration"),
    def("TSConstructSignatureDeclaration"),
    def("TSIndexSignature"),
    def("TSMethodSignature"),
    def("TSPropertySignature")
  );

  def("TSTypeLiteral")
    .bases("TSType")
    .build("members")
    .field("members", [TSTypeMember]);

  def("TSTypeParameter")
    .bases("Identifier")
    .field("name", or(def("Literal"), def("StringLiteral")))
    .field("constraint", or(def("TSType"), null), defaults["null"])
    .field("default", or(def("TSType"), null), defaults["null"]);

  def("TSTypeAssertion")
    .bases("Expression")
    .build("typeAnnotation", "expression")
    .field("typeAnnotation", def("TSType"))
    .field("expression", def("Expression"))
    .field("extra",
           or({ parenthesized: Boolean }, null),
           defaults["null"]);

  def("TSTypeParameterDeclaration")
    .bases("Declaration")
    .build("params")
    .field("params", [def("TSTypeParameter")]);

  def("TSTypeParameterInstantiation")
    .bases("Node")
    .build("params")
    .field("params", [def("TSType")]);

  def("TSEnumDeclaration")
    .bases("Declaration")
    .build("id", "members")
    .field("id", def("Identifier"))
    .field("const", Boolean, defaults["false"])
    .field("declare", Boolean, defaults["false"])
    .field("members", [def("TSEnumMember")])
    .field("initializer",
           or(def("Expression"), null),
           defaults["null"]);

  def("TSTypeAliasDeclaration")
    .bases("Declaration")
    .build("id")
    .field("id", def("Identifier"))
    .field("declare", Boolean, defaults["false"])
    .field("typeParameters",
           or(def("TSTypeParameterDeclaration"), null),
           defaults["null"])
    .field("typeAnnotation", def("TSType"));

  def("TSModuleBlock")
    .bases("Node")
    .build("body")
    .field("body", [def("Statement")]);

  def("TSModuleDeclaration")
    .bases("Declaration")
    .build("id", "body")
    .field("id", def("Identifier"))
    .field("declare", Boolean, defaults["false"])
    .field("global", Boolean, defaults["false"])
    .field("body", or(def("TSModuleBlock"),
                      def("TSModuleDeclaration")));

  def("TSImportEqualsDeclaration")
    .bases("Statement")
    .build("id", "moduleReference")
    .field("id", def("Identifier"))
    .field("isExport", Boolean, defaults["false"])
    .field("moduleReference",
           or(def("Identifier"),
              def("TSExternalModuleReference")));

  def("TSExternalModuleReference")
    .bases("Node")
    .build("expression")
    .field("expression", def("StringLiteral"));

  def("TSInterfaceBody")
    .bases("Node")
    .build("body")
    .field("body", [TSTypeMember]);

  def("TSExpressionWithTypeArguments")
    .bases("TSType")
    .build("expression", "typeParameters")
    .field("expression", def("Identifier"))
    .field("typeParameters",
           or(def("TSTypeParameterInstantiation"), null),
           defaults["null"]);

  def("TSInterfaceDeclaration")
    .bases("Declaration")
    .build("id", "body")
    .field("id", def("Identifier"))
    .field("declare", Boolean, defaults["false"])
    .field("typeParameters",
           or(def("TSTypeParameterDeclaration"), null),
           defaults["null"])
    .field("extends",
           or([def("TSExpressionWithTypeArguments")], null),
           defaults["null"])
    .field("body", def("TSInterfaceBody"));

  def("TSParameterProperty")
    .bases("Pattern")
    .build("parameter")
    .field("accessibility",
           or("public", "private", "protected", void 0),
           defaults["undefined"])
    .field("readonly", Boolean, defaults["false"])
    .field("parameter", or(def("Identifier"),
                           def("AssignmentPattern")));
};
<|endoftext|>


<commit_before>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the 'License'); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an 'AS IS'
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var Fields = require('oae-config/lib/fields');

var widths = [
    {
        'name': '25%',
        'value': '3'
    },
    {
        'name': '33%',
        'value': '4'
    },
    {
        'name': '50%',
        'value': '6'
    },
    {
        'name': '66%',
        'value': '8'
    },
    {
        'name': '75%',
        'value': '9'
    },
    {
        'name': '100%',
        'value': '12'
    }
];

/**
 * Create a configurable landing page block with some configured default values
 *
 * @param  {Object}     [opts]                      The default values for the landing page block
 * @param  {String}     [opts.type]                 The block type. Defaults to `empty`
 * @param  {Number}     [opts.xs]                   Block width at extra small resolution. Defaults to 12
 * @param  {Number}     [opts.sm]                   Block width at small resolution. Defaults to 12
 * @param  {Number}     [opts.md]                   Block width at medium resolution. Defaults to 12
 * @param  {Number}     [opts.lg]                   Block width at large resolution. Defaults to 12
 * @param  {Number}     [opts.minHeight]            The minimum heigh in pixels
 * @param  {String}     [opts.bgColor]              The default background color. If left null, the block will be transparent
 * @param  {String}     [opts.titleColor]           The default title color
 * @param  {String}     [opts.textColor]            The default text color
 * @param  {String}     [opts.text]                 The default text
 * @param  {String}     [opts.icon]                 The default icon
 * @param  {String}     [opts.imgUrl]               The path to the default image URL
 * @param  {String}     [opts.videoUrl]             The path to the default video URL
 * @param  {String}     [opts.videoPlaceholder]     The path to the default video placeholder image
 * @return {Object}                                 The created landing page block
 * @api private
 */
var _createBlock = function(opts) {
    opts = opts || {};

    type = opts.type || 'empty';
    xs = opts.xs || 12
    sm = opts.sm || 12;
    md = opts.md || 12;
    lg = opts.lg || 12;

    return {
        'name': 'Block values',
        'description': 'Block values',
        'elements': {
            'type': new Fields.List('Block type', 'Block type', opts.type, [
                {
                    'name': 'Empty',
                    'value': 'empty'
                },
                {
                    'name': 'Search',
                    'value': 'search'
                },
                {
                    'name': 'Text',
                    'value': 'text'
                },
                {
                    'name': 'Text with icon',
                    'value': 'iconText'
                },
                {
                    'name': 'Image',
                    'value': 'image'
                },
                {
                    'name': 'Video',
                    'value': 'video'
                }
            ],  {'suppress': true}),
            'xs': new Fields.List('XS Block width', 'Block width at extra small resolution', opts.xs, widths, {'suppress': true}),
            'sm': new Fields.List('SM Block width', 'Block width at small resolution', opts.sm, widths, {'suppress': true}),
            'md': new Fields.List('MD Block width', 'Block width at medium resolution', opts.md, widths, {'suppress': true}),
            'lg': new Fields.List('LG Block width', 'Block width at large resolution', opts.lg, widths, {'suppress': true}),
            'minHeight': new Fields.Text('Block minimum height', 'Minimum height for the block in px', opts.minHeight, {'suppress': true}),
            'bgColor': new Fields.Text('Block background color', 'Background color for the block', opts.bgColor, {'suppress': true}),
            'titleColor': new Fields.Text('Block title color', 'Title color for the block', opts.titleColor, {'suppress': true}),
            'textColor': new Fields.Text('Block text color', 'Text color for the block', opts.textColor, {'suppress': true}),
            'text': new Fields.InternationalizableText('Block text', 'Text content for the block', opts.text, {'suppress': true}),
            'icon': new Fields.Text('Block icon', 'Icon for the block', opts.icon, {'suppress': true}),
            'imgUrl': new Fields.Text('Image URL', 'Image URL', opts.imgUrl, {'suppress': true}),
            'videoUrl': new Fields.Text('Video URL', 'Video URL', opts.videoUrl, {'suppress': true}),
            'videoPlaceholder': new Fields.Text('Video Placeholder Image', 'URL for video placeholder image', opts.videoPlaceholder, {'suppress': true})
        }
    };
};

module.exports = {
    'title': 'OAE Tenant Module',
    'block_1': _createBlock({
        'type': 'search',
        'xs': 12,
        'sm': 12,
        'md': 12,
        'lg': 12
    }),
    'block_2': _createBlock({
        'type': 'video',
        'xs': 12,
        'sm': 12,
        'md': 8,
        'lg': 8,
        'minHeight': 290,
        'videoUrl': 'https://www.youtube.com/watch?v=cfiM87Y0pWw',
        'videoPlaceholder': '/ui/img/index-video-bg.png'
    }),
    'block_3': _createBlock({
        'type': 'text',
        'xs': 12,
        'sm': 6,
        'md': 4,
        'lg': 4,
        'titleColor': '#FFF',
        'textColor': '#FFF',
        'text': '# __MSG__SUPPORTING_ACADEMIC_COLLABORATION__\n __MSG__A_POWERFULL_NEW_WAY_FOR_STUDENTS_AND_FACULTY_TO_CREATE_KNOWLEDGE_COLLABORATE_AND_CONNECT_WITH_THE_WORLD__'
    }),
    'block_4': _createBlock({
        'type': 'iconText',
        'xs': 12,
        'sm': 6,
        'md': 4,
        'lg': 4,
        'bgColor': '#FFF',
        'titleColor': '#4199CA',
        'textColor': '#000',
        'text': '#### __MSG__AUTHORING_EXPERIENCE__\n __MSG__RICH_COMPELLING_INTERACTIVE_CONTENT_AUTHORING__',
        'icon': 'fa-edit'
    }),
    'block_5': _createBlock({
        'type': 'iconText',
        'xs': 12,
        'sm': 6,
        'md': 4,
        'lg': 4,
        'bgColor': '#424242',
        'titleColor': '#FFF',
        'textColor': '#FFF',
        'text': '#### __MSG__CHANNELS_OF_COMMUNICATION__\n __MSG__PARTICIPATING_IN_DISCUSSIONS_AND_FEEDBACK_WITHIN_PERSONALIZED_NETWORKS__',
        'icon': 'fa-comments'
    }),
    'block_6': _createBlock({
        'type': 'iconText',
        'xs': 12,
        'sm': 6,
        'md': 4,
        'lg': 4,
        'bgColor': '#f0EEEC',
        'titleColor': '#424242',
        'textColor': '#000',
        'text': '#### __MSG__ACCESS_TO_CONTENT__\n __MSG__EXPANDED_ACCESS_TO_LEARNING_AND_RESEARCH_MATERIALS_BETTER_CONNECTS_LIBRARY_SERVICES__',
        'icon': 'fa-cloud-download'
    }),
    'block_7': _createBlock(),
    'block_8': _createBlock(),
    'block_9': _createBlock(),
    'block_10': _createBlock(),
    'block_11': _createBlock(),
    'block_12': _createBlock()
};
<commit_msg>Fixed linting issue in tenant landing pages config<commit_after>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the 'License'); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an 'AS IS'
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var Fields = require('oae-config/lib/fields');

var widths = [
    {
        'name': '25%',
        'value': '3'
    },
    {
        'name': '33%',
        'value': '4'
    },
    {
        'name': '50%',
        'value': '6'
    },
    {
        'name': '66%',
        'value': '8'
    },
    {
        'name': '75%',
        'value': '9'
    },
    {
        'name': '100%',
        'value': '12'
    }
];

/**
 * Create a configurable landing page block with some configured default values
 *
 * @param  {Object}     [opts]                      The default values for the landing page block
 * @param  {String}     [opts.type]                 The block type. Defaults to `empty`
 * @param  {Number}     [opts.xs]                   Block width at extra small resolution. Defaults to 12
 * @param  {Number}     [opts.sm]                   Block width at small resolution. Defaults to 12
 * @param  {Number}     [opts.md]                   Block width at medium resolution. Defaults to 12
 * @param  {Number}     [opts.lg]                   Block width at large resolution. Defaults to 12
 * @param  {Number}     [opts.minHeight]            The minimum heigh in pixels
 * @param  {String}     [opts.bgColor]              The default background color. If left null, the block will be transparent
 * @param  {String}     [opts.titleColor]           The default title color
 * @param  {String}     [opts.textColor]            The default text color
 * @param  {String}     [opts.text]                 The default text
 * @param  {String}     [opts.icon]                 The default icon
 * @param  {String}     [opts.imgUrl]               The path to the default image URL
 * @param  {String}     [opts.videoUrl]             The path to the default video URL
 * @param  {String}     [opts.videoPlaceholder]     The path to the default video placeholder image
 * @return {Object}                                 The created landing page block
 * @api private
 */
var _createBlock = function(opts) {
    opts = opts || {};

    type = opts.type || 'empty';
    xs = opts.xs || 12;
    sm = opts.sm || 12;
    md = opts.md || 12;
    lg = opts.lg || 12;

    return {
        'name': 'Block values',
        'description': 'Block values',
        'elements': {
            'type': new Fields.List('Block type', 'Block type', opts.type, [
                {
                    'name': 'Empty',
                    'value': 'empty'
                },
                {
                    'name': 'Search',
                    'value': 'search'
                },
                {
                    'name': 'Text',
                    'value': 'text'
                },
                {
                    'name': 'Text with icon',
                    'value': 'iconText'
                },
                {
                    'name': 'Image',
                    'value': 'image'
                },
                {
                    'name': 'Video',
                    'value': 'video'
                }
            ],  {'suppress': true}),
            'xs': new Fields.List('XS Block width', 'Block width at extra small resolution', opts.xs, widths, {'suppress': true}),
            'sm': new Fields.List('SM Block width', 'Block width at small resolution', opts.sm, widths, {'suppress': true}),
            'md': new Fields.List('MD Block width', 'Block width at medium resolution', opts.md, widths, {'suppress': true}),
            'lg': new Fields.List('LG Block width', 'Block width at large resolution', opts.lg, widths, {'suppress': true}),
            'minHeight': new Fields.Text('Block minimum height', 'Minimum height for the block in px', opts.minHeight, {'suppress': true}),
            'bgColor': new Fields.Text('Block background color', 'Background color for the block', opts.bgColor, {'suppress': true}),
            'titleColor': new Fields.Text('Block title color', 'Title color for the block', opts.titleColor, {'suppress': true}),
            'textColor': new Fields.Text('Block text color', 'Text color for the block', opts.textColor, {'suppress': true}),
            'text': new Fields.InternationalizableText('Block text', 'Text content for the block', opts.text, {'suppress': true}),
            'icon': new Fields.Text('Block icon', 'Icon for the block', opts.icon, {'suppress': true}),
            'imgUrl': new Fields.Text('Image URL', 'Image URL', opts.imgUrl, {'suppress': true}),
            'videoUrl': new Fields.Text('Video URL', 'Video URL', opts.videoUrl, {'suppress': true}),
            'videoPlaceholder': new Fields.Text('Video Placeholder Image', 'URL for video placeholder image', opts.videoPlaceholder, {'suppress': true})
        }
    };
};

module.exports = {
    'title': 'OAE Tenant Module',
    'block_1': _createBlock({
        'type': 'search',
        'xs': 12,
        'sm': 12,
        'md': 12,
        'lg': 12
    }),
    'block_2': _createBlock({
        'type': 'video',
        'xs': 12,
        'sm': 12,
        'md': 8,
        'lg': 8,
        'minHeight': 290,
        'videoUrl': 'https://www.youtube.com/watch?v=cfiM87Y0pWw',
        'videoPlaceholder': '/ui/img/index-video-bg.png'
    }),
    'block_3': _createBlock({
        'type': 'text',
        'xs': 12,
        'sm': 6,
        'md': 4,
        'lg': 4,
        'titleColor': '#FFF',
        'textColor': '#FFF',
        'text': '# __MSG__SUPPORTING_ACADEMIC_COLLABORATION__\n __MSG__A_POWERFULL_NEW_WAY_FOR_STUDENTS_AND_FACULTY_TO_CREATE_KNOWLEDGE_COLLABORATE_AND_CONNECT_WITH_THE_WORLD__'
    }),
    'block_4': _createBlock({
        'type': 'iconText',
        'xs': 12,
        'sm': 6,
        'md': 4,
        'lg': 4,
        'bgColor': '#FFF',
        'titleColor': '#4199CA',
        'textColor': '#000',
        'text': '#### __MSG__AUTHORING_EXPERIENCE__\n __MSG__RICH_COMPELLING_INTERACTIVE_CONTENT_AUTHORING__',
        'icon': 'fa-edit'
    }),
    'block_5': _createBlock({
        'type': 'iconText',
        'xs': 12,
        'sm': 6,
        'md': 4,
        'lg': 4,
        'bgColor': '#424242',
        'titleColor': '#FFF',
        'textColor': '#FFF',
        'text': '#### __MSG__CHANNELS_OF_COMMUNICATION__\n __MSG__PARTICIPATING_IN_DISCUSSIONS_AND_FEEDBACK_WITHIN_PERSONALIZED_NETWORKS__',
        'icon': 'fa-comments'
    }),
    'block_6': _createBlock({
        'type': 'iconText',
        'xs': 12,
        'sm': 6,
        'md': 4,
        'lg': 4,
        'bgColor': '#f0EEEC',
        'titleColor': '#424242',
        'textColor': '#000',
        'text': '#### __MSG__ACCESS_TO_CONTENT__\n __MSG__EXPANDED_ACCESS_TO_LEARNING_AND_RESEARCH_MATERIALS_BETTER_CONNECTS_LIBRARY_SERVICES__',
        'icon': 'fa-cloud-download'
    }),
    'block_7': _createBlock(),
    'block_8': _createBlock(),
    'block_9': _createBlock(),
    'block_10': _createBlock(),
    'block_11': _createBlock(),
    'block_12': _createBlock()
};
<|endoftext|>


<commit_before>function onAuthCallback() {

    var codeInfo = getCodeFromUrl();
    if (!codeInfo) {
        alert("failed to receive auth code (the token to get the token)");
        return
    }

    var code = codeInfo["code"]
    alert("code: " + code)
    jQuery.get("https://lively-kernel.org/lively4-auth/github_accesstoken?code=" + code,
              function(data, status, xhr) {
                var authInfo = parseAuthInfoFromUrl(data)
                window.opener.githubAuth.onAuthenticated(window.uuid, authInfo);
                window.close()
              }
              ).fail(function(err) {
                alert("Getting the key from Github failed: " + err)
              })

}

function getCodeFromUrl() {
  if (window.location.search) {
    var authResponse = window.location.search.substring(1);
    var authInfo = JSON.parse(
      '{"' + authResponse.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
      function(key, value) { return key === "" ? value : decodeURIComponent(value); });
    return authInfo;
  }
}

function parseAuthInfoFromUrl() {
  if (window.location.hash) {
    var authResponse = window.location.hash.substring(1);
    var authInfo = JSON.parse(
      '{"' + authResponse.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
      function(key, value) { return key === "" ? value : decodeURIComponent(value); });
    return authInfo;
  }
}
<commit_msg>draft ace editor<commit_after>function onAuthCallback() {

    var codeInfo = getCodeFromUrl();
    if (!codeInfo) {
        alert("failed to receive auth code (the token to get the token)");
        return
    }

    var code = codeInfo["code"]
    alert("code: " + code)
    jQuery.get("https://lively-kernel.org/lively4-auth/github_accesstoken?code=" + code,
              function(data, status, xhr) {
                var authInfo = parseAuthInfoFromUrl(data)
                window.opener.githubAuth.onAuthenticated(window.uuid, authInfo);
                window.close()
              }
              ).fail(function(err) {
                alert("Getting the key from Github failed: " + err)
              })

}

function getCodeFromUrl() {
  if (window.location.search) {
    var authResponse = window.location.search.substring(1);
    var authInfo = JSON.parse(
      '{"' + authResponse.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
      function(key, value) { return key === "" ? value : decodeURIComponent(value); });
    return authInfo;
  }
}

function parseAuthInfoFromUrl(data) {
  var authInfo = JSON.parse(
    '{"' + data.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
    function(key, value) { return key === "" ? value : decodeURIComponent(value); });
  return authInfo;
}
<|endoftext|>