<commit_before>import { moduleFor, RenderingTest } from '../../utils/test-case';
import { Component } from '../../utils/helpers';
import {
  instrumentationSubscribe,
  instrumentationReset,
  set
} from 'ember-metal';

moduleFor('Components instrumentation', class extends RenderingTest {
  constructor() {
    super();

    this.resetEvents();

    instrumentationSubscribe('render.component', {
      before: (name, timestamp, payload) => {
        if (payload.view !== this.component) {
          this.actual.before.push(payload);
        }
      },
      after: (name, timestamp, payload) => {
        if (payload.view !== this.component) {
          this.actual.after.push(payload);
        }
      }
    });
  }

  resetEvents() {
    this.expected = {
      before: [],
      after: []
    };

    this.actual = {
      before: [],
      after: []
    };
  }

  teardown() {
    this.assert.deepEqual(this.actual.before, [], 'No unexpected events (before)');
    this.assert.deepEqual(this.actual.after, [], 'No unexpected events (after)');
    super.teardown();
    instrumentationReset();
  }

  ['@test zomg'](assert) { assert.ok(true); }

  ['@test it should receive an instrumentation event for both initial render and updates'](assert) {
    let testCase = this;

    let BaseClass = Component.extend({
      tagName: '',

      willRender() {
        testCase.expected.before.push(this);
        testCase.expected.after.unshift(this);
      }
    });

    this.registerComponent('x-bar', {
      template: '[x-bar: {{bar}}] {{yield}}',
      ComponentClass: BaseClass.extend()
    });

    this.registerComponent('x-baz', {
      template: '[x-baz: {{baz}}]',
      ComponentClass: BaseClass.extend()
    });

    this.registerComponent('x-bat', {
      template: '[x-bat: {{bat}}]',
      ComponentClass: BaseClass.extend()
    });

    this.render(`[-top-level: {{foo}}] {{#x-bar bar=bar}}{{x-baz baz=baz}}{{/x-bar}} {{x-bat bat=bat}}`, {
      foo: 'foo', bar: 'bar', baz: 'baz', bat: 'bat'
    });

    this.assertText('[-top-level: foo] [x-bar: bar] [x-baz: baz] [x-bat: bat]');

    this.assertEvents('after initial render', true);

    this.runTask(() => this.rerender());

    this.assertEvents('after no-op rerender');

    this.runTask(() => set(this.context, 'foo', 'FOO'));

    this.assertEvents('after updating top-level');

    this.runTask(() => set(this.context, 'baz', 'BAZ'));

    this.assertEvents('after updating inner-most');

    this.runTask(() => {
      set(this.context, 'bar', 'BAR');
      set(this.context, 'bat', 'BAT');
    });

    this.assertEvents('after updating the rest');

    this.runTask(() => {
      set(this.context, 'foo', 'FOO');
      set(this.context, 'bar', 'BAR');
      set(this.context, 'baz', 'BAZ');
      set(this.context, 'bat', 'BAT');
    });

    this.assertEvents('after reset');
  }

  assertEvents(label, initialRender = false) {
    let { actual, expected } = this;

    this.assert.strictEqual(actual.before.length, actual.after.length, `${label}: before and after callbacks should be balanced`);

    this._assertEvents(`${label} (before):`, actual.before, expected.before, initialRender);
    this._assertEvents(`${label} (after):`, actual.before, expected.before, initialRender);

    this.resetEvents();
  }

  _assertEvents(label, actual, expected, initialRender) {
    this.assert.equal(actual.length, expected.length, `${label}: expected ${expected.length} and got ${actual.length}`);

    actual.forEach((payload, i) => this.assertPayload(payload, expected[i], initialRender));
  }

  assertPayload(payload, component, initialRender) {
    this.assert.equal(payload.object, component.toString(), 'payload.object');
    this.assert.equal(payload.containerKey, component._debugContainerKey, 'payload.containerKey');
    this.assert.equal(payload.view, component, 'payload.view');
    this.assert.strictEqual(payload.initialRender, initialRender, 'payload.initialRender');
  }
});
<commit_msg>ensure that containerKey is present<commit_after>import { moduleFor, RenderingTest } from '../../utils/test-case';
import { Component } from '../../utils/helpers';
import {
  instrumentationSubscribe,
  instrumentationReset,
  set
} from 'ember-metal';

moduleFor('Components instrumentation', class extends RenderingTest {
  constructor() {
    super();

    this.resetEvents();

    instrumentationSubscribe('render.component', {
      before: (name, timestamp, payload) => {
        if (payload.view !== this.component) {
          this.actual.before.push(payload);
        }
      },
      after: (name, timestamp, payload) => {
        if (payload.view !== this.component) {
          this.actual.after.push(payload);
        }
      }
    });
  }

  resetEvents() {
    this.expected = {
      before: [],
      after: []
    };

    this.actual = {
      before: [],
      after: []
    };
  }

  teardown() {
    this.assert.deepEqual(this.actual.before, [], 'No unexpected events (before)');
    this.assert.deepEqual(this.actual.after, [], 'No unexpected events (after)');
    super.teardown();
    instrumentationReset();
  }

  ['@test zomg'](assert) { assert.ok(true); }

  ['@test it should receive an instrumentation event for both initial render and updates'](assert) {
    let testCase = this;

    let BaseClass = Component.extend({
      tagName: '',

      willRender() {
        testCase.expected.before.push(this);
        testCase.expected.after.unshift(this);
      }
    });

    this.registerComponent('x-bar', {
      template: '[x-bar: {{bar}}] {{yield}}',
      ComponentClass: BaseClass.extend()
    });

    this.registerComponent('x-baz', {
      template: '[x-baz: {{baz}}]',
      ComponentClass: BaseClass.extend()
    });

    this.registerComponent('x-bat', {
      template: '[x-bat: {{bat}}]',
      ComponentClass: BaseClass.extend()
    });

    this.render(`[-top-level: {{foo}}] {{#x-bar bar=bar}}{{x-baz baz=baz}}{{/x-bar}} {{x-bat bat=bat}}`, {
      foo: 'foo', bar: 'bar', baz: 'baz', bat: 'bat'
    });

    this.assertText('[-top-level: foo] [x-bar: bar] [x-baz: baz] [x-bat: bat]');

    this.assertEvents('after initial render', true);

    this.runTask(() => this.rerender());

    this.assertEvents('after no-op rerender');

    this.runTask(() => set(this.context, 'foo', 'FOO'));

    this.assertEvents('after updating top-level');

    this.runTask(() => set(this.context, 'baz', 'BAZ'));

    this.assertEvents('after updating inner-most');

    this.runTask(() => {
      set(this.context, 'bar', 'BAR');
      set(this.context, 'bat', 'BAT');
    });

    this.assertEvents('after updating the rest');

    this.runTask(() => {
      set(this.context, 'foo', 'FOO');
      set(this.context, 'bar', 'BAR');
      set(this.context, 'baz', 'BAZ');
      set(this.context, 'bat', 'BAT');
    });

    this.assertEvents('after reset');
  }

  assertEvents(label, initialRender = false) {
    let { actual, expected } = this;

    this.assert.strictEqual(actual.before.length, actual.after.length, `${label}: before and after callbacks should be balanced`);

    this._assertEvents(`${label} (before):`, actual.before, expected.before, initialRender);
    this._assertEvents(`${label} (after):`, actual.before, expected.before, initialRender);

    this.resetEvents();
  }

  _assertEvents(label, actual, expected, initialRender) {
    this.assert.equal(actual.length, expected.length, `${label}: expected ${expected.length} and got ${actual.length}`);

    actual.forEach((payload, i) => this.assertPayload(payload, expected[i], initialRender));
  }

  assertPayload(payload, component, initialRender) {
    this.assert.equal(payload.object, component.toString(), 'payload.object');
    this.assert.ok(payload.containerKey, 'the container key should be present');
    this.assert.equal(payload.containerKey, component._debugContainerKey, 'payload.containerKey');
    this.assert.equal(payload.view, component, 'payload.view');
    this.assert.strictEqual(payload.initialRender, initialRender, 'payload.initialRender');
  }
});
<|endoftext|>


<commit_before>import { moduleFor, RenderingTest } from '../../utils/test-case';
import { strip } from '../../utils/abstract-test-case';
import { _registerMacros, _experimentalMacros } from 'ember-glimmer';
import { compileArgs } from '@glimmer/runtime';

