async ['@test Support shared but overridable mixin pattern'](assert) {
      assert.expect(7);

      let HasPage = Mixin.create({
        queryParams: 'page',
        page: 1,
      });

      this.add(
        'controller:parent',
        Controller.extend(HasPage, {
          queryParams: { page: 'yespage' },
        })
      );

      this.add('controller:parent.child', Controller.extend(HasPage));

      await this.setupBase();
      this.assertCurrentPath('/parent/child');

      let parentController = this.getController('parent');
      let parentChildController = this.getController('parent.child');

      await this.setAndFlush(parentChildController, 'page', 2);
      this.assertCurrentPath('/parent/child?page=2');
      assert.equal(parentController.get('page'), 1);
      assert.equal(parentChildController.get('page'), 2);

      await this.setAndFlush(parentController, 'page', 2);
      this.assertCurrentPath('/parent/child?page=2&yespage=2');
      assert.equal(parentController.get('page'), 2);
      assert.equal(parentChildController.get('page'), 2);
    }
Example #2
0
    ['@test Actions inside an outlet go to the associated controller'](assert) {
      this.add(
        'controller:index',
        Controller.extend({
          actions: {
            componentAction() {
              assert.ok(true, 'controller received the action');
            },
          },
        })
      );

      this.addComponent('component-with-action', {
        ComponentClass: Component.extend({
          classNames: ['component-with-action'],
          click() {
            this.sendAction();
          },
        }),
      });

      this.addTemplate('index', '{{component-with-action action="componentAction"}}');

      return this.visit('/').then(() => {
        this.runTask(() => this.$('.component-with-action').click());
      });
    }
Example #3
0
    ['@test predefined classes do not get logged'](assert) {
      this.add('controller:application', Controller.extend());
      this.add('controller:posts', Controller.extend());
      this.add('route:application', Route.extend());
      this.add('route:posts', Route.extend());

      return this.visit('/posts').then(() => {
        assert.ok(
          !this.logs['controller:application'],
          'did not expect: ApplicationController was generated'
        );
        assert.ok(!this.logs['controller:posts'], 'did not expect: PostsController was generated');

        assert.ok(
          !this.logs['route:application'],
          'did not expect: ApplicationRoute was generated'
        );
        assert.ok(!this.logs['route:posts'], 'did not expect: PostsRoute was generated');
      });
    }
Example #4
0
    ['@test controllers can be injected into controllers'](assert) {
      let owner = buildOwner();

      owner.register(
        'controller:post',
        Controller.extend({
          postsController: injectController('posts'),
        })
      );

      owner.register('controller:posts', Controller.extend());

      let postController = owner.lookup('controller:post');
      let postsController = owner.lookup('controller:posts');

      assert.equal(
        postsController,
        postController.get('postsController'),
        'controller.posts is injected'
      );
    }
Example #5
0
    ['@test specifying `content` (with `model` specified) does not result in deprecation'](assert) {
      assert.expect(3);
      expectNoDeprecation();

      let controller = Controller.extend({
        content: 'foo-bar',
        model: 'blammo',
      }).create();

      assert.equal(get(controller, 'content'), 'foo-bar');
      assert.equal(get(controller, 'model'), 'blammo');
    }
Example #6
0
 ['@test Action can be handled by a function on actions object'](assert) {
   assert.expect(1);
   let TestController = Controller.extend({
     actions: {
       poke() {
         assert.ok(true, 'poked');
       },
     },
   });
   let controller = TestController.create();
   controller.send('poke');
 }