moduleFor('registerMacros', class extends RenderingTest {
  constructor() {
    let originalMacros = _experimentalMacros.slice();

    _registerMacros((blocks, inlines) => {
      blocks.add('-let', (sexp, builder) => {
        let [,, params, hash, _default] = sexp;
        let args = compileArgs(params, hash, builder);

        builder.putArgs(args);

        builder.labelled(null, b => {
          b.evaluate(_default);
        });
      });
    });

    super();
    this.originalMacros = originalMacros;
  }

  teardown() {
    _experimentalMacros.length = 0;
    this.originalMacros.forEach(macro => _experimentalMacros.push(macro));

    super.teardown();
  }

  ['@test allows registering custom syntax via private API'](assert) {
    this.render(strip`
      {{#-let obj as |bar|}}
        {{bar}}
      {{/-let}}
    `, { obj: 'hello world!'});

    this.assertText('hello world!');
  }
});
<commit_msg>Fix macro syntax<commit_after>import { moduleFor, RenderingTest } from '../../utils/test-case';
import { strip } from '../../utils/abstract-test-case';
import { _registerMacros, _experimentalMacros } from 'ember-glimmer';
import { compileExpression } from '@glimmer/runtime';

moduleFor('registerMacros', class extends RenderingTest {
  constructor() {
    let originalMacros = _experimentalMacros.slice();

    _registerMacros((blocks, inlines) => {
      blocks.add('-let', (params, hash, _default, inverse, builder) => {
        compileExpression(params[0], builder);
        builder.invokeStatic(_default, 1);
      });
    });

    super();
    this.originalMacros = originalMacros;
  }

  teardown() {
    _experimentalMacros.length = 0;
    this.originalMacros.forEach(macro => _experimentalMacros.push(macro));

    super.teardown();
  }

  ['@test allows registering custom syntax via private API'](assert) {
    this.render(strip`
      {{#-let obj as |bar|}}
        {{bar}}
      {{/-let}}
    `, { obj: 'hello world!'});

    this.assertText('hello world!');
  }
});
<|endoftext|>


<commit_before>import React, { useEffect, useState } from 'react'
import { useActions, useValues } from 'kea'

import { Button, Form, Input, Modal, Icon, Tag } from "antd"

import connectionsLogic from '../../logic'

function DatabaseForm ({ form: { getFieldDecorator, validateFieldsAndScroll, getFieldValue } }) {
  const { isAddOpen, isEditOpen, editingConnection, isSaving, didTest, isTesting, testPassed } = useValues(connectionsLogic)
  const { addConnection, editConnection, closeConnection, confirmRemoveConnection, testConnection } = useActions(connectionsLogic)

  const [wasEverOpen, setWasEverOpen] = useState(false)

  const handleAdd = (e) => {
    e.preventDefault()

    validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { keyword, url, structurePath, timeoutMs } = values

        if (isEditOpen) {
          editConnection(editingConnection._id, url, structurePath, timeoutMs)
        } else {
          addConnection({keyword, url, structurePath, timeoutMs})
        }
      }
    })
  }

  const runTest = () => {
    if (isEditOpen || isAddOpen) {
      setWasEverOpen(true)
      testConnection(getFieldValue('url'), getFieldValue('structurePath'))
    }
  }

  useEffect(runTest, [isEditOpen, isAddOpen])

  const initial = isEditOpen ? editingConnection : {}

  return (
    <Modal
      destroyOnClose
      visible={isAddOpen || isEditOpen}
      title={isAddOpen ? 'New Connection' : 'Edit Connection'}
      onCancel={closeConnection}
      canOutsideClickClose
      footer={[
        isEditOpen ? <Button key="delete" onClick={() => confirmRemoveConnection(editingConnection._id)} type='link' style={{ float: 'left' }}>
          <Icon type='delete' theme="filled" />
          Delete
        </Button> : null,
        <Button key="back" onClick={closeConnection}>
          Cancel
        </Button>,
        <Button key="submit" type="primary" loading={isSaving} onClick={handleAdd}>
          Save
        </Button>,
      ]}
    >
      {wasEverOpen ? <Form labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} onSubmit={handleAdd}>
        <Form.Item
          label='Keyword'
          extra="This will be used in URLs, dashboards, etc to refer to your database. You can't change this later!">
          {getFieldDecorator('keyword', {
            initialValue: initial.keyword || '',
            rules: [
              {
                required: true,
                message: 'Please input a keyword!',
              }
            ]
          })(<Input disabled={isEditOpen} autoFocus={isAddOpen} placeholder='mydb' style={{width: '100%'}} />)}
        </Form.Item>

        <Form.Item
          label='Connection'
          extra='Currently only URLs in the format "psql://user:pass@localhost/dbname" are supported.'>
          {getFieldDecorator('url', {
            initialValue: initial.url || '',
            rules: [
              {
                required: true,
                message: 'Please input a connection string!',
              },
              {
                pattern: /^psql:\/\//,
                message: 'Must be in the format "psql://user:pass@localhost/dbname"'
              }
            ]
          })(<Input placeholder='psql://user:pass@localhost/dbname' style={{width: '100%'}} onBlur={runTest} />)}
        </Form.Item>

        <Form.Item
          label='insights.yml'
          extra='Leave empty to autodetect the database structure'>
          {getFieldDecorator('structurePath', {
            initialValue: initial.structurePath || ''
          })(<Input placeholder='/Users/yourname/projects/code/insights.yml' style={{width: '100%'}} onBlur={runTest} />)}
        </Form.Item>

        <Form.Item
          label='Timeout'
          extra='Statement timeout in milliseconds'>
          {getFieldDecorator('timeoutMs', {
            initialValue: initial.timeoutMs || '',
            rules: [
              {
                type: 'number',
                message: 'Please input a number',
                transform: value => Number(value)
              }
            ]
          })(<Input placeholder='15000' style={{width: '100%'}} />)}
        </Form.Item>

        <Form.Item label='Test'>
          {!didTest
            ? <Tag>Enter URL to test</Tag>
            : isTesting
              ? <Tag color='blue'>Connecting...</Tag>
              : testPassed
                ? <Tag color='green'>Connection Established</Tag>
                : <Tag color='red'>Connection Failed</Tag>}

          {getFieldValue('url') ? <Button
            type='link'
            onClick={runTest}
            loading={isTesting}>{isTesting ? '' : testPassed ? 'Reconnect' : 'Retry'}</Button> : null}
        </Form.Item>
      </Form> : null}
    </Modal>
  )
}

export default Form.create({ name: 'database' })(DatabaseForm);
<commit_msg>limit allowed characters for keywords<commit_after>import React, { useEffect, useState } from 'react'
import { useActions, useValues } from 'kea'

import { Button, Form, Input, Modal, Icon, Tag } from "antd"

import connectionsLogic from '../../logic'

function DatabaseForm ({ form: { getFieldDecorator, validateFieldsAndScroll, getFieldValue } }) {
  const { isAddOpen, isEditOpen, editingConnection, isSaving, didTest, isTesting, testPassed } = useValues(connectionsLogic)
  const { addConnection, editConnection, closeConnection, confirmRemoveConnection, testConnection } = useActions(connectionsLogic)

  const [wasEverOpen, setWasEverOpen] = useState(false)

  const handleAdd = (e) => {
    e.preventDefault()

    validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { keyword, url, structurePath, timeoutMs } = values

        if (isEditOpen) {
          editConnection(editingConnection._id, url, structurePath, timeoutMs)
        } else {
          addConnection({keyword, url, structurePath, timeoutMs})
        }
      }
    })
  }

  const runTest = () => {
    if (isEditOpen || isAddOpen) {
      setWasEverOpen(true)
      testConnection(getFieldValue('url'), getFieldValue('structurePath'))
    }
  }

  useEffect(runTest, [isEditOpen, isAddOpen])

  const initial = isEditOpen ? editingConnection : {}

  return (
    <Modal
      destroyOnClose
      visible={isAddOpen || isEditOpen}
      title={isAddOpen ? 'New Connection' : 'Edit Connection'}
      onCancel={closeConnection}
      canOutsideClickClose
      footer={[
        isEditOpen ? <Button key="delete" onClick={() => confirmRemoveConnection(editingConnection._id)} type='link' style={{ float: 'left' }}>
          <Icon type='delete' theme="filled" />
          Delete
        </Button> : null,
        <Button key="back" onClick={closeConnection}>
          Cancel
        </Button>,
        <Button key="submit" type="primary" loading={isSaving} onClick={handleAdd}>
          Save
        </Button>,
      ]}
    >
      {wasEverOpen ? <Form labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} onSubmit={handleAdd}>
        <Form.Item
          label='Keyword'
          extra="This will be used in URLs, dashboards, etc to refer to your database. You can't change this later!">
          {getFieldDecorator('keyword', {
            initialValue: initial.keyword || '',
            rules: [
              {
                required: true,
                message: 'Please input a keyword!',
              },
              {
                pattern: /^[a-zA-Z0-9_\-]+$/,
                message: 'Allowed characters: A-Z, a-z, 0-9, _ and -'
              }
            ]
          })(<Input disabled={isEditOpen} autoFocus={isAddOpen} placeholder='mydb' style={{width: '100%'}} />)}
        </Form.Item>

        <Form.Item
          label='Connection'
          extra='Currently only URLs in the format "psql://user:pass@localhost/dbname" are supported.'>
          {getFieldDecorator('url', {
            initialValue: initial.url || '',
            rules: [
              {
                required: true,
                message: 'Please input a connection string!',
              },
              {
                pattern: /^psql:\/\//,
                message: 'Must be in the format "psql://user:pass@localhost/dbname"'
              }
            ]
          })(<Input placeholder='psql://user:pass@localhost/dbname' style={{width: '100%'}} onBlur={runTest} />)}
        </Form.Item>

        <Form.Item
          label='insights.yml'
          extra='Leave empty to autodetect the database structure'>
          {getFieldDecorator('structurePath', {
            initialValue: initial.structurePath || ''
          })(<Input placeholder='/Users/yourname/projects/code/insights.yml' style={{width: '100%'}} onBlur={runTest} />)}
        </Form.Item>

        <Form.Item
          label='Timeout'
          extra='Statement timeout in milliseconds'>
          {getFieldDecorator('timeoutMs', {
            initialValue: initial.timeoutMs || '',
            rules: [
              {
                type: 'number',
                message: 'Please input a number',
                transform: value => Number(value)
              }
            ]
          })(<Input placeholder='15000' style={{width: '100%'}} />)}
        </Form.Item>

        <Form.Item label='Test'>
          {!didTest
            ? <Tag>Enter URL to test</Tag>
            : isTesting
              ? <Tag color='blue'>Connecting...</Tag>
              : testPassed
                ? <Tag color='green'>Connection Established</Tag>
                : <Tag color='red'>Connection Failed</Tag>}

          {getFieldValue('url') ? <Button
            type='link'
            onClick={runTest}
            loading={isTesting}>{isTesting ? '' : testPassed ? 'Reconnect' : 'Retry'}</Button> : null}
        </Form.Item>
      </Form> : null}
    </Modal>
  )
}

export default Form.create({ name: 'database' })(DatabaseForm);
<|endoftext|>


<commit_before>// @flow

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { Dialog, DialogContent } from '../../base/dialog';
import { translate } from '../../base/i18n';

import { updateCalendarEvent } from '../actions';

type Props = {

    /**
     * The Redux dispatch function.
     */
    dispatch: Function,

    /**
     * The ID of the event to be updated.
     */
    eventId: string,

    /**
     * Function to translate i18n labels.
     */
    t: Function
};

/**
 * Component for the add Jitsi link confirm dialog.
 */
class UpdateCalendarEventDialog extends Component<Props> {
    /**
     * Initializes a new {@code UpdateCalendarEventDialog} instance.
     *
     * @inheritdoc
     */
    constructor(props: Props) {
        super(props);

        this._onSubmit = this._onSubmit.bind(this);
    }

    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        return (
            <Dialog
                okTitleKey = 'dialog.confirm'
                onSubmit = { this._onSubmit }
                titleKey = 'calendarSync.confirmAddLinkTitle'
                width = 'small'>
                <DialogContent>
                    { this.props.t('calendarSync.confirmAddLink') }
                </DialogContent>
            </Dialog>
        );
    }

    _onSubmit: () => boolean;

    /**
     * Callback for the confirm button.
     *
     * @private
     * @returns {boolean} - True (to note that the modal should be closed).
     */
    _onSubmit() {
        this.props.dispatch(updateCalendarEvent(this.props.eventId, ''));

        return true;
    }
}

export default translate(connect()(UpdateCalendarEventDialog));
<commit_msg>[RN] Make feature dialogs branded: calendar-sync<commit_after>// @flow

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { ConfirmDialog } from '../../base/dialog';
import { translate } from '../../base/i18n';

import { updateCalendarEvent } from '../actions';

type Props = {

    /**
     * The Redux dispatch function.
     */
    dispatch: Function,

    /**
     * The ID of the event to be updated.
     */
    eventId: string,

    /**
     * Function to translate i18n labels.
     */
    t: Function
};

/**
 * Component for the add Jitsi link confirm dialog.
 */
class UpdateCalendarEventDialog extends Component<Props> {
    /**
     * Initializes a new {@code UpdateCalendarEventDialog} instance.
     *
     * @inheritdoc
     */
    constructor(props: Props) {
        super(props);

        this._onSubmit = this._onSubmit.bind(this);
    }

    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        return (
            <ConfirmDialog
                contentKey = 'calendarSync.confirmAddLink'
                onSubmit = { this._onSubmit } />
        );
    }

    _onSubmit: () => boolean;

    /**
     * Callback for the confirm button.
     *
     * @private
     * @returns {boolean} - True (to note that the modal should be closed).
     */
    _onSubmit() {
        this.props.dispatch(updateCalendarEvent(this.props.eventId, ''));

        return true;
    }
}

export default translate(connect()(UpdateCalendarEventDialog));
<|endoftext|>


<commit_before>import angular from 'angular';
import template from './specific-topics.html';
import dialogTemplate from './specific-topics.dialog.html';

export const SpecificTopicsComponent = {
    bindings: {},
    controller: class SpecificTopicsComponent {
        constructor($scope, $mdDialog, SpecificTopicsService, GeneralTopicsService, ResponseHandler, Validator) {
            'ngInject';
            this.$scope = $scope;
            this.$mdDialog = $mdDialog;
            this.SpecificTopicsService = SpecificTopicsService;
            this.GeneralTopicsService = GeneralTopicsService;
            this.ResponseHandler = ResponseHandler;
            this.Validator = Validator;
        }

        /**
         * Gets all specific topics, general topics and the relationship between them. Then for each specific topic adds the related generalTopic
         */
        $onInit() {
            this.specificTopics = [];
            this.assignGeneralTopicIdIntoSpecificTopics(false);
        }

        /**
         * Get all specific topics
         */
        getSpecificTopics(forceRefresh) {
            return this.SpecificTopicsService.get(forceRefresh).then(specificTopics => this.specificTopics = specificTopics);
        }

        /**
         * Get all general topics
         */
        getGeneralTopics(forceRefresh) {
            return this.GeneralTopicsService.get(forceRefresh).then(generalTopics => this.generalTopics = generalTopics);
        }

        assignGeneralTopicIdIntoSpecificTopics(forceRefresh) {
            this.SpecificTopicsService.getRelatedGeneralTopics(forceRefresh).then(relations => {
                this.getSpecificTopics(forceRefresh).then(() => {
                    this.getGeneralTopics(forceRefresh).then(() => {
                        this.specificTopics.forEach(specificTopic => {
                            specificTopic.generalTopics = [];

                            const relationsToSpecificTopic = relations.filter(relation => relation.idSpecificTopic === specificTopic.id);

                            relationsToSpecificTopic.forEach(relationToSpecificTopic => {
                                specificTopic.generalTopics.push(this.generalTopics.find(generalTopic => generalTopic.id === relationToSpecificTopic.idGeneralTopic));
                            });
                        });
                    });
                });
            });
        }

        /**
         * Validate if a general topic is in a specific topic
         * @param {any} generalTopic
         * @param {any} specificTopic
         */
        isGeneralTopicInSpecificTopic(generalTopic, specificTopic) {
            return specificTopic.generalTopics.find(gt => gt.id === generalTopic.id);
        }

        /**
         * Add/remove a general topic in a specific topic
         * @param {any} generalTopic
         * @param {any} specificTopic
         */
        toggleGeneralTopicToSpecificTopic(generalTopic, specificTopic) {
            const isAlready = specificTopic.generalTopics.find(gt => gt.id === generalTopic.id);

            if (isAlready) {
                const index = specificTopic.generalTopics.map(gt => gt.id).indexOf(generalTopic.id);
                specificTopic.generalTopics.splice(index, 1);
            } else {
                specificTopic.generalTopics.push(generalTopic);
            }
        }

        /**
         * Add or update a specific topic
         * @param {any} specificTopic
         * @param {any} targetEvent
         * @param {string} method
         */
        addOrEdit(specificTopic = this.getNewSpecificTopic(), targetEvent, method) {
            this.isEditing = !!specificTopic.id;
            this.selectedSpecificTopic = angular.copy(specificTopic);

            this.$mdDialog
                .show({
                    preserveScope: true,
                    scope: this.$scope,
                    targetEvent,
                    template: dialogTemplate
                })
                .then(specificTopic => {
                    specificTopic.name = specificTopic.name.trim();
                    if (!this.Validator.isUnique(this.specificTopics, 'name', this.selectedSpecificTopic, this.isEditing, true, 'tema específico')) {
                        this.selectedSpecificTopic = null;
                        return;
                    }

                    if (!this.isEditing) {
                        delete specificTopic.id;
                        delete specificTopic.status;
                    }

                    this.SpecificTopicsService[method](specificTopic).then(response => {
                        this.ResponseHandler.success(response);
                        this.selectedSpecificTopic = this.getNewSpecificTopic();
                        this.assignGeneralTopicIdIntoSpecificTopics(true);
                    });
                })
                .catch(() => {
                    this.selectedSpecificTopic = this.getNewSpecificTopic();
                });
        }

        /**
         * Returns a new instance of a specificTopic
         * @return {any}
         */
        getNewSpecificTopic() {
            return { id: null, name: '', status: true, generalTopics: [] };
        }

        /**
         * Receives list of objects and return only that ones that have status true
         * @param {any} list
         */
        filterByActive(list) {
            return list.filter(item => item.status);
        }
    },
    template
};<commit_msg>fix Load catalogs in the right way<commit_after>import angular from 'angular';
import Promise from 'ypromise';
import template from './specific-topics.html';
import dialogTemplate from './specific-topics.dialog.html';