Example #7
0
    ['@test A handled action can be bubbled to the target for continued processing'](assert) {
      assert.expect(2);
      let TestController = Controller.extend({
        actions: {
          poke() {
            assert.ok(true, 'poked 1');
            return true;
          },
        },
      });

      let controller = TestController.create({
        target: Controller.extend({
          actions: {
            poke() {
              assert.ok(true, 'poked 2');
            },
          },
        }).create(),
      });
      controller.send('poke');
    }
    it('validates one field per validation + module & direct validator ', function(done) {
      let service = this.subject();

      let sampleObject = Controller.extend(AdvValidable, {
        validations: [
          {
            fields: 'field1',
            validator: 'test-validator'
          },
          {
            fields: 'field2',
            validator: function(arg){
              return arg === 42;
            }
          }
        ],
        field1: 'test',
        field2: 10000000
      }).create();


      let testValidator = Service.extend(AdvValidator,{
        validate: function(){
          return true;
        },
        isAsync: false
      });

      this.register('validator:test-validator', testValidator);

      let validationResult = service.validateObject(sampleObject);
      expect(validationResult).to.exist;
      validationResult
        .then((vResult) => {
          let result = vResult.result;
          expect(result).to.exist;
          expect(result.length).to.equal(2);
          expect(result[0]).to.deep.equal({fields:'field1', result: [], params: {}}, JSON.stringify(result[0]));
          expect(result[1]).to.deep.equal({fields:'field2', result: [false], params: {}}, JSON.stringify(result[1]));

          expect(vResult.valid).to.be.false;
          expect(vResult.target).to.deep.equal(sampleObject);
          done();
        })
        .catch((e) => {
          done(e);
        });
    });
    async ['@test query params does not error when a query parameter exists for route instances that share a controller'](
      assert
    ) {
      assert.expect(1);

      let parentController = Controller.extend({
        queryParams: { page: 'page' },
      });
      this.add('controller:parent', parentController);
      this.add('route:parent.child', Route.extend({ controllerName: 'parent' }));

      await this.setupBase('/parent');
      await this.transitionTo('parent.child', { queryParams: { page: 2 } });

      this.assertCurrentPath('/parent/child?page=2');
    }
Example #10
0
    ['@test services can be injected into controllers'](assert) {
      let owner = buildOwner();

      owner.register(
        'controller:application',
        Controller.extend({
          authService: injectService('auth'),
        })
      );

      owner.register('service:auth', Service.extend());

      let appController = owner.lookup('controller:application');
      let authService = owner.lookup('service:auth');

      assert.equal(authService, appController.get('authService'), 'service.auth is injected');
    }
Example #11
0
    ['@test .send asserts if called on a destroyed controller']() {
      let owner = buildOwner();

      owner.register(
        'controller:application',
        Controller.extend({
          toString() {
            return 'controller:rip-alley';
          },
        })
      );

      let controller = owner.lookup('controller:application');
      runDestroy(owner);

      expectAssertion(() => {
        controller.send('trigger-me-dead');
      }, "Attempted to call .send() with the action 'trigger-me-dead' on the destroyed object 'controller:rip-alley'.");
    }
    it('validates one field per validation + direct function', function(done) {
      let service = this.subject();

      let sampleObject = Controller.extend(AdvValidable, {
        validations: [
          {
            fields: 'field1',
            validator: function() {
              return true;
            }
          },
          {
            fields: 'field2',
            validator: function(arg2) {
              return arg2===42;
            }
          }
        ],
        field1: 'test',
        field2: 42
      }).create();

      let validationResult = service.validateObject(sampleObject);
      expect(validationResult).to.exist;

      validationResult
        .then((vResult) => {
          let result = vResult.result;
          expect(result).to.exist;
          expect(result.length).to.equal(2);
          expect(result[0]).to.deep.equal({fields:'field1', result: [], params: {}}, JSON.stringify(result[0]));
          expect(result[1]).to.deep.equal({fields:'field2', result: [], params: {}}, JSON.stringify(result[1]));

          expect(vResult.valid).to.be.true;
          expect(vResult.target).to.deep.equal(sampleObject);
          done();
        })
        .catch((e) => {
          done(e);
        });
    });