export const SpecificTopicsComponent = {
    bindings: {},
    controller: class SpecificTopicsComponent {
        constructor($scope, $mdDialog, SpecificTopicsService, GeneralTopicsService, ResponseHandler, Validator) {
            'ngInject';
            this.$scope = $scope;
            this.$mdDialog = $mdDialog;
            this.SpecificTopicsService = SpecificTopicsService;
            this.GeneralTopicsService = GeneralTopicsService;
            this.ResponseHandler = ResponseHandler;
            this.Validator = Validator;
        }

        /**
         * Gets all specific topics, general topics and the relationship between them. Then for each specific topic adds the related generalTopic
         */
        $onInit() {
            this.specificTopics = [];
            this.getCatalogs();
            this.assignGeneralTopicIdIntoSpecificTopics(false);
        }

        getCatalogs() {
            return Promise.all([this.getGeneralTopics(), this.getSpecificTopics()]);
        }

        /**
         * Get all specific topics
         */
        getSpecificTopics(forceRefresh) {
            return this.SpecificTopicsService.get(forceRefresh).then(specificTopics => this.specificTopics = specificTopics);
        }

        /**
         * Get all general topics
         */
        getGeneralTopics(forceRefresh) {
            return this.GeneralTopicsService.get(forceRefresh).then(generalTopics => this.generalTopics = generalTopics);
        }

        assignGeneralTopicIdIntoSpecificTopics(forceRefresh) {
            this.SpecificTopicsService.getRelatedGeneralTopics(forceRefresh).then(relations => {
                this.specificTopics.forEach(specificTopic => {
                    specificTopic.generalTopics = [];

                    const relationsToSpecificTopic = relations.filter(relation => relation.idSpecificTopic === specificTopic.id);

                    relationsToSpecificTopic.forEach(relationToSpecificTopic => {
                        specificTopic.generalTopics.push(this.generalTopics.find(generalTopic => generalTopic.id === relationToSpecificTopic.idGeneralTopic));
                    });
                });
            });
        }

        /**
         * Validate if a general topic is in a specific topic
         * @param {any} generalTopic
         * @param {any} specificTopic
         */
        isGeneralTopicInSpecificTopic(generalTopic, specificTopic) {
            return specificTopic.generalTopics.find(gt => gt.id === generalTopic.id);
        }

        /**
         * Add/remove a general topic in a specific topic
         * @param {any} generalTopic
         * @param {any} specificTopic
         */
        toggleGeneralTopicToSpecificTopic(generalTopic, specificTopic) {
            const isAlready = specificTopic.generalTopics.find(gt => gt.id === generalTopic.id);

            if (isAlready) {
                const index = specificTopic.generalTopics.map(gt => gt.id).indexOf(generalTopic.id);
                specificTopic.generalTopics.splice(index, 1);
            } else {
                specificTopic.generalTopics.push(generalTopic);
            }
        }

        /**
         * Add or update a specific topic
         * @param {any} specificTopic
         * @param {any} targetEvent
         * @param {string} method
         */
        addOrEdit(specificTopic = this.getNewSpecificTopic(), targetEvent, method) {
            this.isEditing = !!specificTopic.id;
            this.selectedSpecificTopic = angular.copy(specificTopic);

            this.$mdDialog
                .show({
                    preserveScope: true,
                    scope: this.$scope,
                    targetEvent,
                    template: dialogTemplate
                })
                .then(specificTopic => {
                    specificTopic.name = specificTopic.name.trim();
                    if (!this.Validator.isUnique(this.specificTopics, 'name', this.selectedSpecificTopic, this.isEditing, true, 'tema específico')) {
                        this.selectedSpecificTopic = null;
                        return;
                    }

                    if (!this.isEditing) {
                        delete specificTopic.id;
                        delete specificTopic.status;
                    }

                    this.SpecificTopicsService[method](specificTopic).then(response => {
                        this.ResponseHandler.success(response);
                        this.selectedSpecificTopic = this.getNewSpecificTopic();
                        this.getCatalogs();
                        this.assignGeneralTopicIdIntoSpecificTopics(true);
                    });
                })
                .catch(() => {
                    this.selectedSpecificTopic = this.getNewSpecificTopic();
                });
        }

        /**
         * Returns a new instance of a specificTopic
         * @return {any}
         */
        getNewSpecificTopic() {
            return { id: null, name: '', status: true, generalTopics: [] };
        }

        /**
         * Receives list of objects and return only that ones that have status true
         * @param {any} list
         */
        filterByActive(list) {
            return list.filter(item => item.status);
        }
    },
    template
};<|endoftext|>


<commit_before>app.controller('MainController', [
  '$scope',
  '$state',
  '$filter',
  '$sce',
  'CollegeFactory',
  'Filter',
  MainController]);