Example #13
0
      ['@test RouterService#urlFor returns URL for simple route with basic query params and default value'](
        assert
      ) {
        assert.expect(1);

        this.add(
          'controller:parent.child',
          Controller.extend({
            queryParams: ['sort'],
            sort: 'ASC',
          })
        );

        let queryParams = this.buildQueryParams({ sort: 'ASC' });

        return this.visit('/').then(() => {
          let expectedURL = this.routerService.urlFor('parent.child', queryParams);

          assert.equal('/child?sort=ASC', expectedURL);
        });
      }
Example #14
0
      ['@test RouterService#urlFor returns URL for simple route with basic query params and default value with stickyness'](
        assert
      ) {
        assert.expect(2);

        this.add(
          'controller:parent.child',
          Controller.extend({
            queryParams: ['sort', 'foo'],
            sort: 'ASC',
          })
        );

        return this.visit('/child/?sort=DESC').then(() => {
          let controller = this.applicationInstance.lookup('controller:parent.child');
          assert.equal(get(controller, 'sort'), 'DESC', 'sticky is set');

          let queryParams = this.buildQueryParams({ foo: 'derp' });
          let actual = this.routerService.urlFor('parent.child', queryParams);

          assert.equal(actual, '/child?foo=derp', 'does not use "stickiness"');
        });
      }
Example #15
0
    ["@test Action can be handled by a superclass' actions object"](assert) {
      assert.expect(4);

      let SuperController = Controller.extend({
        actions: {
          foo() {
            assert.ok(true, 'foo');
          },
          bar(msg) {
            assert.equal(msg, 'HELLO');
          },
        },
      });

      let BarControllerMixin = Mixin.create({
        actions: {
          bar(msg) {
            assert.equal(msg, 'HELLO');
            this._super(msg);
          },
        },
      });

      let IndexController = SuperController.extend(BarControllerMixin, {
        actions: {
          baz() {
            assert.ok(true, 'baz');
          },
        },
      });

      let controller = IndexController.create({});
      controller.send('foo');
      controller.send('bar', 'HELLO');
      controller.send('baz');
    }
Example #16
0
import Controller from '@ember/controller';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';

export default Controller.extend({
  intl: service(),

  text: computed('model.content', 'intl.locale', function() {
    let intl = this.intl;

    return this.get('model.content')
      .replace('Developers', intl.t('developers'))
      .replace('Translators', intl.t('translators'));
  }),
});
Example #17
0
import Controller from "@ember/controller";

export default Controller.extend({
  actions: {
    save() {
      let self = this;
      self
        .get("model")
        .save()
        .then(function() {
          self.router.transitionTo("admin.replications.index");
        });
    },
  },
});
Example #18
0
/* eslint-disable ghost/ember/alias-model-in-controller */
import Controller from '@ember/controller';
import {computed} from '@ember/object';
import {inject as service} from '@ember/service';

export default Controller.extend({
    dropdown: service(),
    session: service(),
    settings: service(),
    ui: service(),

    showNavMenu: computed('currentPath', 'session.{isAuthenticated,user.isFulfilled}', 'ui.isFullScreen', function () {
        // if we're in fullscreen mode don't show the nav menu
        if (this.ui.isFullScreen) {
            return false;
        }

        // we need to defer showing the navigation menu until the session.user
        // promise has fulfilled so that gh-user-can-admin has the correct data
        if (!this.get('session.isAuthenticated') || !this.get('session.user.isFulfilled')) {
            return false;
        }

        return (this.get('currentPath') !== 'error404' || this.get('session.isAuthenticated'))
                && !this.get('currentPath').match(/(signin|signup|setup|reset)/);
    })
});
Example #19
0
export default Controller.extend({
  growl:       service(),
  queryParams: ['mode'],
  mode:        '',
  actions:     {
    save(success) {
      var model = get(this, 'model');
      var errors = model.pipeline.validationErrors();

      if (errors.length > 0) {
        set(this, 'errors', errors)
        success(false)

        return
      }
      var mode = get(this, 'mode');

      (() => {
        if (mode === 'duplicate'){
          return model.pipeline.save();
        }

        return model.pipeline.save(model.pipeline.serialize());
      })()
        .then(() => {
          success(true)
          set(this, 'errors', null);
          this.transitionToRoute('pipelines')
        }).catch((err) => {
          get(this, 'growl').fromError(err.message);
        }).finally(() => {
          success(false)
        })
    },
    cancel() {
      set(this, 'errors', null);
      window.history.back();
    }
  },
  stagges:     function() {
    var pipeline = get(this, 'model.pipeline');

    return pipeline.stages
  }.property('model'),
  filteredPipelineHistory: function(){
    let pipelineHistory = get(this, 'model.pipelineHistory');
    let pipeline = get(this, 'model.pipeline');

    if (!pipelineHistory){
      return;
    }
    let filteredPipelineHistory = pipelineHistory
      .filter((ele) => ele.pipeline.id === pipeline.id)
      .sort((a, b) => b.get('startedTimeStamp') - a.get('startedTimeStamp'));

    return filteredPipelineHistory;
  }.property('model.pipelineHistory.[]', 'model.pipeline'),
  editable: function(){
    let mode = get(this, 'mode');

    return (mode !== 'review');
  }.property('mode'),
});
Example #20
0
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <*****@*****.**>.
//
// https://documize.com

import { inject as service } from '@ember/service';
import Notifier from '../../../mixins/notifier';
import Controller from '@ember/controller';

export default Controller.extend(Notifier, {
	documentService: service('document'),
	router: service(),
	selectedRevision: null,

	actions: {
		onRevision(revision) {
			this.set('selectedRevision', revision);
		},

		onRollback(pageId, revisionId) {
			this.get('documentService').rollbackPage(this.get('document.id'), pageId, revisionId).then(() => {
				this.get('router').transitionTo('document.index');
			});
		}
	}
});
Example #21
0
export default Controller.extend({
  queryParams: ['dimension'],
  dimension: 'All',

  tableIsLoading: false,

  showDetails: false,
  selectedTab: 'details',

  dimensionsStart: 0,
  dimensionsEnd: 0,
  displayStart: 0,
  displayEnd: 0,
  dateFormat: 'MMM D, YYYY hh:mm a',

  subchartStart: 0,
  subchartEnd: 0,

  actions: {
    // Sets new dimension start and end
    setNewDate({ start, end }) {
      const dimensionsStart = moment(start).valueOf();
      const dimensionsEnd = moment(end).valueOf();

      this.setProperties({
        dimensionsEnd,
        dimensionsStart
      });
    },

    /**
     * Setting loading state to false on component's didRender
     */
    onRendering() {
      this.set('tableIsLoading', false);
    },

    onToggle(showDetails) {
      this.setProperties({
        showDetails,
        tableIsLoading: true
      });
    },

    /**
     * Handles subchart date change (debounced)
     */
    setDateParams([start, end]) {
      this.set('tableIsLoading', true);
      debounce(this, this.get('actions.setNewDate'), { start, end }, 500);
    },

    /**
     * Handles Contribution Table Tab selection
     * @param {String} tab Name of selected Tab
     */
    onTabChange(tab) {
      const currentTab = this.get('selectedTab');
      if (currentTab !== tab) {
        later(() => {
          this.setProperties({
            selectedTab: tab
          });
        });
      }
    }
  }

});
Example #22
0
/* eslint-disable ghost/ember/alias-model-in-controller */
import Controller, {inject as controller} from '@ember/controller';
import {computed} from '@ember/object';
import {match} from '@ember/object/computed';
import {inject as service} from '@ember/service';