function MainController($scope, $state, $filter, $sce, CollegeFactory, Filter) {
  $scope.filter = Filter;
  $scope.filtered = [];
  $scope.sort = {
    priority: {},
    direction: false
  };
  $scope.counter = {
    'from': 0,
    'to': 0,
    'effect': 'swing',
    'duration': 2
  };
  $scope.colleges = [];
  $scope.priorities = [
    {
      "id": null,
      "name": null,
    }, {
      "id": "enrollment_count",
      "name": "Enrollment"
    }, {
      "id": "environment",
      "name": "Environment"
    }, {
      "id": "tuition",
      "name": "Tuition"
    }, {
      "id": "st_ratio",
      "name": "Classroom Ratio"
    }, {
      "id": "location",
      "name": "Location"
    }, {
      "id": "financial_aid_score",
      "name": "Financial Aid"
    }, {
      "id": "academic_intensity",
      "name": "Academic Intensity"
    }, {
      "id": "school_privacy",
      "name": "Private/Public"
    }
  ];

  // Load college data from external source
  CollegeFactory.getData(function(data) {
    $scope.colleges = data;
    angular.forEach($scope.colleges, function(college, key) {
      $scope.colleges[key].norm = {};
      // Convert integer-strings to integers in-place
      angular.forEach([
        'tuition', 'enrollment_count', 'financial_aid_score',
        'academic_intensity', 'school_privacy', 'st_ratio'
      ], function(cat) {
        $scope.colleges[this].acf[cat] = parseInt($scope.colleges[this].acf[cat]) || 0;
      }, key);

      // Normalize and isolate data
      // Normalize from string
      angular.forEach([
        'tuition', 'enrollment_count', 'financial_aid_score',
        'academic_intensity', 'st_ratio'
      ], function(cat) {
        $scope.colleges[this].norm[cat] = parseInt($scope.colleges[this].acf[cat]) || 0;
      }, key);
      // Normalize from object (value key)
      angular.forEach([
        'school_privacy', 'environment', 'selectivity'
      ], function(cat) {
        $scope.colleges[this].norm[cat] = $scope.render_acf_text(
          {'id': cat}, $scope.colleges[this].acf);
      }, key);
      // Normalize from "string array...ish"
      console.debug('college', $scope.colleges[key]);
      angular.forEach([
        'housing_types', 'housing_sub_types', 'food_services',
      ], function(cat) {
        $scope.colleges[this].norm[cat] = $scope.colleges[this].acf[cat].value.split('||');
        $scope.colleges[this].norm[cat] = $scope.render_acf_text(
          {'id': cat}, $scope.colleges[this].norm);
      }, key);
      $scope.colleges[key].norm.location = college.acf.school_city + ', ' + college.acf.school_state;

      console.debug('college', college);
      return;
    });
  });

  $scope.go = function(ref) {
    $state.go(ref);
  };

  $scope.resetFilters = function() {
    $scope.filter.priority = ["enrollment_count", "tuition", "location"];
    $scope.filter.filters = {};
  };

  $scope.$watch('filtered.length', function(nval, oval) {
    $scope.counter.from = oval;
    $scope.counter.to = nval;
  });

  // Load the sidebar
  $scope.getSidebar = function () {
	  return stylesheet_directory_uri + '/rowingdb/components/sidebar/sidebar.php';
	};

  // Set the table sort
  $scope.setSort = function(priority) {
    if( $scope.sort.priority === priority ) {
      $scope.sort.direction = !$scope.sort.direction;
    } else {
      $scope.sort.priority = priority;
      $scope.sort.direction = false;
    }
  };

  // Priorities options filter
  $scope.prioritiesFilter = function(current_idx) {
    return function(item) {
      var keep = true;
      var existing_priorities = [];
      // Get a list of all priorities defined
      angular.forEach($scope.filter.priority, function(priority, idx) {
        if( idx !== current_idx && priority && priority !== "" )
          existing_priorities.push(priority);
      });
      // If no priorities already defined, return
      if( !existing_priorities.length )
        return keep;
      // Check if this item already is defined elsewhere
      angular.forEach(existing_priorities, function(priority) {
        if( this.id === priority ) {
          keep = false;
          return;
        }
      }, item);
      return keep;
    };
  };

  // Filter of filters...
  $scope.masterFilter = function(college) {
    ret = true;
    angular.forEach($scope.filter.filters, function(spec, type_id) {
      if( spec && type_id ) {
        var type = $scope.filter.types_map[type_id];
        if( type && angular.isFunction(type.filter) ) {
          type.id = type_id;
          if( !type.filter(type, college, spec) ) {
            ret = false;
            return ret;
          }
        }
      }
    });
    return ret;
  };

  // Filter out colleges without well-formatted city/state parts
  $scope.hasLocationFilter = function(college) {
    if( !college.hasOwnProperty('acf') ||
        !college.acf.hasOwnProperty('school_city') ||
        !college.acf.hasOwnProperty('school_state') ||
        !angular.isString(college.acf.school_city) ||
        !angular.isString(college.acf.school_state) ||
        (college.acf.school_city.length === 0 ||
         !college.acf.school_city.trim()) ||
        (college.acf.school_state.length === 0 ||
         !college.acf.school_state.trim()))
      return false;
    return true;
  };

  // Find a priority by id
  $scope.get_priority_by_id = function(pid) {
    var prio = null;
    if( pid === null ) return prio;
    angular.forEach($scope.priorities, function(val) {
      if( pid === val.id ) {
        prio = val;
        return;
      }
    });
    return prio;
  };

  // Return ordered, existing priorities list
  $scope.get_priorities = function() {
    var prios = [];
    angular.forEach($scope.filter.priority, function(val) {
      if( val !== null && val !== "" ) {
        var prio = $scope.get_priority_by_id(val);
        if( prio !== null )
          prios.push(prio);
      }
    });
    return prios;
  };

  // Find a type's corresponding data
  function get_type_data(type) {
    var res = null;
    angular.forEach($scope.filter.types_map, function(val, key) {
      if( type === key ) {
        val.id = key;
        res = val;
        return;
      }
    });
    return res;
  }

  // Allow for HTML rendering / unescaping
  $scope.trustHtml = function(html) {
    return $sce.trustAsHtml(html);
  };

  // Render text intelligently
  $scope.render_acf_text = function(priority, acf) {
    if( !acf || acf[priority.id] === 'false' )
      return '';

    data = get_type_data(priority.id);
    if( data && angular.isFunction(data.render_text) )
      return $scope.filter.types_map[priority.id].render_text(acf, data);
    return acf[priority.id];
  };
}
<commit_msg>Generalizing iface<commit_after>app.controller('MainController', [
  '$scope',
  '$state',
  '$filter',
  '$sce',
  'CollegeFactory',
  'Filter',
  MainController]);

function MainController($scope, $state, $filter, $sce, CollegeFactory, Filter) {
  $scope.filter = Filter;
  $scope.filtered = [];
  $scope.sort = {
    priority: {},
    direction: false
  };
  $scope.counter = {
    'from': 0,
    'to': 0,
    'effect': 'swing',
    'duration': 2
  };
  $scope.colleges = [];
  $scope.priorities = [
    {
      "id": null,
      "name": null,
    }, {
      "id": "enrollment_count",
      "name": "Enrollment"
    }, {
      "id": "environment",
      "name": "Environment"
    }, {
      "id": "tuition",
      "name": "Tuition"
    }, {
      "id": "st_ratio",
      "name": "Classroom Ratio"
    }, {
      "id": "location",
      "name": "Location"
    }, {
      "id": "financial_aid_score",
      "name": "Financial Aid"
    }, {
      "id": "academic_intensity",
      "name": "Academic Intensity"
    }, {
      "id": "school_privacy",
      "name": "Private/Public"
    }
  ];

  // Load college data from external source
  CollegeFactory.getData(function(data) {
    $scope.colleges = data;
    angular.forEach($scope.colleges, function(college, key) {
      $scope.colleges[key].norm = {};
      // Convert integer-strings to integers in-place
      angular.forEach([
        'tuition', 'enrollment_count', 'financial_aid_score',
        'academic_intensity', 'school_privacy', 'st_ratio'
      ], function(cat) {
        $scope.colleges[this].acf[cat] = parseInt($scope.colleges[this].acf[cat]) || 0;
      }, key);

      // Normalize and isolate data
      // Normalize from string
      angular.forEach([
        'tuition', 'enrollment_count', 'financial_aid_score',
        'academic_intensity', 'st_ratio'
      ], function(cat) {
        $scope.colleges[this].norm[cat] = parseInt($scope.colleges[this].acf[cat]) || 0;
      }, key);
      // Normalize from object (value key)
      angular.forEach([
        'school_privacy', 'environment', 'selectivity'
      ], function(cat) {
        $scope.colleges[this].norm[cat] = $scope.colleges[this].acf[cat].label;
      }, key);
      // Normalize from "string array...ish"
      console.debug('college', $scope.colleges[key]);
      angular.forEach([
        'housing_types', 'housing_sub_types', 'food_services',
      ], function(cat) {
        $scope.colleges[this].norm[cat] = [];
        angular.forEach($scope.colleges[this].acf[cat], function(val) {
          $scope.colleges[this].norm[cat].push(val.label);
        }, this);
      }, key);
      $scope.colleges[key].norm.location = college.acf.school_city + ', ' + college.acf.school_state;

      console.debug('college', college);
      return;
    });
  });

  $scope.go = function(ref) {
    $state.go(ref);
  };

  $scope.resetFilters = function() {
    $scope.filter.priority = ["enrollment_count", "tuition", "location"];
    $scope.filter.filters = {};
  };

  $scope.$watch('filtered.length', function(nval, oval) {
    $scope.counter.from = oval;
    $scope.counter.to = nval;
  });

  // Load the sidebar
  $scope.getSidebar = function () {
	  return stylesheet_directory_uri + '/rowingdb/components/sidebar/sidebar.php';
	};

  // Set the table sort
  $scope.setSort = function(priority) {
    if( $scope.sort.priority === priority ) {
      $scope.sort.direction = !$scope.sort.direction;
    } else {
      $scope.sort.priority = priority;
      $scope.sort.direction = false;
    }
  };

  // Priorities options filter
  $scope.prioritiesFilter = function(current_idx) {
    return function(item) {
      var keep = true;
      var existing_priorities = [];
      // Get a list of all priorities defined
      angular.forEach($scope.filter.priority, function(priority, idx) {
        if( idx !== current_idx && priority && priority !== "" )
          existing_priorities.push(priority);
      });
      // If no priorities already defined, return
      if( !existing_priorities.length )
        return keep;
      // Check if this item already is defined elsewhere
      angular.forEach(existing_priorities, function(priority) {
        if( this.id === priority ) {
          keep = false;
          return;
        }
      }, item);
      return keep;
    };
  };

  // Filter of filters...
  $scope.masterFilter = function(college) {
    ret = true;
    angular.forEach($scope.filter.filters, function(spec, type_id) {
      if( spec && type_id ) {
        var type = $scope.filter.types_map[type_id];
        if( type && angular.isFunction(type.filter) ) {
          type.id = type_id;
          if( !type.filter(type, college, spec) ) {
            ret = false;
            return ret;
          }
        }
      }
    });
    return ret;
  };

  // Filter out colleges without well-formatted city/state parts
  $scope.hasLocationFilter = function(college) {
    if( !college.hasOwnProperty('acf') ||
        !college.acf.hasOwnProperty('school_city') ||
        !college.acf.hasOwnProperty('school_state') ||
        !angular.isString(college.acf.school_city) ||
        !angular.isString(college.acf.school_state) ||
        (college.acf.school_city.length === 0 ||
         !college.acf.school_city.trim()) ||
        (college.acf.school_state.length === 0 ||
         !college.acf.school_state.trim()))
      return false;
    return true;
  };

  // Find a priority by id
  $scope.get_priority_by_id = function(pid) {
    var prio = null;
    if( pid === null ) return prio;
    angular.forEach($scope.priorities, function(val) {
      if( pid === val.id ) {
        prio = val;
        return;
      }
    });
    return prio;
  };

  // Return ordered, existing priorities list
  $scope.get_priorities = function() {
    var prios = [];
    angular.forEach($scope.filter.priority, function(val) {
      if( val !== null && val !== "" ) {
        var prio = $scope.get_priority_by_id(val);
        if( prio !== null )
          prios.push(prio);
      }
    });
    return prios;
  };

  // Find a type's corresponding data
  function get_type_data(type) {
    var res = null;
    angular.forEach($scope.filter.types_map, function(val, key) {
      if( type === key ) {
        val.id = key;
        res = val;
        return;
      }
    });
    return res;
  }

  // Allow for HTML rendering / unescaping
  $scope.trustHtml = function(html) {
    return $sce.trustAsHtml(html);
  };

  // Render text intelligently
  $scope.render_acf_text = function(priority, acf) {
    if( !acf || acf[priority.id] === 'false' )
      return '';

    data = get_type_data(priority.id);
    if( data && angular.isFunction(data.render_text) )
      return $scope.filter.types_map[priority.id].render_text(acf, data);
    return acf[priority.id];
  };
}
<|endoftext|>