export default Controller.extend({
    appController: controller('application'),
    ghostPaths: service(),

    showBackLink: match('appController.currentRouteName', /^setup\.(two|three)$/),

    backRoute: computed('appController.currentRouteName', function () {
        let currentRoute = this.get('appController.currentRouteName');

        return currentRoute === 'setup.two' ? 'setup.one' : 'setup.two';
    })
});
Example #23
0
export default Controller.extend({
  chart: null,
  pageTitle: "C3 Chart Events",
  message: null,

  init() {
    this._super(...arguments);
  },

  jsonData: null,

  data: computed(function() {
    return {
      json: this.jsonData,
      type: "bar",
      keys: {
        x: "region",
        value: ["total"]
      }
    };
  }),
  axis: {
    x: {
      type: "category",
      categories: ["Central", "East", "West"],
      rotated: true
    }
  },
  size: {
    width: 650
  },
  grid: {
    y: {
      lines: [{ value: 900, text: "Yearly Target" }]
    }
  },
  legend: {
    hide: true
  },
  tooltip: {
    grouped: false
  },
  title: { text: "Regional Sales" },
  padding: { top: 20, bottom: 5, right: 15 },

  actions: {
    init() {
      this.set("pageTitle", "Chart Events - loading...");
      later(this, () => this.set("pageTitle", "C3 Chart Events"), 500);
    },

    mouseover(chart) {
      document.getElementById(chart.element.id).classList.remove("demo-box");
      document
        .getElementById(chart.element.id)
        .classList.add("demo-chart-selected");
      this.set("pageTitle", "YTD Sales");
    },

    mouseout(chart) {
      document.getElementById(chart.element.id).classList.add("demo-box");
      document
        .getElementById(chart.element.id)
        .classList.remove("demo-chart-selected");
      this.set("pageTitle", "C3 Chart Events");
    },

    resizing(/* chart */){
      this.set("message", "adjusting...");
      later(() => this.set("message", ""), 700)
    }
  }
});
Example #24
0
import { alias } from '@ember/object/computed';
import Controller from '@ember/controller';
import WithNamespaceResetting from 'nomad-ui/mixins/with-namespace-resetting';
import Sortable from 'nomad-ui/mixins/sortable';

export default Controller.extend(WithNamespaceResetting, Sortable, {
  queryParams: {
    sortProperty: 'sort',
    sortDescending: 'desc',
  },

  sortProperty: 'modifyIndex',
  sortDescending: true,

  job: alias('model'),
  evaluations: alias('model.evaluations'),

  listToSort: alias('evaluations'),
  sortedEvaluations: alias('listSorted'),
});
Example #25
0
import Controller from '@ember/controller';

export default Controller.extend({
  queryParams: ['appId', 'appName', 'stackId', 'upgrade', 'catalog', 'namespaceId', 'clone'],
  stackId:     null,
  upgrade:     null,
  showName:    true,
  catalog:     null,
  namespaceId: null,
  appId:       null,
  appName:     null,

  parentRoute: 'catalog-tab',

  actions: {
    cancel() {
      this.send('goToPrevious', 'apps-tab.index');
    }
  },
});
Example #26
0
const headers = [
  {
    translationKey: 'membersPage.index.table.userId',
    name:           'user.displayName',
    sort:           ['user.dispalyName', 'name', 'id'],
  },
  {
    translationKey: 'membersPage.index.table.template',
    name:           'roleTemplateId',
    sort:           ['roleTemplateId'],
  },
  {
    translationKey: 'generic.created',
    name:           'created',
    sort:           ['created'],
    classNames:     'text-right pr-20',
    width:          200,
  },
]

export default Controller.extend(FilterState, {
  settings:          service(),
  scope:             service(),
  sortBy:            'name',
  headers,
  searchText:        '',
  filterableContent: computed('model.clusterRoleTemplateBindings.[]', function() {
    return get(this, 'model.clusterRoleTemplateBindings');
  }),
});
Example #27
0
import Controller from '@ember/controller';
import { set } from '@ember/object';

export default Controller.extend({
  queryParams: ['arrangeBy', 'sortBy', 'filterBy', 'query'],
  arrangeBy: null,
  sortBy: null,
  filterBy: null,
  query: '',
  isShortcutBarOpen: false,

  actions: {
    setSearchQuery(query) {
      set(this, 'query', query);
    },

    showShortcutBar() {
      set(this, 'isShortcutBarOpen', true);
    },

    toggleShortcutBar() {
      set(this, 'isShortcutBarOpen', !this.isShortcutBarOpen);
    }
  }
});
Example #28
0
File: controller.js Project: go/ui
export default Controller.extend({
  growl:             service(),
  prefs:             service(),
  scope:             service(),

  sortBy:            'name',
  queryParams:       ['sortBy'],
  searchText:        '',
  headers:           hostHeaders,

  extraSearchFields: [
    'displayUserLabelStrings',
    'requireAnyLabelStrings',
  ],

  actions: {
    scaleDownPool(id) {
      get(this,'model.cluster').send('scaleDownPool',id);
    },

    scaleUpPool(id) {
      get(this,'model.cluster').send('scaleUpPool',id);
    },

    editCluster() {
      get(this,'model.cluster').send('edit');
    },
  },

  groupByKey: computed('model.cluster.nodePools.length', function() {
    if ( get(this, 'model.cluster.nodePools.length') ) {
      return 'nodePoolId';
    }

    return null;
  }),

  rows: computed('*****@*****.**', function() {
    return get(this,'model.nodes').filterBy('clusterId', get(this,'model.cluster.id'));
  }),
});
Example #29
0
export default Controller.extend(WithHealthFiltering, {
  filter: function(item, { s = '', status = '' }) {
    const term = s.toLowerCase();
    return (
      (get(item, 'Name')
        .toLowerCase()
        .indexOf(term) !== -1 ||
        (get(item, 'Tags') || []).some(function(item) {
          return item.toLowerCase().indexOf(term) !== -1;
        })) &&
      item.hasStatus(status)
    );
  },
  totalWidth: computed('{maxPassing,maxWarning,maxCritical}', function() {
    const PADDING = 32 * 3 + 13;
    return ['maxPassing', 'maxWarning', 'maxCritical'].reduce((prev, item) => {
      return prev + width(get(this, item));
    }, PADDING);
  }),
  thWidth: computed('totalWidth', function() {
    return widthDeclaration(get(this, 'totalWidth'));
  }),
  remainingWidth: computed('totalWidth', function() {
    return htmlSafe(`width: calc(50% - ${Math.round(get(this, 'totalWidth') / 2)}px)`);
  }),
  maxPassing: computed('items', function() {
    return max(get(this, 'items'), 'ChecksPassing');
  }),
  maxWarning: computed('items', function() {
    return max(get(this, 'items'), 'ChecksWarning');
  }),
  maxCritical: computed('items', function() {
    return max(get(this, 'items'), 'ChecksCritical');
  }),
  passingWidth: computed('maxPassing', function() {
    return widthDeclaration(width(get(this, 'maxPassing')));
  }),
  warningWidth: computed('maxWarning', function() {
    return widthDeclaration(width(get(this, 'maxWarning')));
  }),
  criticalWidth: computed('maxCritical', function() {
    return widthDeclaration(width(get(this, 'maxCritical')));
  }),
});
Example #30
0
export default Controller.extend({
  draftPosts: filterBy("model","rating","draft"),
  readyPosts: filterBy("model","rating","ready"),
  unclassifiedPosts: filterBy("model","rating","unclassified"),

  /*objectDropped: function() {
    log("posts controller objectDropped");
  },*/

  objectDroppedc: function() {
    log("posts controller objectDroppedc");
  },

  objectDropped: function() {
    log("posts controller objectDropped method");
  },


  actions: {
    resetRatings: function() {
      this.get('model').forEach(function(post) {
        post.set('rating','unclassified');
        post.save();
      });
    },

    objectDropped: function(ops) {
      var bin = ops.bin;
      var obj = ops.obj;
      log("posts controller action objectDropped obj " + obj.get('title') + " bin " + bin.get('name'));
    }
  }
});