<commit_before>/**
 * Created by quasarchimaere on 29.11.2018.
 */
import { actionTypes } from "../actions/actions.js";
import Immutable from "immutable";
import { getIn } from "../utils.js";

const initialState = Immutable.fromJS({
  initialLoadFinished: false,
  processingCreate: false,
  logoutInProcess: false,
  loginInProcess: false,
  loginInProcessFor: undefined,
});

export default function(processState = initialState, action = {}) {
  switch (action.type) {
    case actionTypes.needs.whatsNew:
    case actionTypes.needs.whatsAround:
      return processState.set("processingPublish", true);

    case actionTypes.failedToGetLocation:
    case actionTypes.needs.createSuccessful:
      return processState.set("processingPublish", false);

    case actionTypes.account.logoutStarted:
      return processState.set("logoutInProcess", true);

    case actionTypes.account.logout:
      return processState.set("logoutInProcess", false);

    case actionTypes.account.loginStarted:
      return processState
        .set("loginInProcess", true)
        .set("loginInProcessFor", getIn(action, ["payload", "email"]));

    case actionTypes.account.login: {
      if (getIn(action, ["payload", "loginFinished"])) {
        return processState
          .set("loginInProcess", false)
          .set("loginInProcessFor", undefined);
      }
      return processState;
    }

    case actionTypes.account.loginFailed:
      return processState
        .set("loginInProcess", false)
        .set("loginInProcessFor", undefined);

    case actionTypes.initialPageLoad: {
      if (processState.get("initialLoadFinished")) {
        return processState;
      } else {
        const initialLoadFinished = getIn(action, [
          "payload",
          "initialLoadFinished",
        ]);
        return processState.set("initialLoadFinished", initialLoadFinished);
      }
    }

    default:
      return processState;
  }
}
<commit_msg>Rename createWhatsX to processingPublish (so we can use it for all other pendingPublishes as well and drop the component var)<commit_after>/**
 * Created by quasarchimaere on 29.11.2018.
 */
import { actionTypes } from "../actions/actions.js";
import Immutable from "immutable";
import { getIn } from "../utils.js";

const initialState = Immutable.fromJS({
  initialLoadFinished: false,
  processingPublish: false,
  logoutInProcess: false,
  loginInProcess: false,
  loginInProcessFor: undefined,
});

export default function(processState = initialState, action = {}) {
  switch (action.type) {
    case actionTypes.needs.whatsNew:
    case actionTypes.needs.whatsAround:
      return processState.set("processingPublish", true);

    case actionTypes.failedToGetLocation:
    case actionTypes.needs.createSuccessful:
      return processState.set("processingPublish", false);

    case actionTypes.account.logoutStarted:
      return processState.set("logoutInProcess", true);

    case actionTypes.account.logout:
      return processState.set("logoutInProcess", false);

    case actionTypes.account.loginStarted:
      return processState
        .set("loginInProcess", true)
        .set("loginInProcessFor", getIn(action, ["payload", "email"]));

    case actionTypes.account.login: {
      if (getIn(action, ["payload", "loginFinished"])) {
        return processState
          .set("loginInProcess", false)
          .set("loginInProcessFor", undefined);
      }
      return processState;
    }

    case actionTypes.account.loginFailed:
      return processState
        .set("loginInProcess", false)
        .set("loginInProcessFor", undefined);

    case actionTypes.initialPageLoad: {
      if (processState.get("initialLoadFinished")) {
        return processState;
      } else {
        const initialLoadFinished = getIn(action, [
          "payload",
          "initialLoadFinished",
        ]);
        return processState.set("initialLoadFinished", initialLoadFinished);
      }
    }

    default:
      return processState;
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

define([
    'underscore',
    'knockback',
    'contrail-view',
    'contrail-list-model',
    'monitor/infrastructure/vrouter/ui/js/models/VRouterRoutesFormModel'
    //Remove all query references once it is moved to core
], function (_, Knockback, ContrailView, ContrailListModel, VRouterRoutesFormModel) {

    var VRouterRoutesFormView = ContrailView.extend({
        render: function (options) {
            var self = this, viewConfig = self.attributes.viewConfig,
                hostname = viewConfig['hostname'],
                prefix = ctwl.VROUTER_ROUTES_PREFIX;
                routesTmpl = contrail.getTemplate4Id(
                            ctwc.TMPL_FORM_RESULT),
                vRouterRoutesFormModel = new VRouterRoutesFormModel(),
                widgetConfig = contrail.checkIfExist(viewConfig.widgetConfig) ?
                        viewConfig.widgetConfig : null,
                routesFormId = "#" + prefix + "-form";

            self.model = vRouterRoutesFormModel;
            self.$el.append(routesTmpl({prefix: prefix}));

            self.renderView4Config($(self.$el).find(routesFormId),
                    this.model,
                    self.getViewConfig(options,viewConfig),
                    null,
                    null,
                    null,
                    function () {
                        self.model.showErrorAttr(prefix + '-container',
                                false);
                        Knockback.applyBindings(self.model,
                                document.getElementById(prefix + '-container'));
                        kbValidation.bind(self);
                        // self.renderQueryResult(viewConfig);
                        $("#vrouter_routes_radio").on('change', function() {
                            self.renderQueryResult(viewConfig);
                        });
                    }
            );

            if (widgetConfig !== null) {
                self.renderView4Config($(self.$el).find(routesFormId),
                        self.model, widgetConfig, null, null, null);
            }
        },

        renderQueryResult: function(viewConfig) {
            var self = this,
                prefix = ctwl.VROUTER_ROUTES_PREFIX;
                hostname = viewConfig['hostname'],
                introspectPort = viewConfig['introspectPort'];
                queryResultId = "#" + prefix + "-results",

                responseViewConfig = {
                    elementId: ctwl.VROUTER_ROUTES_RESULTS_VIEW,
                    view: "VRouterRoutesGridView",
                    viewPathPrefix: ctwl.VROUTER_VIEWPATH_PREFIX,
                    app: cowc.APP_CONTRAIL_CONTROLLER,
                    viewConfig: $.extend({},viewConfig,{
                            route_type : self.model.route_type()
                        })
                };

            var queryParams = self.model.getQueryParams();

            function getIndexForType(selectedVRF,type) {
                var parts = selectedVRF.split('&&');
                var index = '';
                $.each(parts,function(i,d){
                    if(d.indexOf(type) != -1){
                        index = d.split('=')[1];
                    }
                });
                return index;
            }

            function constructvRouterUnicastRouteURL(initialSelection) {
                var selectedVrf = self.model.vrf_name();
                var ucIndex = getIndexForType(selectedVrf,'ucast');
                var urlParams = {
                    ip : monitorInfraUtils.getIPOrHostName(viewConfig),
                    introspectPort : introspectPort,
                    vrfindex: ucIndex
                }
                return {
                    url: monitorInfraConstants.monitorInfraUrls['VROUTER_UNICAST_ROUTES'],
                    params:urlParams
                }
            }

            function constructvRouterL2RouteURL() {
                var selectedVrf = self.model.vrf_name();
                var l2index = getIndexForType(selectedVrf,'l2');
                var urlParams = {
                    ip : monitorInfraUtils.getIPOrHostName(viewConfig),
                    introspectPort : introspectPort,
                    vrfindex: l2index
                }
                return {
                    url: monitorInfraConstants.monitorInfraUrls['VROUTER_L2_ROUTES'],
                    params:urlParams
                }
            }

            function constructvRouterMulticastURL() {
                var selectedVrf = self.model.vrf_name();
                var mcIndex = getIndexForType(selectedVrf,'mcast');
                var urlParams = {
                    ip : monitorInfraUtils.getIPOrHostName(viewConfig),
                    introspectPort : introspectPort,
                    vrfindex: mcIndex
                }
                return {
                    url: monitorInfraConstants.monitorInfraUrls['VROUTER_MCAST_ROUTES'],
                    params:urlParams
                }
            }

            function constructvRouterUnicast6RouteURL(initialSelection) {
                var selectedVrf = self.model.vrf_name();
                var ucIndex = getIndexForType(selectedVrf,'ucast6');
                var urlParams = {
                    ip : monitorInfraUtils.getIPOrHostName(viewConfig),
                    introspectPort : introspectPort,
                    vrfindex: ucIndex
                }
                return {
                    url: monitorInfraConstants.monitorInfraUrls['VROUTER_UCAST6_ROUTES'],
                    params:urlParams
                }
            }
            var constructURLMap = {
                l2: constructvRouterL2RouteURL,
                ucast: constructvRouterUnicastRouteURL,
                mcast: constructvRouterMulticastURL,
                ucast6: constructvRouterUnicast6RouteURL
            };
            var urlObj  = constructURLMap[self.model.route_type()](viewConfig);
            var paginationInfo;
            function getPaginationInfo() {
                return paginationInfo;
            }
            var remoteConfig = {
                    url: urlObj['url'] + '?' + $.param(urlObj['params']),
                    type: 'GET'
                };
            var routeParseMap = {
                'ucast' : monitorInfraParsers.parseVRouterUnicastRoutesData,
                'mcast' : monitorInfraParsers.parseVRouterMulticastRoutesData,
                'ucast6' : monitorInfraParsers.parseVRouterIPv6RoutesData,
                'l2'    : monitorInfraParsers.parseVRouterL2RoutesData
            };

            var listModelConfig = {
                    remote : {
                        ajaxConfig : remoteConfig,
                        dataParser :  function(response) {
                            var routeType = self.model.route_type();
                            var retData = routeParseMap[routeType](response);
                            paginationInfo = retData['paginationInfo'];
                            monitorInfraUtils.updateGridTitleWithPagingInfo(
                                $('#' + ctwl.VROUTER_ROUTES_GRID_ID),paginationInfo);
                            return retData['data'];
                        }
                    },
                    cacheConfig : {
                       // ucid: ctwc.CACHE_CONFIGNODE
                    }
                };
            var model = new ContrailListModel(listModelConfig);

            self.renderView4Config($(self.$el).find(queryResultId),
                    model, responseViewConfig,null,null,null,function() {
                        monitorInfraUtils.bindGridPrevNextListeners({
                            gridSel: $('#' + ctwl.VROUTER_ROUTES_GRID_ID),
                            model: self.model,
                            resetForm : function() {
                                    self.model.reset();
                                },
                            obj:viewConfig,
                            getUrlFn: function() {
                                return constructURLMap[self.model.route_type()](viewConfig)
                            },
                            paginationInfoFn: getPaginationInfo
                        });
                    });
        },

        getViewConfig: function (options,viewConfig) {
            var self = this;
            var hostname = viewConfig['hostname'];
            return {
                view: "SectionView",
                viewConfig: {
                    rows: [
                        {
                            columns: [
                                {
                                    elementId: 'vrf_name',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        label: 'VRF',
                                        path: 'vrf_name',
                                        dataBindValue:'vrf_name',
                                        elementConfig: {
                                            defaultValueId: 0,
                                            dataSource: {
                                                type:'remote',
                                                url: contrail.format(
                                                    monitorInfraConstants.monitorInfraUrls['VROUTER_VRF_LIST'],
                                                    monitorInfraUtils.getIPOrHostName(viewConfig),viewConfig['introspectPort']),
                                                async: true,
                                                dataType: 'xml',
                                               // dataTextField:'text',
                                               // dataValueField:'value',
                                                parse: function(response) {
                                                    if(response != null) {
                                                        var ret = [];
                                                        var vrfs = response.getElementsByTagName('VrfSandeshData');
                                                        $.each(vrfs,function(idx,vrfXmlObj){
                                                            var name = getValueByJsonPath(vrfXmlObj.getElementsByTagName('name'),'0;innerHTML','');
                                                            var ucIndex = getValueByJsonPath(vrfXmlObj.getElementsByTagName('ucindex'),'0;innerHTML','');
                                                            var mcIndex = getValueByJsonPath(vrfXmlObj.getElementsByTagName('mcindex'),'0;innerHTML','');
                                                            var l2Index = getValueByJsonPath(vrfXmlObj.getElementsByTagName('l2index'),'0;innerHTML','');
                                                            var uc6Index = getValueByJsonPath(vrfXmlObj.getElementsByTagName('uc6index'),'0;innerHTML','');
                                                            var value = "ucast=" + ucIndex + "&&mcast=" + mcIndex + "&&l2=" + l2Index + "&&ucast6=" + uc6Index;
                                                            ret.push({text:name,id:value});
                                                        });
                                                        //Set the firstValue in model
                                                        if(ret.length > 0) {
                                                            self.model.vrf_name(ret[0]['id']);
                                                        }
                                                        self.renderQueryResult(viewConfig);
                                                        return ret;
                                                    }
                                                }
                                            }
                                        },
                                        class: "span6"
                                    }
                                },{
                                    elementId: 'vrouter_routes_radio',
                                    view: "FormRadioButtonView",
                                    viewConfig: {
                                        class: 'span6',
                                        path:'route_type',
                                        dataBindValue:'route_type',
                                        elementConfig: {
                                            dataObj: [
                                            {'label': 'Unicast',
                                             'value': 'ucast'},
                                            {'label': 'Multicast',
                                             'value': 'mcast'},
                                            {'label': 'L2',
                                             'value': 'l2'},
                                            {'label': 'Unicast 6',
                                             'value': 'ucast6'}
                                        ],
                                            btnClass: 'btn-primary'
                                        }
                                    }
                                }],
                        }
                    ]
                }
            };
        }
    });
    return VRouterRoutesFormView;
});
<commit_msg>Closes-Bug: #1510674 - Replaced the usage of innerHTML which was causing issues in Safari browser. Added a change event to the vrf dropddown to refresh the grid.<commit_after>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

define([
    'underscore',
    'knockback',
    'contrail-view',
    'contrail-list-model',
    'monitor/infrastructure/vrouter/ui/js/models/VRouterRoutesFormModel'
    //Remove all query references once it is moved to core
], function (_, Knockback, ContrailView, ContrailListModel, VRouterRoutesFormModel) {

    var VRouterRoutesFormView = ContrailView.extend({
        render: function (options) {
            var self = this, viewConfig = self.attributes.viewConfig,
                hostname = viewConfig['hostname'],
                prefix = ctwl.VROUTER_ROUTES_PREFIX;
                routesTmpl = contrail.getTemplate4Id(
                            ctwc.TMPL_FORM_RESULT),
                vRouterRoutesFormModel = new VRouterRoutesFormModel(),
                widgetConfig = contrail.checkIfExist(viewConfig.widgetConfig) ?
                        viewConfig.widgetConfig : null,
                routesFormId = "#" + prefix + "-form";

            self.model = vRouterRoutesFormModel;
            self.$el.append(routesTmpl({prefix: prefix}));

            self.renderView4Config($(self.$el).find(routesFormId),
                    this.model,
                    self.getViewConfig(options,viewConfig),
                    null,
                    null,
                    null,
                    function () {
                        self.model.showErrorAttr(prefix + '-container',
                                false);
                        Knockback.applyBindings(self.model,
                                document.getElementById(prefix + '-container'));
                        kbValidation.bind(self);
                        // self.renderQueryResult(viewConfig);
                        $("#vrouter_routes_radio").on('change', function() {
                            self.renderQueryResult(viewConfig);
                        });
                        $("#vrf_name").on('change', function() {
                            self.renderQueryResult(viewConfig);
                        });
                    }
            );

            if (widgetConfig !== null) {
                self.renderView4Config($(self.$el).find(routesFormId),
                        self.model, widgetConfig, null, null, null);
            }
        },

        renderQueryResult: function(viewConfig) {
            var self = this,
                prefix = ctwl.VROUTER_ROUTES_PREFIX;
                hostname = viewConfig['hostname'],
                introspectPort = viewConfig['introspectPort'];
                queryResultId = "#" + prefix + "-results",

                responseViewConfig = {
                    elementId: ctwl.VROUTER_ROUTES_RESULTS_VIEW,
                    view: "VRouterRoutesGridView",
                    viewPathPrefix: ctwl.VROUTER_VIEWPATH_PREFIX,
                    app: cowc.APP_CONTRAIL_CONTROLLER,
                    viewConfig: $.extend({},viewConfig,{
                            route_type : self.model.route_type()
                        })
                };

            var queryParams = self.model.getQueryParams();

            function getIndexForType(selectedVRF,type) {
                var parts = selectedVRF.split('&&');
                var index = '';
                $.each(parts,function(i,d){
                    if(d.indexOf(type) != -1){
                        index = d.split('=')[1];
                    }
                });
                return index;
            }

            function constructvRouterUnicastRouteURL(initialSelection) {
                var selectedVrf = self.model.vrf_name();
                var ucIndex = getIndexForType(selectedVrf,'ucast');
                var urlParams = {
                    ip : monitorInfraUtils.getIPOrHostName(viewConfig),
                    introspectPort : introspectPort,
                    vrfindex: ucIndex
                }
                return {
                    url: monitorInfraConstants.monitorInfraUrls['VROUTER_UNICAST_ROUTES'],
                    params:urlParams
                }
            }

            function constructvRouterL2RouteURL() {
                var selectedVrf = self.model.vrf_name();
                var l2index = getIndexForType(selectedVrf,'l2');
                var urlParams = {
                    ip : monitorInfraUtils.getIPOrHostName(viewConfig),
                    introspectPort : introspectPort,
                    vrfindex: l2index
                }
                return {
                    url: monitorInfraConstants.monitorInfraUrls['VROUTER_L2_ROUTES'],
                    params:urlParams
                }
            }

            function constructvRouterMulticastURL() {
                var selectedVrf = self.model.vrf_name();
                var mcIndex = getIndexForType(selectedVrf,'mcast');
                var urlParams = {
                    ip : monitorInfraUtils.getIPOrHostName(viewConfig),
                    introspectPort : introspectPort,
                    vrfindex: mcIndex
                }
                return {
                    url: monitorInfraConstants.monitorInfraUrls['VROUTER_MCAST_ROUTES'],
                    params:urlParams
                }
            }

            function constructvRouterUnicast6RouteURL(initialSelection) {
                var selectedVrf = self.model.vrf_name();
                var ucIndex = getIndexForType(selectedVrf,'ucast6');
                var urlParams = {
                    ip : monitorInfraUtils.getIPOrHostName(viewConfig),
                    introspectPort : introspectPort,
                    vrfindex: ucIndex
                }
                return {
                    url: monitorInfraConstants.monitorInfraUrls['VROUTER_UCAST6_ROUTES'],
                    params:urlParams
                }
            }
            var constructURLMap = {
                l2: constructvRouterL2RouteURL,
                ucast: constructvRouterUnicastRouteURL,
                mcast: constructvRouterMulticastURL,
                ucast6: constructvRouterUnicast6RouteURL
            };
            var urlObj  = constructURLMap[self.model.route_type()](viewConfig);
            var paginationInfo;
            function getPaginationInfo() {
                return paginationInfo;
            }
            var remoteConfig = {
                    url: urlObj['url'] + '?' + $.param(urlObj['params']),
                    type: 'GET'
                };
            var routeParseMap = {
                'ucast' : monitorInfraParsers.parseVRouterUnicastRoutesData,
                'mcast' : monitorInfraParsers.parseVRouterMulticastRoutesData,
                'ucast6' : monitorInfraParsers.parseVRouterIPv6RoutesData,
                'l2'    : monitorInfraParsers.parseVRouterL2RoutesData
            };

            var listModelConfig = {
                    remote : {
                        ajaxConfig : remoteConfig,
                        dataParser :  function(response) {
                            var routeType = self.model.route_type();
                            var retData = routeParseMap[routeType](response);
                            paginationInfo = retData['paginationInfo'];
                            monitorInfraUtils.updateGridTitleWithPagingInfo(
                                $('#' + ctwl.VROUTER_ROUTES_GRID_ID),paginationInfo);
                            return retData['data'];
                        }
                    },
                    cacheConfig : {
                       // ucid: ctwc.CACHE_CONFIGNODE
                    }
                };
            var model = new ContrailListModel(listModelConfig);

            self.renderView4Config($(self.$el).find(queryResultId),
                    model, responseViewConfig,null,null,null,function() {
                        monitorInfraUtils.bindGridPrevNextListeners({
                            gridSel: $('#' + ctwl.VROUTER_ROUTES_GRID_ID),
                            model: self.model,
                            resetForm : function() {
                                    self.model.reset();
                                },
                            obj:viewConfig,
                            getUrlFn: function() {
                                return constructURLMap[self.model.route_type()](viewConfig)
                            },
                            paginationInfoFn: getPaginationInfo
                        });
                    });
        },

        getViewConfig: function (options,viewConfig) {
            var self = this;
            var hostname = viewConfig['hostname'];
            return {
                view: "SectionView",
                viewConfig: {
                    rows: [
                        {
                            columns: [
                                {
                                    elementId: 'vrf_name',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        label: 'VRF',
                                        path: 'vrf_name',
                                        dataBindValue:'vrf_name',
                                        elementConfig: {
                                            defaultValueId: 0,
                                            dataSource: {
                                                type:'remote',
                                                url: contrail.format(
                                                    monitorInfraConstants.monitorInfraUrls['VROUTER_VRF_LIST'],
                                                    monitorInfraUtils.getIPOrHostName(viewConfig),viewConfig['introspectPort']),
                                                async: true,
                                                dataType: 'xml',
                                               // dataTextField:'text',
                                               // dataValueField:'value',
                                                parse: function(response) {
                                                    if(response != null) {
                                                        var ret = [];
                                                        var vrfs = response.getElementsByTagName('VrfSandeshData');
                                                        $.each(vrfs,function(idx,vrfXmlObj){
                                                            var name = $(vrfXmlObj.getElementsByTagName('name')[0]).text();
                                                            var ucIndex = $(vrfXmlObj.getElementsByTagName('ucindex')[0]).text();
                                                            var mcIndex = $(vrfXmlObj.getElementsByTagName('mcindex')[0]).text();
                                                            var l2Index = $(vrfXmlObj.getElementsByTagName('l2index')[0]).text();
                                                            var uc6Index = $(vrfXmlObj.getElementsByTagName('uc6index')[0]).text();
                                                            var value = "ucast=" + ucIndex + "&&mcast=" + mcIndex + "&&l2=" + l2Index + "&&ucast6=" + uc6Index;
                                                            ret.push({text:name,id:value});
                                                        });
                                                        //Set the firstValue in model
                                                        if(ret.length > 0) {
                                                            self.model.vrf_name(ret[0]['id']);
                                                        }
                                                        self.renderQueryResult(viewConfig);
                                                        return ret;
                                                    }
                                                }
                                            }
                                        },
                                        class: "span6"
                                    }
                                },{
                                    elementId: 'vrouter_routes_radio',
                                    view: "FormRadioButtonView",
                                    viewConfig: {
                                        class: 'span6',
                                        path:'route_type',
                                        dataBindValue:'route_type',
                                        elementConfig: {
                                            dataObj: [
                                            {'label': 'Unicast',
                                             'value': 'ucast'},
                                            {'label': 'Multicast',
                                             'value': 'mcast'},
                                            {'label': 'L2',
                                             'value': 'l2'},
                                            {'label': 'Unicast 6',
                                             'value': 'ucast6'}
                                        ],
                                            btnClass: 'btn-primary'
                                        }
                                    }
                                }],
                        }
                    ]
                }
            };
        }
    });
    return VRouterRoutesFormView;
});
<|endoftext|>


<commit_before><commit_msg>Update<commit_after><|endoftext|>


<commit_before>const WebSocket = require('ws');

const wss = new WebSocket.Server({
  perMessageDeflate: false,
  port: 8080
});

wss.on('connection', (ws) => {

  // Receive message from client
  ws.on('message', (message) => {
    console.log('Received: %s', message);
  });

  // Send message to client
  ws.send('The message from server.');
});<commit_msg>Add message output from console.log.<commit_after>const WebSocket = require('ws');

const wss = new WebSocket.Server({
  perMessageDeflate: false,
  port: 8080
});

wss.on('connection', (ws) => {
  console.log('WebSocket connection has been established.')
  // Receive message from client
  ws.on('message', (message) => {
    console.log('Received: %s', message);
  });

  // Send message to client
  ws.send('The message from server.');
});<|endoftext|>