<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.0.0');
		this.setClientTag('node:20-05-09');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.0.0');
		this.setClientTag('node:20-05-10');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


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

/* global __dirname */

const path                = require('path');
const process             = require('process');
const os                  = require('os');
const jasmineSeedReporter = require('karma-jasmine-seed-reporter');
const childProcess        = require('child_process');

let browsers;

if (process.platform === 'darwin') {
  browsers = ['Firefox', 'Chrome', 'Safari'];
} else if (process.platform === 'win32') {

  // make sure to kill Edge browser before doing anything.
  childProcess.spawnSync('taskkill', ['/F', '/IM', 'MicrosoftEdge.exe', '/T']);

  // Clear Edge history so that it doesn't re-open tabs after getting killed
  childProcess.spawnSync('Remove-Item', ["C:\\Users\\" +  os.userInfo().username + "\\AppData\\Local\\Packages\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\AC\\*", '-Force', '-Recurse']);

  browsers = ['Edge'];
} else {
  // linux, bsd, et.al.
  browsers = ['Firefox'];
}

module.exports = function (config) {
  config.set({
    basePath:      path.join(__dirname, 'public', 'assets', 'webpack'),
    frameworks:    ['jasmine'],
    client:        {
      captureConsole: true,
      jasmine:        {
        random: true,
        seed:   process.env['JASMINE_SEED']
      }
    },
    plugins:        [jasmineSeedReporter, "karma-*"],
    preprocessors:  {
      '**/*.js': ['sourcemap']
    },
    files:          [
      {
        pattern:  'vendor-and-helpers.chunk.js',
        watched:  true,
        included: true,
        served:   true
      },
      {
        pattern:  'specRoot.js',
        watched:  true,
        included: true,
        served:   true
      },
    ],
    reporters:      ['progress', 'junit', 'kjhtml', 'html', 'jasmine-seed'],
    htmlReporter:   {
      outputDir:               path.join(__dirname, '..', '..', '..', 'target', 'karma_reports'),
      templatePath:            null,
      focusOnFailures:         true,
      namedFiles:              false,
      pageTitle:               null,
      urlFriendlyName:         false,
      preserveDescribeNesting: false,
      foldAll:                 false,
    },
    junitReporter:  {
      outputDir:          path.join(__dirname, '..', '..', '..', 'target', 'karma_reports'),
      outputFile:         undefined,
      suite:              '',
      useBrowserName:     true,
      nameFormatter:      undefined,
      classNameFormatter: undefined,
      properties:         {}
    },
    port:          9876,
    colors:        true,
    logLevel:      process.env['KARMA_LOG_LEVEL'] ? config[`LOG_${process.env['KARMA_LOG_LEVEL'].toUpperCase()}`] : config.LOG_INFO,
    autoWatch:     true,
    browsers,
    singleRun:     false,
    concurrency:   Infinity
  });
};
<commit_msg>Use powershell to delete edge browser history (#5625)<commit_after>/*
 * Copyright 2017 ThoughtWorks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global __dirname */

const path                = require('path');
const process             = require('process');
const os                  = require('os');
const jasmineSeedReporter = require('karma-jasmine-seed-reporter');
const childProcess        = require('child_process');

let browsers;

if (process.platform === 'darwin') {
  browsers = ['Firefox', 'Chrome', 'Safari'];
} else if (process.platform === 'win32') {

  // make sure to kill Edge browser before doing anything.
  childProcess.spawnSync('taskkill', ['/F', '/IM', 'MicrosoftEdge.exe', '/T']);

  // Clear Edge history so that it doesn't re-open tabs after getting killed
  childProcess.spawnSync('powershell', ['-Command', "Remove-Item $env:USERPROFILE/AppData/Local/Packages/Microsoft.MicrosoftEdge_8wekyb3d8bbwe/AC/* -Force -Recurse"]);

  browsers = ['Edge'];
} else {
  // linux, bsd, et.al.
  browsers = ['Firefox'];
}

module.exports = function (config) {
  config.set({
    basePath:      path.join(__dirname, 'public', 'assets', 'webpack'),
    frameworks:    ['jasmine'],
    client:        {
      captureConsole: true,
      jasmine:        {
        random: true,
        seed:   process.env['JASMINE_SEED']
      }
    },
    plugins:        [jasmineSeedReporter, "karma-*"],
    preprocessors:  {
      '**/*.js': ['sourcemap']
    },
    files:          [
      {
        pattern:  'vendor-and-helpers.chunk.js',
        watched:  true,
        included: true,
        served:   true
      },
      {
        pattern:  'specRoot.js',
        watched:  true,
        included: true,
        served:   true
      },
    ],
    reporters:      ['progress', 'junit', 'kjhtml', 'html', 'jasmine-seed'],
    htmlReporter:   {
      outputDir:               path.join(__dirname, '..', '..', '..', 'target', 'karma_reports'),
      templatePath:            null,
      focusOnFailures:         true,
      namedFiles:              false,
      pageTitle:               null,
      urlFriendlyName:         false,
      preserveDescribeNesting: false,
      foldAll:                 false,
    },
    junitReporter:  {
      outputDir:          path.join(__dirname, '..', '..', '..', 'target', 'karma_reports'),
      outputFile:         undefined,
      suite:              '',
      useBrowserName:     true,
      nameFormatter:      undefined,
      classNameFormatter: undefined,
      properties:         {}
    },
    port:          9876,
    colors:        true,
    logLevel:      process.env['KARMA_LOG_LEVEL'] ? config[`LOG_${process.env['KARMA_LOG_LEVEL'].toUpperCase()}`] : config.LOG_INFO,
    autoWatch:     true,
    browsers,
    singleRun:     false,
    concurrency:   Infinity
  });
};
<|endoftext|>


<commit_before>/**
@module ember
@submodule ember-runtime
*/

// ..........................................................
// HELPERS
//
import Ember from 'ember-metal/core'; // ES6TODO: Ember.A

import { get } from 'ember-metal/property_get';
import {
  computed,
  cacheFor
} from 'ember-metal/computed';
import isNone from 'ember-metal/is_none';
import Enumerable from 'ember-runtime/mixins/enumerable';
import { map } from 'ember-metal/enumerable_utils';
import {
  Mixin,
  required
} from 'ember-metal/mixin';
import {
  propertyWillChange,
  propertyDidChange
} from 'ember-metal/property_events';
import {
  addListener,
  removeListener,
  sendEvent,
  hasListeners
} from 'ember-metal/events';
import { isWatching } from 'ember-metal/watching';

function arrayObserversHelper(obj, target, opts, operation, notify) {
  var willChange = (opts && opts.willChange) || 'arrayWillChange';
  var didChange  = (opts && opts.didChange) || 'arrayDidChange';
  var hasObservers = get(obj, 'hasArrayObservers');

  if (hasObservers === notify) {
    propertyWillChange(obj, 'hasArrayObservers');
  }

  operation(obj, '@array:before', target, willChange);
  operation(obj, '@array:change', target, didChange);

  if (hasObservers === notify) {
    propertyDidChange(obj, 'hasArrayObservers');
  }

  return obj;
}

// ..........................................................
// ARRAY
//
/**
  This mixin implements Observer-friendly Array-like behavior. It is not a
  concrete implementation, but it can be used up by other classes that want
  to appear like arrays.

  For example, ArrayProxy and ArrayController are both concrete classes that can
  be instantiated to implement array-like behavior. Both of these classes use
  the Array Mixin by way of the MutableArray mixin, which allows observable
  changes to be made to the underlying array.

  Unlike `Ember.Enumerable,` this mixin defines methods specifically for
  collections that provide index-ordered access to their contents. When you
  are designing code that needs to accept any kind of Array-like object, you
  should use these methods instead of Array primitives because these will
  properly notify observers of changes to the array.

  Although these methods are efficient, they do add a layer of indirection to
  your application so it is a good idea to use them only when you need the
  flexibility of using both true JavaScript arrays and "virtual" arrays such
  as controllers and collections.

  You can use the methods defined in this module to access and modify array
  contents in a KVO-friendly way. You can also be notified whenever the
  membership of an array changes by using `.observes('myArray.[]')`.

  To support `Ember.Array` in your own class, you must override two
  primitives to use it: `replace()` and `objectAt()`.

  Note that the Ember.Array mixin also incorporates the `Ember.Enumerable`
  mixin. All `Ember.Array`-like objects are also enumerable.

  @class Array
  @namespace Ember
  @uses Ember.Enumerable
  @since Ember 0.9.0
*/
export default Mixin.create(Enumerable, {

  /**
    Your array must support the `length` property. Your replace methods should
    set this property whenever it changes.

    @property {Number} length
  */
  length: required(),

  /**
    Returns the object at the given `index`. If the given `index` is negative
    or is greater or equal than the array length, returns `undefined`.

    This is one of the primitives you must implement to support `Ember.Array`.
    If your object supports retrieving the value of an array item using `get()`
    (i.e. `myArray.get(0)`), then you do not need to implement this method
    yourself.

    ```javascript
    var arr = ['a', 'b', 'c', 'd'];

    arr.objectAt(0);   // 'a'
    arr.objectAt(3);   // 'd'
    arr.objectAt(-1);  // undefined
    arr.objectAt(4);   // undefined
    arr.objectAt(5);   // undefined
    ```

    @method objectAt
    @param {Number} idx The index of the item to return.
    @return {*} item at index or undefined
  */
  objectAt(idx) {
    if (idx < 0 || idx >= get(this, 'length')) {
      return undefined;
    }

    return get(this, idx);
  },

  /**
    This returns the objects at the specified indexes, using `objectAt`.

    ```javascript
    var arr = ['a', 'b', 'c', 'd'];

    arr.objectsAt([0, 1, 2]);  // ['a', 'b', 'c']
    arr.objectsAt([2, 3, 4]);  // ['c', 'd', undefined]
    ```

    @method objectsAt
    @param {Array} indexes An array of indexes of items to return.
    @return {Array}
   */
  objectsAt(indexes) {
    var self = this;

    return map(indexes, function(idx) {
      return self.objectAt(idx);
    });
  },

  // overrides Ember.Enumerable version
  nextObject(idx) {
    return this.objectAt(idx);
  },

  /**
    This is the handler for the special array content property. If you get
    this property, it will return this. If you set this property to a new
    array, it will replace the current content.

    This property overrides the default property defined in `Ember.Enumerable`.

    @property []
    @return this
  */
  '[]': computed(function(key, value) {
    if (value !== undefined) {
      this.replace(0, get(this, 'length'), value);
    }

    return this;
  }),

  firstObject: computed(function() {
    return this.objectAt(0);
  }),

  lastObject: computed(function() {
    return this.objectAt(get(this, 'length') - 1);
  }),

  // optimized version from Enumerable
  contains(obj) {
    return this.indexOf(obj) >= 0;
  },

  // Add any extra methods to Ember.Array that are native to the built-in Array.
  /**
    Returns a new array that is a slice of the receiver. This implementation
    uses the observable array methods to retrieve the objects for the new
    slice.

    ```javascript
    var arr = ['red', 'green', 'blue'];

    arr.slice(0);       // ['red', 'green', 'blue']
    arr.slice(0, 2);    // ['red', 'green']
    arr.slice(1, 100);  // ['green', 'blue']
    ```

    @method slice
    @param {Integer} beginIndex (Optional) index to begin slicing from.
    @param {Integer} endIndex (Optional) index to end the slice at (but not included).
    @return {Array} New array with specified slice
  */
  slice(beginIndex, endIndex) {
    var ret = Ember.A();
    var length = get(this, 'length');

    if (isNone(beginIndex)) {
      beginIndex = 0;
    }

    if (isNone(endIndex) || (endIndex > length)) {
      endIndex = length;
    }

    if (beginIndex < 0) {
      beginIndex = length + beginIndex;
    }

    if (endIndex < 0) {
      endIndex = length + endIndex;
    }

    while (beginIndex < endIndex) {
      ret[ret.length] = this.objectAt(beginIndex++);
    }

    return ret;
  },

  /**
    Returns the index of the given object's first occurrence.
    If no `startAt` argument is given, the starting location to
    search is 0. If it's negative, will count backward from
    the end of the array. Returns -1 if no match is found.

    ```javascript
    var arr = ['a', 'b', 'c', 'd', 'a'];

    arr.indexOf('a');       //  0
    arr.indexOf('z');       // -1
    arr.indexOf('a', 2);    //  4
    arr.indexOf('a', -1);   //  4
    arr.indexOf('b', 3);    // -1
    arr.indexOf('a', 100);  // -1
    ```

    @method indexOf
    @param {Object} object the item to search for
    @param {Number} startAt optional starting location to search, default 0
    @return {Number} index or -1 if not found
  */
  indexOf(object, startAt) {
    var len = get(this, 'length');
    var idx;

    if (startAt === undefined) {
      startAt = 0;
    }

    if (startAt < 0) {
      startAt += len;
    }

    for (idx = startAt; idx < len; idx++) {
      if (this.objectAt(idx) === object) {
        return idx;
      }
    }

    return -1;
  },

  /**
    Returns the index of the given object's last occurrence.
    If no `startAt` argument is given, the search starts from
    the last position. If it's negative, will count backward
    from the end of the array. Returns -1 if no match is found.

    ```javascript
    var arr = ['a', 'b', 'c', 'd', 'a'];

    arr.lastIndexOf('a');       //  4
    arr.lastIndexOf('z');       // -1
    arr.lastIndexOf('a', 2);    //  0
    arr.lastIndexOf('a', -1);   //  4
    arr.lastIndexOf('b', 3);    //  1
    arr.lastIndexOf('a', 100);  //  4
    ```

    @method lastIndexOf
    @param {Object} object the item to search for
    @param {Number} startAt optional starting location to search, default 0
    @return {Number} index or -1 if not found
  */
  lastIndexOf(object, startAt) {
    var len = get(this, 'length');
    var idx;

    if (startAt === undefined || startAt >= len) {
      startAt = len-1;
    }

    if (startAt < 0) {
      startAt += len;
    }

    for (idx = startAt; idx >= 0; idx--) {
      if (this.objectAt(idx) === object) {
        return idx;
      }
    }

    return -1;
  },

  // ..........................................................
  // ARRAY OBSERVERS
  //

  /**
    Adds an array observer to the receiving array. The array observer object
    normally must implement two methods:

    * `arrayWillChange(observedObj, start, removeCount, addCount)` - This method will be
      called just before the array is modified.
    * `arrayDidChange(observedObj, start, removeCount, addCount)` - This method will be
      called just after the array is modified.

    Both callbacks will be passed the observed object, starting index of the
    change as well a a count of the items to be removed and added. You can use
    these callbacks to optionally inspect the array during the change, clear
    caches, or do any other bookkeeping necessary.

    In addition to passing a target, you can also include an options hash
    which you can use to override the method names that will be invoked on the
    target.

    @method addArrayObserver
    @param {Object} target The observer object.
    @param {Hash} opts Optional hash of configuration options including
      `willChange` and `didChange` option.
    @return {Ember.Array} receiver
  */

  addArrayObserver(target, opts) {
    return arrayObserversHelper(this, target, opts, addListener, false);
  },

  /**
    Removes an array observer from the object if the observer is current
    registered. Calling this method multiple times with the same object will
    have no effect.

    @method removeArrayObserver
    @param {Object} target The object observing the array.
    @param {Hash} opts Optional hash of configuration options including
      `willChange` and `didChange` option.
    @return {Ember.Array} receiver
  */
  removeArrayObserver(target, opts) {
    return arrayObserversHelper(this, target, opts, removeListener, true);
  },

  /**
    Becomes true whenever the array currently has observers watching changes
    on the array.

    @property {Boolean} hasArrayObservers
  */
  hasArrayObservers: computed(function() {
    return hasListeners(this, '@array:change') || hasListeners(this, '@array:before');
  }),

  /**
    If you are implementing an object that supports `Ember.Array`, call this
    method just before the array content changes to notify any observers and
    invalidate any related properties. Pass the starting index of the change
    as well as a delta of the amounts to change.

    @method arrayContentWillChange
    @param {Number} startIdx The starting index in the array that will change.
    @param {Number} removeAmt The number of items that will be removed. If you
      pass `null` assumes 0
    @param {Number} addAmt The number of items that will be added. If you
      pass `null` assumes 0.
    @return {Ember.Array} receiver
  */
  arrayContentWillChange(startIdx, removeAmt, addAmt) {
    var removing, lim;

    // if no args are passed assume everything changes
    if (startIdx === undefined) {
      startIdx = 0;
      removeAmt = addAmt = -1;
    } else {
      if (removeAmt === undefined) {
        removeAmt = -1;
      }

      if (addAmt === undefined) {
        addAmt = -1;
      }
    }

    // Make sure the @each proxy is set up if anyone is observing @each
    if (isWatching(this, '@each')) {
      get(this, '@each');
    }

    sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]);

    if (startIdx >= 0 && removeAmt >= 0 && get(this, 'hasEnumerableObservers')) {
      removing = [];
      lim = startIdx + removeAmt;

      for (var idx = startIdx; idx < lim; idx++) {
        removing.push(this.objectAt(idx));
      }
    } else {
      removing = removeAmt;
    }

    this.enumerableContentWillChange(removing, addAmt);

    return this;
  },

  /**
    If you are implementing an object that supports `Ember.Array`, call this
    method just after the array content changes to notify any observers and
    invalidate any related properties. Pass the starting index of the change
    as well as a delta of the amounts to change.

    @method arrayContentDidChange
    @param {Number} startIdx The starting index in the array that did change.
    @param {Number} removeAmt The number of items that were removed. If you
      pass `null` assumes 0
    @param {Number} addAmt The number of items that were added. If you
      pass `null` assumes 0.
    @return {Ember.Array} receiver
  */
  arrayContentDidChange(startIdx, removeAmt, addAmt) {
    var adding, lim;

    // if no args are passed assume everything changes
    if (startIdx === undefined) {
      startIdx = 0;
      removeAmt = addAmt = -1;
    } else {
      if (removeAmt === undefined) {
        removeAmt = -1;
      }

      if (addAmt === undefined) {
        addAmt = -1;
      }
    }

    if (startIdx >= 0 && addAmt >= 0 && get(this, 'hasEnumerableObservers')) {
      adding = [];
      lim = startIdx + addAmt;

      for (var idx = startIdx; idx < lim; idx++) {
        adding.push(this.objectAt(idx));
      }
    } else {
      adding = addAmt;
    }

    this.enumerableContentDidChange(removeAmt, adding);
    sendEvent(this, '@array:change', [this, startIdx, removeAmt, addAmt]);

    var length = get(this, 'length');
    var cachedFirst = cacheFor(this, 'firstObject');
    var cachedLast = cacheFor(this, 'lastObject');

    if (this.objectAt(0) !== cachedFirst) {
      propertyWillChange(this, 'firstObject');
      propertyDidChange(this, 'firstObject');
    }

    if (this.objectAt(length-1) !== cachedLast) {
      propertyWillChange(this, 'lastObject');
      propertyDidChange(this, 'lastObject');
    }

    return this;
  },

  // ..........................................................
  // ENUMERATED PROPERTIES
  //

  /**
    Returns a special object that can be used to observe individual properties
    on the array. Just get an equivalent property on this object and it will
    return an enumerable that maps automatically to the named key on the
    member objects.

    If you merely want to watch for any items being added or removed to the array,
    use the `[]` property instead of `@each`.

    @property @each
  */
  '@each': computed(function() {
    if (!this.__each) {
      // ES6TODO: GRRRRR
      var EachProxy = requireModule('ember-runtime/system/each_proxy')['EachProxy'];

      this.__each = new EachProxy(this);
    }

    return this.__each;
  })
});
<commit_msg>Document primitives of Ember.Array mixin<commit_after>/**
@module ember
@submodule ember-runtime
*/

// ..........................................................
// HELPERS
//
import Ember from 'ember-metal/core'; // ES6TODO: Ember.A

import { get } from 'ember-metal/property_get';
import {
  computed,
  cacheFor
} from 'ember-metal/computed';
import isNone from 'ember-metal/is_none';
import Enumerable from 'ember-runtime/mixins/enumerable';
import { map } from 'ember-metal/enumerable_utils';
import {
  Mixin,
  required
} from 'ember-metal/mixin';
import {
  propertyWillChange,
  propertyDidChange
} from 'ember-metal/property_events';
import {
  addListener,
  removeListener,
  sendEvent,
  hasListeners
} from 'ember-metal/events';
import { isWatching } from 'ember-metal/watching';

function arrayObserversHelper(obj, target, opts, operation, notify) {
  var willChange = (opts && opts.willChange) || 'arrayWillChange';
  var didChange  = (opts && opts.didChange) || 'arrayDidChange';
  var hasObservers = get(obj, 'hasArrayObservers');

  if (hasObservers === notify) {
    propertyWillChange(obj, 'hasArrayObservers');
  }

  operation(obj, '@array:before', target, willChange);
  operation(obj, '@array:change', target, didChange);

  if (hasObservers === notify) {
    propertyDidChange(obj, 'hasArrayObservers');
  }

  return obj;
}

// ..........................................................
// ARRAY
//
/**
  This mixin implements Observer-friendly Array-like behavior. It is not a
  concrete implementation, but it can be used up by other classes that want
  to appear like arrays.

  For example, ArrayProxy and ArrayController are both concrete classes that can
  be instantiated to implement array-like behavior. Both of these classes use
  the Array Mixin by way of the MutableArray mixin, which allows observable
  changes to be made to the underlying array.

  Unlike `Ember.Enumerable,` this mixin defines methods specifically for
  collections that provide index-ordered access to their contents. When you
  are designing code that needs to accept any kind of Array-like object, you
  should use these methods instead of Array primitives because these will
  properly notify observers of changes to the array.

  Although these methods are efficient, they do add a layer of indirection to
  your application so it is a good idea to use them only when you need the
  flexibility of using both true JavaScript arrays and "virtual" arrays such
  as controllers and collections.

  You can use the methods defined in this module to access and modify array
  contents in a KVO-friendly way. You can also be notified whenever the
  membership of an array changes by using `.observes('myArray.[]')`.

  To support `Ember.Array` in your own class, you must override two
  primitives to use it: `length()` and `objectAt()`.

  Note that the Ember.Array mixin also incorporates the `Ember.Enumerable`
  mixin. All `Ember.Array`-like objects are also enumerable.

  @class Array
  @namespace Ember
  @uses Ember.Enumerable
  @since Ember 0.9.0
*/
export default Mixin.create(Enumerable, {

  /**
    Your array must support the `length` property. Your replace methods should
    set this property whenever it changes.

    @property {Number} length
  */
  length: required(),

  /**
    Returns the object at the given `index`. If the given `index` is negative
    or is greater or equal than the array length, returns `undefined`.

    This is one of the primitives you must implement to support `Ember.Array`.
    If your object supports retrieving the value of an array item using `get()`
    (i.e. `myArray.get(0)`), then you do not need to implement this method
    yourself.

    ```javascript
    var arr = ['a', 'b', 'c', 'd'];

    arr.objectAt(0);   // 'a'
    arr.objectAt(3);   // 'd'
    arr.objectAt(-1);  // undefined
    arr.objectAt(4);   // undefined
    arr.objectAt(5);   // undefined
    ```

    @method objectAt
    @param {Number} idx The index of the item to return.
    @return {*} item at index or undefined
  */
  objectAt(idx) {
    if (idx < 0 || idx >= get(this, 'length')) {
      return undefined;
    }

    return get(this, idx);
  },

  /**
    This returns the objects at the specified indexes, using `objectAt`.

    ```javascript
    var arr = ['a', 'b', 'c', 'd'];

    arr.objectsAt([0, 1, 2]);  // ['a', 'b', 'c']
    arr.objectsAt([2, 3, 4]);  // ['c', 'd', undefined]
    ```

    @method objectsAt
    @param {Array} indexes An array of indexes of items to return.
    @return {Array}
   */
  objectsAt(indexes) {
    var self = this;

    return map(indexes, function(idx) {
      return self.objectAt(idx);
    });
  },

  // overrides Ember.Enumerable version
  nextObject(idx) {
    return this.objectAt(idx);
  },

  /**
    This is the handler for the special array content property. If you get
    this property, it will return this. If you set this property to a new
    array, it will replace the current content.

    This property overrides the default property defined in `Ember.Enumerable`.

    @property []
    @return this
  */
  '[]': computed(function(key, value) {
    if (value !== undefined) {
      this.replace(0, get(this, 'length'), value);
    }

    return this;
  }),

  firstObject: computed(function() {
    return this.objectAt(0);
  }),

  lastObject: computed(function() {
    return this.objectAt(get(this, 'length') - 1);
  }),

  // optimized version from Enumerable
  contains(obj) {
    return this.indexOf(obj) >= 0;
  },

  // Add any extra methods to Ember.Array that are native to the built-in Array.
  /**
    Returns a new array that is a slice of the receiver. This implementation
    uses the observable array methods to retrieve the objects for the new
    slice.

    ```javascript
    var arr = ['red', 'green', 'blue'];

    arr.slice(0);       // ['red', 'green', 'blue']
    arr.slice(0, 2);    // ['red', 'green']
    arr.slice(1, 100);  // ['green', 'blue']
    ```

    @method slice
    @param {Integer} beginIndex (Optional) index to begin slicing from.
    @param {Integer} endIndex (Optional) index to end the slice at (but not included).
    @return {Array} New array with specified slice
  */
  slice(beginIndex, endIndex) {
    var ret = Ember.A();
    var length = get(this, 'length');

    if (isNone(beginIndex)) {
      beginIndex = 0;
    }

    if (isNone(endIndex) || (endIndex > length)) {
      endIndex = length;
    }

    if (beginIndex < 0) {
      beginIndex = length + beginIndex;
    }

    if (endIndex < 0) {
      endIndex = length + endIndex;
    }

    while (beginIndex < endIndex) {
      ret[ret.length] = this.objectAt(beginIndex++);
    }

    return ret;
  },

  /**
    Returns the index of the given object's first occurrence.
    If no `startAt` argument is given, the starting location to
    search is 0. If it's negative, will count backward from
    the end of the array. Returns -1 if no match is found.

    ```javascript
    var arr = ['a', 'b', 'c', 'd', 'a'];

    arr.indexOf('a');       //  0
    arr.indexOf('z');       // -1
    arr.indexOf('a', 2);    //  4
    arr.indexOf('a', -1);   //  4
    arr.indexOf('b', 3);    // -1
    arr.indexOf('a', 100);  // -1
    ```

    @method indexOf
    @param {Object} object the item to search for
    @param {Number} startAt optional starting location to search, default 0
    @return {Number} index or -1 if not found
  */
  indexOf(object, startAt) {
    var len = get(this, 'length');
    var idx;

    if (startAt === undefined) {
      startAt = 0;
    }

    if (startAt < 0) {
      startAt += len;
    }

    for (idx = startAt; idx < len; idx++) {
      if (this.objectAt(idx) === object) {
        return idx;
      }
    }

    return -1;
  },

  /**
    Returns the index of the given object's last occurrence.
    If no `startAt` argument is given, the search starts from
    the last position. If it's negative, will count backward
    from the end of the array. Returns -1 if no match is found.

    ```javascript
    var arr = ['a', 'b', 'c', 'd', 'a'];

    arr.lastIndexOf('a');       //  4
    arr.lastIndexOf('z');       // -1
    arr.lastIndexOf('a', 2);    //  0
    arr.lastIndexOf('a', -1);   //  4
    arr.lastIndexOf('b', 3);    //  1
    arr.lastIndexOf('a', 100);  //  4
    ```

    @method lastIndexOf
    @param {Object} object the item to search for
    @param {Number} startAt optional starting location to search, default 0
    @return {Number} index or -1 if not found
  */
  lastIndexOf(object, startAt) {
    var len = get(this, 'length');
    var idx;

    if (startAt === undefined || startAt >= len) {
      startAt = len-1;
    }

    if (startAt < 0) {
      startAt += len;
    }

    for (idx = startAt; idx >= 0; idx--) {
      if (this.objectAt(idx) === object) {
        return idx;
      }
    }

    return -1;
  },

  // ..........................................................
  // ARRAY OBSERVERS
  //

  /**
    Adds an array observer to the receiving array. The array observer object
    normally must implement two methods:

    * `arrayWillChange(observedObj, start, removeCount, addCount)` - This method will be
      called just before the array is modified.
    * `arrayDidChange(observedObj, start, removeCount, addCount)` - This method will be
      called just after the array is modified.

    Both callbacks will be passed the observed object, starting index of the
    change as well a a count of the items to be removed and added. You can use
    these callbacks to optionally inspect the array during the change, clear
    caches, or do any other bookkeeping necessary.

    In addition to passing a target, you can also include an options hash
    which you can use to override the method names that will be invoked on the
    target.

    @method addArrayObserver
    @param {Object} target The observer object.
    @param {Hash} opts Optional hash of configuration options including
      `willChange` and `didChange` option.
    @return {Ember.Array} receiver
  */

  addArrayObserver(target, opts) {
    return arrayObserversHelper(this, target, opts, addListener, false);
  },

  /**
    Removes an array observer from the object if the observer is current
    registered. Calling this method multiple times with the same object will
    have no effect.

    @method removeArrayObserver
    @param {Object} target The object observing the array.
    @param {Hash} opts Optional hash of configuration options including
      `willChange` and `didChange` option.
    @return {Ember.Array} receiver
  */
  removeArrayObserver(target, opts) {
    return arrayObserversHelper(this, target, opts, removeListener, true);
  },

  /**
    Becomes true whenever the array currently has observers watching changes
    on the array.

    @property {Boolean} hasArrayObservers
  */
  hasArrayObservers: computed(function() {
    return hasListeners(this, '@array:change') || hasListeners(this, '@array:before');
  }),

  /**
    If you are implementing an object that supports `Ember.Array`, call this
    method just before the array content changes to notify any observers and
    invalidate any related properties. Pass the starting index of the change
    as well as a delta of the amounts to change.

    @method arrayContentWillChange
    @param {Number} startIdx The starting index in the array that will change.
    @param {Number} removeAmt The number of items that will be removed. If you
      pass `null` assumes 0
    @param {Number} addAmt The number of items that will be added. If you
      pass `null` assumes 0.
    @return {Ember.Array} receiver
  */
  arrayContentWillChange(startIdx, removeAmt, addAmt) {
    var removing, lim;

    // if no args are passed assume everything changes
    if (startIdx === undefined) {
      startIdx = 0;
      removeAmt = addAmt = -1;
    } else {
      if (removeAmt === undefined) {
        removeAmt = -1;
      }

      if (addAmt === undefined) {
        addAmt = -1;
      }
    }

    // Make sure the @each proxy is set up if anyone is observing @each
    if (isWatching(this, '@each')) {
      get(this, '@each');
    }

    sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]);

    if (startIdx >= 0 && removeAmt >= 0 && get(this, 'hasEnumerableObservers')) {
      removing = [];
      lim = startIdx + removeAmt;

      for (var idx = startIdx; idx < lim; idx++) {
        removing.push(this.objectAt(idx));
      }
    } else {
      removing = removeAmt;
    }

    this.enumerableContentWillChange(removing, addAmt);

    return this;
  },

  /**
    If you are implementing an object that supports `Ember.Array`, call this
    method just after the array content changes to notify any observers and
    invalidate any related properties. Pass the starting index of the change
    as well as a delta of the amounts to change.

    @method arrayContentDidChange
    @param {Number} startIdx The starting index in the array that did change.
    @param {Number} removeAmt The number of items that were removed. If you
      pass `null` assumes 0
    @param {Number} addAmt The number of items that were added. If you
      pass `null` assumes 0.
    @return {Ember.Array} receiver
  */
  arrayContentDidChange(startIdx, removeAmt, addAmt) {
    var adding, lim;

    // if no args are passed assume everything changes
    if (startIdx === undefined) {
      startIdx = 0;
      removeAmt = addAmt = -1;
    } else {
      if (removeAmt === undefined) {
        removeAmt = -1;
      }

      if (addAmt === undefined) {
        addAmt = -1;
      }
    }

    if (startIdx >= 0 && addAmt >= 0 && get(this, 'hasEnumerableObservers')) {
      adding = [];
      lim = startIdx + addAmt;

      for (var idx = startIdx; idx < lim; idx++) {
        adding.push(this.objectAt(idx));
      }
    } else {
      adding = addAmt;
    }

    this.enumerableContentDidChange(removeAmt, adding);
    sendEvent(this, '@array:change', [this, startIdx, removeAmt, addAmt]);

    var length = get(this, 'length');
    var cachedFirst = cacheFor(this, 'firstObject');
    var cachedLast = cacheFor(this, 'lastObject');

    if (this.objectAt(0) !== cachedFirst) {
      propertyWillChange(this, 'firstObject');
      propertyDidChange(this, 'firstObject');
    }

    if (this.objectAt(length-1) !== cachedLast) {
      propertyWillChange(this, 'lastObject');
      propertyDidChange(this, 'lastObject');
    }

    return this;
  },

  // ..........................................................
  // ENUMERATED PROPERTIES
  //

  /**
    Returns a special object that can be used to observe individual properties
    on the array. Just get an equivalent property on this object and it will
    return an enumerable that maps automatically to the named key on the
    member objects.

    If you merely want to watch for any items being added or removed to the array,
    use the `[]` property instead of `@each`.

    @property @each
  */
  '@each': computed(function() {
    if (!this.__each) {
      // ES6TODO: GRRRRR
      var EachProxy = requireModule('ember-runtime/system/each_proxy')['EachProxy'];

      this.__each = new EachProxy(this);
    }

    return this.__each;
  })
});
<|endoftext|>


<commit_before>var MyGame = MyGame || {};

MyGame.ImageSelect = function(){};

MyGame.ImageSelect.prototype = {
  preload: function(){
    this.matrix = this.cache.getText('Matrix');
    this.picture = this.cache.getText('Image');
    this.currentPlayState = this.cache.getText('Music');
    if(this.cache.checkTextKey('Dimensions')){
      this.dimensions = this.cache.getText('Dimensions').dimensions;
    }
    if(this.cache.checkJSONKey('Pics')){
      this.pictures = this.cache.getJSON('Pics').pics;
    } else {
      console.log("no Pics");
    }
  },
  create: function(){
    this.imgSelect();
    this.createTopButtons();
    this.createBottomButtons();
    console.log(this);
  },
  imgSelect: function(){
    var w10 = this.world.width * 0.15 ;
    var w2 = w10 * 0.25;
    var h10 = this.world.height * 0.15;

    var bmd2 = this.make.bitmapData(w10,w10);
    bmd2.draw('fullSize',0,0,w10,h10);
    bmd2.update();
    this.add.sprite(0,0,bmd2);

    var bmd2a = this.add.bitmapData(w10,w10);
    bmd2a.ctx.beginPath();
    bmd2a.ctx.rect(0,0,w10,w10);
    bmd2a.ctx.fillStyle = '#FF0000';
    bmd2a.ctx.fill();
    var area, currentImg, imgScale;

    /**
    for(i=0;i<this.pictures.length;i++){
      if(i===0){
        area = Phaser.Rectangle(0,0,100,100);
        currentImg = this.add.image(0,0,'fullSize');
        currentImg.crop(area);
        imgScale = new Phaser.Point(0.15,0.15);
        currentImg.scale = imgScale;
        currentImg.anchor.set(0.5);
        imgText = this.add.text(0,-w2*1.5,this.picture.word);
        imgText.align = 'center';
        imgText.anchor.set(0.5);
        if (this.pictures[i].word == this.picture.word) {
          imgPick = this.add.sprite(this.world.centerX, this.world.centerY,bmd2a);
        } else {
          imgPick = this.add.sprite(this.world.centerX, this.world.centerY,bmd2);
        }
        imgPick.addChild(imgText);
        imgPick.addChild(currentImg);
      } else if(i==1) {
        currentImg = this.add.image(0,0,this.pictures[i].word);
        imgScale = new Phaser.Point(0.1,0.1);
        currentImg.scale = imgScale;
        currentImg.anchor.set(0.5);
        imgText = this.add.text(0,-w2*1.5,this.pictures[i].word);
        imgText.align = 'center';
        imgText.anchor.set(0.5);
        if (this.pictures[i].word == this.picture.word) {
          imgPick = this.add.sprite(this.world.centerX - (w10 + w2), this.world.centerY,bmd2a);
        } else {
          imgPick = this.add.sprite(this.world.centerX - (w10 + w2), this.world.centerY,bmd2);
        }
        imgPick.addChild(imgText);
        imgPick.addChild(currentImg);
      } else if(i%2 === 0) {
        currentImg = this.add.image(0,0,this.pictures[i].word);
        //currentImg.crop(area);
        imgScale = new Phaser.Point(0.1,0.1);
        currentImg.scale = imgScale;
        currentImg.anchor.set(0.5);
        imgText = this.add.text(0,-w2*1.5,this.pictures[i].word);
        imgText.align = 'center';
        imgText.anchor.set(0.5);
        if (this.pictures[i].word == this.picture.word) {
          imgPick = this.add.sprite(this.world.centerX + (w10*(i*0.5) + w2*(i*0.5)), this.world.centerY,bmd2a);
        } else {
          imgPick = this.add.sprite(this.world.centerX + (w10*(i*0.5) + w2*(i*0.5)), this.world.centerY,bmd2);
        }
        imgPick.addChild(imgText);
        imgPick.addChild(currentImg);
      } else if(i%2 == 1) {
        currentImg = this.add.image(0,0,this.pictures[i].word);
        imgScale = new Phaser.Point(0.1,0.1);
        currentImg.scale = imgScale;
        currentImg.anchor.set(0.5);
        imgText = this.add.text(0,-w2*1.5,this.pictures[i].word);
        imgText.align = 'center';
        imgText.anchor.set(0.5);
        if (this.pictures[i].word == this.picture.word) {
          imgPick = this.add.sprite(this.world.centerX + (w10*(i - 1) + w2*(i - 1)), this.world.centerY,bmd2a);
        } else {
          imgPick = this.add.sprite(this.world.centerX + (w10*(i - 1) + w2*(i - 1)), this.world.centerY,bmd2);
        }
        imgPick.addChild(imgText);
        imgPick.addChild(currentImg);
      }
      imgPick.anchor.set(0.5);
    }
    **/
  },
  createTopButtons: function(){
    var width = this.world.width/16;
    var bmd = this.add.bitmapData(width,width);
    bmd.ctx.beginPath();
    bmd.ctx.rect(0,0,width,width);
    bmd.ctx.fillStyle = '#ff0000';
    bmd.ctx.fill();
    var homeText = this.add.text(0,0,'home');
    homeText.fontSize = width*0.25;
    homeText.anchor.set(0.5);

    var button = this.add.button(width*1.1, width*0.5,bmd,this.menu,this);
    button.anchor.set(0.5);
    button.addChild(homeText);

    var bmd2 = this.add.bitmapData(width,width);
    bmd2.ctx.beginPath();
    bmd2.ctx.rect(0,0,width,width);
    bmd2.ctx.fillStyle = '#00ff00';
    bmd2.ctx.fill();
    var creditText = this.add.text(0,0,'settings');
    creditText.fontSize = width*0.25;
    creditText.anchor.set(0.5);
    creditText.align = 'center';

    var button2 = this.add.button(this.world.width - width*1.1, width*0.5,bmd2,this.settings,this);
    button2.anchor.set(0.5);
    button2.addChild(creditText);
  },
  settings: function(){
    this.state.start('Settings');
  },
  menu: function(){
    this.state.start('MainMenu');
  },
  credits: function(){
    this.state.start('GameOver');
  },
  createBottomButtons: function(){
    var width = this.world.width/16;
    var bmd = this.add.bitmapData(width,width);
    bmd.ctx.beginPath();
    bmd.ctx.rect(0,0,width,width);
    bmd.ctx.fillStyle = '#FF0000';
    bmd.ctx.fill();
    var offText = this.add.text(0,0,'off');
    offText.fontSize = width*0.3;
    offText.anchor.set(0.5);
    offText.align = 'center';

    this.offButton = this.add.button(width*1.1, this.world.height - width*0.5,bmd,this.musicOff,this);
    this.offButton.anchor.set(0.5);
    this.offButton.addChild(offText);

    var onText = this.add.text(0,0,'on');
    onText.fontSize = width*0.3;
    onText.anchor.set(0.5);
    onText.align = 'center';

    this.onButton = this.add.button(width*1.1, this.world.height - width*0.5,bmd,this.musicOn,this);
    this.onButton.anchor.set(0.5);
    this.onButton.addChild(onText);

    if(this.currentPlayState.value == 'on'){
      this.offButton.bringToTop();
    }
  },
  musicOff: function(){
    this.sound.pauseAll();
    this.onButton.bringToTop();
    this.cache.addText('Music', null, {value: 'off'});
  },
  musicOn: function(){
    this.sound.resumeAll();
    this.offButton.bringToTop();
    this.cache.addText('Music', null, {value: 'on'});
  }
};<commit_msg>Working on image select<commit_after>var MyGame = MyGame || {};

MyGame.ImageSelect = function(){};

MyGame.ImageSelect.prototype = {
  preload: function(){
    this.matrix = this.cache.getText('Matrix');
    this.picture = this.cache.getText('Image');
    this.currentPlayState = this.cache.getText('Music');
    if(this.cache.checkTextKey('Dimensions')){
      this.dimensions = this.cache.getText('Dimensions').dimensions;
    }
    if(this.cache.checkJSONKey('Pics')){
      this.pictures = this.cache.getJSON('Pics').pics;
    } else {
      console.log("no Pics");
    }
  },
  create: function(){
    this.imgSelect();
    this.createTopButtons();
    this.createBottomButtons();
    console.log(this);
  },
  imgSelect: function(){
    var w10 = this.world.width * 0.15 ;
    var w2 = w10 * 0.25;
    var h10 = this.world.height * 0.15;

    var bkgd = this.make.bitmapData(400, this.world.height * 0.75);
    bkgd.fill(50,50,50);

    var bmd2 = this.make.bitmapData(w10,w10);
    bmd2.draw('fullSize',0,0,w10,h10);
    bmd2.update();
    var place = this.add.sprite(0,0,bmd2);
    var bg = this.add.sprite(this.world.width * 0.1,this.world.height * 0.125, bkgd);
    bg.addChild(place);

    /**
    for(i=0;i<this.pictures.length;i++){
      if(i===0){
        area = Phaser.Rectangle(0,0,100,100);
        currentImg = this.add.image(0,0,'fullSize');
        currentImg.crop(area);
        imgScale = new Phaser.Point(0.15,0.15);
        currentImg.scale = imgScale;
        currentImg.anchor.set(0.5);
        imgText = this.add.text(0,-w2*1.5,this.picture.word);
        imgText.align = 'center';
        imgText.anchor.set(0.5);
        if (this.pictures[i].word == this.picture.word) {
          imgPick = this.add.sprite(this.world.centerX, this.world.centerY,bmd2a);
        } else {
          imgPick = this.add.sprite(this.world.centerX, this.world.centerY,bmd2);
        }
        imgPick.addChild(imgText);
        imgPick.addChild(currentImg);
      } else if(i==1) {
        currentImg = this.add.image(0,0,this.pictures[i].word);
        imgScale = new Phaser.Point(0.1,0.1);
        currentImg.scale = imgScale;
        currentImg.anchor.set(0.5);
        imgText = this.add.text(0,-w2*1.5,this.pictures[i].word);
        imgText.align = 'center';
        imgText.anchor.set(0.5);
        if (this.pictures[i].word == this.picture.word) {
          imgPick = this.add.sprite(this.world.centerX - (w10 + w2), this.world.centerY,bmd2a);
        } else {
          imgPick = this.add.sprite(this.world.centerX - (w10 + w2), this.world.centerY,bmd2);
        }
        imgPick.addChild(imgText);
        imgPick.addChild(currentImg);
      } else if(i%2 === 0) {
        currentImg = this.add.image(0,0,this.pictures[i].word);
        //currentImg.crop(area);
        imgScale = new Phaser.Point(0.1,0.1);
        currentImg.scale = imgScale;
        currentImg.anchor.set(0.5);
        imgText = this.add.text(0,-w2*1.5,this.pictures[i].word);
        imgText.align = 'center';
        imgText.anchor.set(0.5);
        if (this.pictures[i].word == this.picture.word) {
          imgPick = this.add.sprite(this.world.centerX + (w10*(i*0.5) + w2*(i*0.5)), this.world.centerY,bmd2a);
        } else {
          imgPick = this.add.sprite(this.world.centerX + (w10*(i*0.5) + w2*(i*0.5)), this.world.centerY,bmd2);
        }
        imgPick.addChild(imgText);
        imgPick.addChild(currentImg);
      } else if(i%2 == 1) {
        currentImg = this.add.image(0,0,this.pictures[i].word);
        imgScale = new Phaser.Point(0.1,0.1);
        currentImg.scale = imgScale;
        currentImg.anchor.set(0.5);
        imgText = this.add.text(0,-w2*1.5,this.pictures[i].word);
        imgText.align = 'center';
        imgText.anchor.set(0.5);
        if (this.pictures[i].word == this.picture.word) {
          imgPick = this.add.sprite(this.world.centerX + (w10*(i - 1) + w2*(i - 1)), this.world.centerY,bmd2a);
        } else {
          imgPick = this.add.sprite(this.world.centerX + (w10*(i - 1) + w2*(i - 1)), this.world.centerY,bmd2);
        }
        imgPick.addChild(imgText);
        imgPick.addChild(currentImg);
      }
      imgPick.anchor.set(0.5);
    }
    **/
  },
  createTopButtons: function(){
    var width = this.world.width/16;
    var bmd = this.add.bitmapData(width,width);
    bmd.ctx.beginPath();
    bmd.ctx.rect(0,0,width,width);
    bmd.ctx.fillStyle = '#ff0000';
    bmd.ctx.fill();
    var homeText = this.add.text(0,0,'home');
    homeText.fontSize = width*0.25;
    homeText.anchor.set(0.5);

    var button = this.add.button(width*1.1, width*0.5,bmd,this.menu,this);
    button.anchor.set(0.5);
    button.addChild(homeText);

    var bmd2 = this.add.bitmapData(width,width);
    bmd2.ctx.beginPath();
    bmd2.ctx.rect(0,0,width,width);
    bmd2.ctx.fillStyle = '#00ff00';
    bmd2.ctx.fill();
    var creditText = this.add.text(0,0,'settings');
    creditText.fontSize = width*0.25;
    creditText.anchor.set(0.5);
    creditText.align = 'center';

    var button2 = this.add.button(this.world.width - width*1.1, width*0.5,bmd2,this.settings,this);
    button2.anchor.set(0.5);
    button2.addChild(creditText);
  },
  settings: function(){
    this.state.start('Settings');
  },
  menu: function(){
    this.state.start('MainMenu');
  },
  credits: function(){
    this.state.start('GameOver');
  },
  createBottomButtons: function(){
    var width = this.world.width/16;
    var bmd = this.add.bitmapData(width,width);
    bmd.ctx.beginPath();
    bmd.ctx.rect(0,0,width,width);
    bmd.ctx.fillStyle = '#FF0000';
    bmd.ctx.fill();
    var offText = this.add.text(0,0,'off');
    offText.fontSize = width*0.3;
    offText.anchor.set(0.5);
    offText.align = 'center';

    this.offButton = this.add.button(width*1.1, this.world.height - width*0.5,bmd,this.musicOff,this);
    this.offButton.anchor.set(0.5);
    this.offButton.addChild(offText);

    var onText = this.add.text(0,0,'on');
    onText.fontSize = width*0.3;
    onText.anchor.set(0.5);
    onText.align = 'center';

    this.onButton = this.add.button(width*1.1, this.world.height - width*0.5,bmd,this.musicOn,this);
    this.onButton.anchor.set(0.5);
    this.onButton.addChild(onText);

    if(this.currentPlayState.value == 'on'){
      this.offButton.bringToTop();
    }
  },
  musicOff: function(){
    this.sound.pauseAll();
    this.onButton.bringToTop();
    this.cache.addText('Music', null, {value: 'off'});
  },
  musicOn: function(){
    this.sound.resumeAll();
    this.offButton.bringToTop();
    this.cache.addText('Music', null, {value: 'on'});
  }
};<|endoftext|>


<commit_before>let redirect;

if (process.env.PORT === undefined) {
    redirect = `https://${process.env.R_HOST}`;
} else if (process.env.PORT !== undefined) {
    if (process.env.HOST === undefined) {
        throw new Error('Missing HOST!');
    } else {
        redirect = `http://${process.env.HOST}:${process.env.PORT}`;
    }
}

module.exports = {
    host: process.env.HOST,
    port: process.env.PORT,
    fitbit: {
        client: {
            id: process.env.FB_ID,
            secret: process.env.FB_SECRET
        },
        uri: {
            authorization: 'https://www.fitbit.com/oauth2/authorize',
            token: 'https://api.fitbit.com/oauth2/token',
            redirect: `${redirect}/fitbit-authorization`
        },
        scope: 'activity heartrate location nutrition profile settings sleep social weight',
        responseType: 'code'
    },
    slack: {
        client: {
            id: process.env.SL_ID,
            secret: process.env.SL_SECRET
        },
        uri: {
            authorization: 'https://slack.com/oauth/authorize',
            token: 'https://slack.com/api/oauth.access',
            redirect: `${redirect}/slack-authorization`
        },
        scope: 'chat:write:bot'
    }
};<commit_msg>Fix faulty check<commit_after>let redirect;

if (process.env.PORT === undefined) {
    redirect = `https://${process.env.R_HOST}`;
} else if (process.env.PORT !== undefined) {
    redirect = `http://${process.env.HOST}:${process.env.PORT}`;
}

module.exports = {
    host: process.env.HOST,
    port: process.env.PORT,
    fitbit: {
        client: {
            id: process.env.FB_ID,
            secret: process.env.FB_SECRET
        },
        uri: {
            authorization: 'https://www.fitbit.com/oauth2/authorize',
            token: 'https://api.fitbit.com/oauth2/token',
            redirect: `${redirect}/fitbit-authorization`
        },
        scope: 'activity heartrate location nutrition profile settings sleep social weight',
        responseType: 'code'
    },
    slack: {
        client: {
            id: process.env.SL_ID,
            secret: process.env.SL_SECRET
        },
        uri: {
            authorization: 'https://slack.com/oauth/authorize',
            token: 'https://slack.com/api/oauth.access',
            redirect: `${redirect}/slack-authorization`
        },
        scope: 'chat:write:bot'
    }
};<|endoftext|>


<commit_before>/**
 * Created by ksinger on 24.08.2015.
 */
import angular from "angular";
import ngAnimate from "angular-animate";

import "ng-redux";
import labelledHrModule from "./labelled-hr.js";
import imageDropzoneModule from "./image-dropzone.js";
import matchingContextModule from "./details/matching-context-picker.js"; // TODO: should be renamed
import createIsseeksModule from "./create-isseeks.js";
import { postTitleCharacterLimit } from "config";
import { get, getIn, attach, delay } from "../utils.js";
import { actionCreators } from "../actions/actions.js";
import won from "../won-es6.js";
import { connect2Redux } from "../won-utils.js";
import { selectIsConnected } from "../selectors.js";

// import { details } from "detailDefinitions";
import { useCases } from "useCaseDefinitions";
// TODO: these should be replaced by importing defintions from config
import descriptionPickerModule from "./details/description-picker.js";
import locationPickerModule from "./details/location-picker.js";
import personPickerModule from "./details/person-picker.js";
import travelActionPickerModule from "./details/travel-action-picker.js";
import tagsPickerModule from "./details/tags-picker.js";
import ttlPickerModule from "./details/ttl-picker.js";

const postTypeTexts = [
  {
    type: won.WON.BasicNeedTypeDemand,
    text: "I'm looking for",
    helpText:
      "Select this if you are looking for things or services other people offer",
  },
  {
    type: won.WON.BasicNeedTypeSupply,
    text: "I'm offering",
    helpText:
      "Use this if you are offering an item or a service. You will find people who said" +
      " that they're looking for something.",
  },
  {
    type: won.WON.BasicNeedTypeDotogether,
    text: "I want to find someone to",
    helpText:
      "Select this if you are looking to find other people who share your interest. You will be matched" +
      " with other people who chose this option as well.",
  },
  {
    type: won.WON.BasicNeedTypeCombined,
    text: "I'm offering and looking for",
    helpText:
      "Select this if you are looking for things or services other people offer + Use this if you are offering an item or a service. You will find people who said" +
      " that they're looking for something.",
  },
];

//TODO can't inject $scope with the angular2-router, preventing redux-cleanup
const serviceDependencies = [
  "$ngRedux",
  "$scope",
  "$element" /*'$routeParams' /*injections as strings here*/,
];

function genComponentConf() {
  const template = `

                <svg style="--local-primary:var(--won-primary-color);"
                    class="cp__header__back__icon">
                    <use xlink:href="#ico36_backarrow" href="#ico36_backarrow"></use>
                </svg>

            {{self.useCase.label}}

            <won-labelled-hr label="::'Offering / Is'" class="cp__content__labelledhr" ng-if="self.useCase.isDetails && self.useCase.seeksDetails"> </won-labelled-hr>
            <won-create-isseeks
                ng-if="self.useCase.isDetails"
                is-or-seeks="::'Description'"
                title-placeholder="::'What do you offer or propose? (Short title shown in lists)'"
                detail-list="self.useCase.isDetails"
                initial-draft="self.useCase.draft.is"
                on-update="::self.updateDraft(draft, 'is')"
                on-scroll="::self.scrollToBottom(element)">
            </won-create-isseeks>
            <won-labelled-hr label="::'Want / Looking For'" class="cp__content__labelledhr" ng-if="self.useCase.isDetails && self.useCase.seeksDetails"> </won-labelled-hr>
            <won-create-isseeks
                ng-if="self.useCase.seeksDetails"
                is-or-seeks="::'Search'"
                title-placeholder="::'What do you want or are you looking for? (Short title shown in lists)'"
                detail-list="self.useCase.seeksDetails"
                initial-draft="self.useCase.draft.seeks"
                on-update="::self.updateDraft(draft, 'seeks')"
                on-scroll="::self.scrollToBottom(element)">
            </won-create-isseeks>

            <won-labelled-hr label="::'Matching Behaviour'" class="cp__content__labelledhr" ng-if="self.useCase.isDetails && self.useCase.seeksDetails"> </won-labelled-hr>

                    Tune Matching Behaviour
                    <svg class="cp__content__tuning__title__carret" ng-show="!self.showTuningOptions">
                        <use xlink:href="#ico16_arrow_down" href="#ico16_arrow_down"></use>
                    </svg>
                    <svg class="cp__content__tuning__title__carret" ng-show="self.showTuningOptions">
                        <use xlink:href="#ico16_arrow_up" href="#ico16_arrow_up"></use>
                    </svg>

                    <won-matching-context-picker
                      ng-if="self.showTuningOptions"
                      default-matching-context="::self.defaultMatchingContext"
                      initial-matching-context="::self.draftObject.matchingContext"
                      on-matching-context-updated="::self.updateMatchingContext(matchingContext)">
                    </won-matching-context-picker>

            <won-labelled-hr label="::'done?'" class="cp__content__labelledhr show-in-responsive"></won-labelled-hr>
            <button type="submit" class="won-button--filled red cp__content__publish show-in-responsive"
                    ng-disabled="!self.isValid()"
                    ng-click="::self.publish()">

                    Publish

                    Publishing …

            </button>

            <won-labelled-hr label="::'done?'" class="cp__footer__labelledhr"></won-labelled-hr>
            <button type="submit" class="won-button--filled red cp__footer__publish"
                    ng-disabled="!self.isValid()"
                    ng-click="::self.publish()">

                    Publish

                    Publishing …

            </button>

    `;

  class Controller {
    constructor(/* arguments <- serviceDependencies */) {
      attach(this, serviceDependencies, arguments);

      this.SEARCH = "search";
      this.POST = "post";

      this.focusedElement = null;
      //TODO debug; deleteme
      window.cnc4dbg = this;

      this.postTypeTexts = postTypeTexts;
      this.characterLimit = postTitleCharacterLimit;

      this.windowHeight = window.screen.height;
      this.scrollContainer().addEventListener("scroll", e => this.onResize(e));

      this.draftObject = {};

      this.showTuningOptions = false;

      this.pendingPublishing = false;
      this.details = { is: [], seeks: [] };
      this.isNew = true;

      const selectFromState = state => {
        const showCreateView = getIn(state, [
          "router",
          "currentParams",
          "showCreateView",
        ]);
        const useCaseString = getIn(state, [
          "router",
          "currentParams",
          "useCase",
        ]);
        const isSearch = showCreateView === this.SEARCH;
        const isPost = showCreateView && !isSearch;

        // needed to be able to reset matching context to default
        // TODO: is there an easier way to do this?
        const defaultMatchingContextList = getIn(state, [
          "config",
          "theme",
          "defaultContext",
        ]);
        const defaultMatchingContext = defaultMatchingContextList
          ? defaultMatchingContextList.toJS()
          : [];

        return {
          connectionHasBeenLost: !selectIsConnected(state),
          showCreateView,
          useCaseString,
          useCase: this.getUseCase(useCaseString),
          isSearch,
          isPost,
          defaultMatchingContext: defaultMatchingContext,
        };
      };

      // TODO: think about how to deal with contexts predefined in usecases
      delay(0).then(() => {
        this.loadInitialDraft();
      });

      // Using actionCreators like this means that every action defined there is available in the template.
      connect2Redux(selectFromState, actionCreators, [], this);
    }

    onResize() {
      //TODO: delete
      //console.log("ResizeEvent: ", window.screen.height);
      if (this.focusedElement) {
        if (this.windowHeight < window.screen.height) {
          this.windowHeight < window.screen.height;
          this.scrollToBottom(this.focusedElement);
        } else {
          this.windowHeight = window.screen.height;
        }
      }
    }

    scrollToBottom(element) {
      this._programmaticallyScrolling = true;

      if (element) {
        let heightHeader =
          this.$element[0].querySelector(".cp__header").offsetHeight + 10;
        let scrollTop = this.$element[0].querySelector(element).offsetTop;
        this.scrollContainer().scrollTop = scrollTop - heightHeader;

        this.focusedElement = element;
        //TODO: debug: delete me
        //console.log("ScrollTop: ", this.scrollContainer().scrollTop);
      }
    }

    scrollContainer() {
      if (!this._scrollContainer) {
        this._scrollContainer = this.$element[0].querySelector(".cp__content");
      }
      return this._scrollContainer;
    }

    getUseCase(useCaseString) {
      if (useCaseString) {
        for (const useCaseName in useCases) {
          if (useCaseString === useCases[useCaseName]["identifier"]) {
            return useCases[useCaseName];
          }
        }
      }
      return undefined;
    }

    toggleTuningOptions() {
      // if (!this.showTuningOptions) {
      //   this.onScroll({ element: ".cis__addDetail__header.b" });
      // }
      this.showTuningOptions = !this.showTuningOptions;
    }

    isValid() {
      const draft = this.draftObject;
      const hasContent = get(draft, "is") || get(draft, "seeks");
      const hasValidIs = this.isOrSeeksIsValid(get(draft, "is"));
      const hasValidSeeks = this.isOrSeeksIsValid(get(draft, "seeks"));
      return (
        !this.connectionHasBeenLost &&
        hasContent &&
        (hasValidIs || hasValidSeeks)
      );
    }

    loadInitialDraft() {
      // just to be sure this is loaded already
      if (!this.useCase) {
        this.getUseCase(this.useCaseString);
      }

      if (this.useCase && this.useCase.draft) {
        // deep clone of draft
        this.draftObject = JSON.parse(JSON.stringify(this.useCase.draft));
      }

      // combine preset matching context with default matching context
      if (this.defaultMatchingContext && this.draftObject.matchingContext) {
        const combinedContext = [
          ...this.defaultMatchingContext,
          ...this.draftObject.matchingContext,
        ].reduce(function(a, b) {
          if (a.indexOf(b) < 0) a.push(b);
          return a;
        }, []);

        this.draftObject.matchingContext = combinedContext;
      } else if (this.defaultMatchingContext) {
        this.draftObject.matchingContext = this.defaultMatchingContext;
      }
    }

    updateMatchingContext(matchingContext) {
      // also accepts []!
      // if (matchingContext && this.draftObject.matchingContext) {
      //   const combinedContext = [
      //     ...matchingContext,
      //     ...this.draftObject.matchingContext,
      //   ].reduce(function(a, b) {
      //     if (a.indexOf(b) < 0) a.push(b);
      //     return a;
      //   }, []);

      //   this.draftObject.matchingContext = combinedContext;
      // } else
      if (matchingContext) {
        this.draftObject.matchingContext = matchingContext;
      }
    }

    updateDraft(updatedDraft, isSeeks) {
      if (this.isNew) {
        this.isNew = false;
      }

      this.draftObject[isSeeks] = updatedDraft;
    }

    publish() {
      // Post both needs
      if (!this.pendingPublishing) {
        this.pendingPublishing = true;

        // TODO: This should be a usecase/done via a different component
        // Check if this is a search
        const searchString = this.checkForSearchString(this.draftObject);
        if (searchString) {
          this.draftObject.searchString = searchString;
          //delete this.draftObject.is;
        }

        if (this.useCase && this.useCase.identifier) {
          this.draftObject.useCase = this.useCase.identifier;
        }

        const draft = this.getPublishObject(this.draftObject);

        this.needs__create(
          draft,
          this.$ngRedux.getState().getIn(["config", "defaultNodeUri"])
        );
      }
    }

    getPublishObject(draft) {
      if (!this.isOrSeeksIsValid(draft.is)) {
        delete draft.is;
      }
      if (!this.isOrSeeksIsValid(draft.seeks)) {
        delete draft.seeks;
      }
      return draft;
    }

    // returns true if the part has a valid title or any other detail
    isOrSeeksIsValid(isOrSeeks) {
      if (!isOrSeeks) {
        return false;
      }

      const title = get(isOrSeeks, "title");
      const hasValidTitle = title && title.length < this.characterLimit;

      let hasDetail = false;
      const details = Object.keys(isOrSeeks);
      for (let d of details) {
        if (isOrSeeks[d] && d !== "type") {
          hasDetail = true;
        }
      }
      return !!(hasValidTitle || hasDetail);
    }

    checkForSearchString(draft) {
      // draft has an is part -> not a pure search
      if (this.isOrSeeksIsValid(draft.is)) {
        return undefined;
      }

      // draft has no valid seeks part -> not a pure search
      if (!draft.seeks || !draft.seeks.title) {
        return undefined;
      }

      for (let detail of Object.keys(draft.seeks)) {
        if (detail !== "title" && detail !== "type" && draft.seeks[detail]) {
          return undefined;
        }
      }

      return draft.seeks.title;
    }

    createWhatsNew() {
      if (!this.pendingPublishing) {
        this.pendingPublishing = true;
        this.needs__whatsNew();
      }
    }
  }

  Controller.$inject = serviceDependencies;

  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      /*scope-isolation*/
    },
    template: template,
  };
}

export default //.controller('CreateNeedController', [...serviceDependencies, CreateNeedController])
angular
  .module("won.owner.components.createPost", [
    labelledHrModule,
    imageDropzoneModule,
    descriptionPickerModule,
    locationPickerModule,
    personPickerModule,
    travelActionPickerModule,
    tagsPickerModule,
    ttlPickerModule,
    createIsseeksModule,
    matchingContextModule,
    ngAnimate,
  ])
  .directive("wonCreatePost", genComponentConf).name;
<commit_msg>Update create-post.js<commit_after>/**
 * Created by ksinger on 24.08.2015.
 */
import angular from "angular";
import ngAnimate from "angular-animate";

import "ng-redux";
import labelledHrModule from "./labelled-hr.js";
import imageDropzoneModule from "./image-dropzone.js";
import matchingContextModule from "./details/matching-context-picker.js"; // TODO: should be renamed
import createIsseeksModule from "./create-isseeks.js";
import { postTitleCharacterLimit } from "config";
import { get, getIn, attach, delay } from "../utils.js";
import { actionCreators } from "../actions/actions.js";
import won from "../won-es6.js";
import { connect2Redux } from "../won-utils.js";
import { selectIsConnected } from "../selectors.js";

// import { details } from "detailDefinitions";
import { useCases } from "useCaseDefinitions";
// TODO: these should be replaced by importing defintions from config
import descriptionPickerModule from "./details/description-picker.js";
import locationPickerModule from "./details/location-picker.js";
import personPickerModule from "./details/person-picker.js";
import travelActionPickerModule from "./details/travel-action-picker.js";
import tagsPickerModule from "./details/tags-picker.js";
import ttlPickerModule from "./details/ttl-picker.js";

const postTypeTexts = [
  {
    type: won.WON.BasicNeedTypeDemand,
    text: "I'm looking for",
    helpText:
      "Select this if you are looking for things or services other people offer",
  },
  {
    type: won.WON.BasicNeedTypeSupply,
    text: "I'm offering",
    helpText:
      "Use this if you are offering an item or a service. You will find people who said" +
      " that they're looking for something.",
  },
  {
    type: won.WON.BasicNeedTypeDotogether,
    text: "I want to find someone to",
    helpText:
      "Select this if you are looking to find other people who share your interest. You will be matched" +
      " with other people who chose this option as well.",
  },
  {
    type: won.WON.BasicNeedTypeCombined,
    text: "I'm offering and looking for",
    helpText:
      "Select this if you are looking for things or services other people offer + Use this if you are offering an item or a service. You will find people who said" +
      " that they're looking for something.",
  },
];

//TODO can't inject $scope with the angular2-router, preventing redux-cleanup
const serviceDependencies = [
  "$ngRedux",
  "$scope",
  "$element" /*'$routeParams' /*injections as strings here*/,
];

function genComponentConf() {
  const template = `

                <svg style="--local-primary:var(--won-primary-color);"
                    class="cp__header__back__icon">
                    <use xlink:href="#ico36_backarrow" href="#ico36_backarrow"></use>
                </svg>

            {{self.useCase.label}}

            <won-labelled-hr label="::'Offering / Is'" class="cp__content__labelledhr" ng-if="self.useCase.isDetails && self.useCase.seeksDetails"> </won-labelled-hr>
            <won-create-isseeks
                ng-if="self.useCase.isDetails"
                is-or-seeks="::'Description'"
                title-placeholder="::'What do you offer or propose? (Short title shown in lists)'"
                detail-list="self.useCase.isDetails"
                initial-draft="self.useCase.draft.is"
                on-update="::self.updateDraft(draft, 'is')"
                on-scroll="::self.scrollToBottom(element)">
            </won-create-isseeks>
            <won-labelled-hr label="::'Want / Looking For'" class="cp__content__labelledhr" ng-if="self.useCase.isDetails && self.useCase.seeksDetails"> </won-labelled-hr>
            <won-create-isseeks
                ng-if="self.useCase.seeksDetails"
                is-or-seeks="::'Search'"
                title-placeholder="::'What do you want or are you looking for? (Short title shown in lists)'"
                detail-list="self.useCase.seeksDetails"
                initial-draft="self.useCase.draft.seeks"
                on-update="::self.updateDraft(draft, 'seeks')"
                on-scroll="::self.scrollToBottom(element)">
            </won-create-isseeks>

            <won-labelled-hr label="::'Matching Behaviour'" class="cp__content__labelledhr" ng-if="self.useCase.isDetails || self.useCase.seeksDetails"> </won-labelled-hr>

                    Tune Matching Behaviour
                    <svg class="cp__content__tuning__title__carret" ng-show="!self.showTuningOptions">
                        <use xlink:href="#ico16_arrow_down" href="#ico16_arrow_down"></use>
                    </svg>
                    <svg class="cp__content__tuning__title__carret" ng-show="self.showTuningOptions">
                        <use xlink:href="#ico16_arrow_up" href="#ico16_arrow_up"></use>
                    </svg>

                    <won-matching-context-picker
                      ng-if="self.showTuningOptions"
                      default-matching-context="::self.defaultMatchingContext"
                      initial-matching-context="::self.draftObject.matchingContext"
                      on-matching-context-updated="::self.updateMatchingContext(matchingContext)">
                    </won-matching-context-picker>

            <won-labelled-hr label="::'done?'" class="cp__content__labelledhr show-in-responsive"></won-labelled-hr>
            <button type="submit" class="won-button--filled red cp__content__publish show-in-responsive"
                    ng-disabled="!self.isValid()"
                    ng-click="::self.publish()">

                    Publish

                    Publishing …

            </button>

            <won-labelled-hr label="::'done?'" class="cp__footer__labelledhr"></won-labelled-hr>
            <button type="submit" class="won-button--filled red cp__footer__publish"
                    ng-disabled="!self.isValid()"
                    ng-click="::self.publish()">

                    Publish

                    Publishing …

            </button>

    `;

  class Controller {
    constructor(/* arguments <- serviceDependencies */) {
      attach(this, serviceDependencies, arguments);

      this.SEARCH = "search";
      this.POST = "post";

      this.focusedElement = null;
      //TODO debug; deleteme
      window.cnc4dbg = this;

      this.postTypeTexts = postTypeTexts;
      this.characterLimit = postTitleCharacterLimit;

      this.windowHeight = window.screen.height;
      this.scrollContainer().addEventListener("scroll", e => this.onResize(e));

      this.draftObject = {};

      this.showTuningOptions = false;

      this.pendingPublishing = false;
      this.details = { is: [], seeks: [] };
      this.isNew = true;

      const selectFromState = state => {
        const showCreateView = getIn(state, [
          "router",
          "currentParams",
          "showCreateView",
        ]);
        const useCaseString = getIn(state, [
          "router",
          "currentParams",
          "useCase",
        ]);
        const isSearch = showCreateView === this.SEARCH;
        const isPost = showCreateView && !isSearch;

        // needed to be able to reset matching context to default
        // TODO: is there an easier way to do this?
        const defaultMatchingContextList = getIn(state, [
          "config",
          "theme",
          "defaultContext",
        ]);
        const defaultMatchingContext = defaultMatchingContextList
          ? defaultMatchingContextList.toJS()
          : [];

        return {
          connectionHasBeenLost: !selectIsConnected(state),
          showCreateView,
          useCaseString,
          useCase: this.getUseCase(useCaseString),
          isSearch,
          isPost,
          defaultMatchingContext: defaultMatchingContext,
        };
      };

      // TODO: think about how to deal with contexts predefined in usecases
      delay(0).then(() => {
        this.loadInitialDraft();
      });

      // Using actionCreators like this means that every action defined there is available in the template.
      connect2Redux(selectFromState, actionCreators, [], this);
    }

    onResize() {
      //TODO: delete
      //console.log("ResizeEvent: ", window.screen.height);
      if (this.focusedElement) {
        if (this.windowHeight < window.screen.height) {
          this.windowHeight < window.screen.height;
          this.scrollToBottom(this.focusedElement);
        } else {
          this.windowHeight = window.screen.height;
        }
      }
    }

    scrollToBottom(element) {
      this._programmaticallyScrolling = true;

      if (element) {
        let heightHeader =
          this.$element[0].querySelector(".cp__header").offsetHeight + 10;
        let scrollTop = this.$element[0].querySelector(element).offsetTop;
        this.scrollContainer().scrollTop = scrollTop - heightHeader;

        this.focusedElement = element;
        //TODO: debug: delete me
        //console.log("ScrollTop: ", this.scrollContainer().scrollTop);
      }
    }

    scrollContainer() {
      if (!this._scrollContainer) {
        this._scrollContainer = this.$element[0].querySelector(".cp__content");
      }
      return this._scrollContainer;
    }

    getUseCase(useCaseString) {
      if (useCaseString) {
        for (const useCaseName in useCases) {
          if (useCaseString === useCases[useCaseName]["identifier"]) {
            return useCases[useCaseName];
          }
        }
      }
      return undefined;
    }

    toggleTuningOptions() {
      // if (!this.showTuningOptions) {
      //   this.onScroll({ element: ".cis__addDetail__header.b" });
      // }
      this.showTuningOptions = !this.showTuningOptions;
    }

    isValid() {
      const draft = this.draftObject;
      const hasContent = get(draft, "is") || get(draft, "seeks");
      const hasValidIs = this.isOrSeeksIsValid(get(draft, "is"));
      const hasValidSeeks = this.isOrSeeksIsValid(get(draft, "seeks"));
      return (
        !this.connectionHasBeenLost &&
        hasContent &&
        (hasValidIs || hasValidSeeks)
      );
    }

    loadInitialDraft() {
      // just to be sure this is loaded already
      if (!this.useCase) {
        this.getUseCase(this.useCaseString);
      }

      if (this.useCase && this.useCase.draft) {
        // deep clone of draft
        this.draftObject = JSON.parse(JSON.stringify(this.useCase.draft));
      }

      // combine preset matching context with default matching context
      if (this.defaultMatchingContext && this.draftObject.matchingContext) {
        const combinedContext = [
          ...this.defaultMatchingContext,
          ...this.draftObject.matchingContext,
        ].reduce(function(a, b) {
          if (a.indexOf(b) < 0) a.push(b);
          return a;
        }, []);

        this.draftObject.matchingContext = combinedContext;
      } else if (this.defaultMatchingContext) {
        this.draftObject.matchingContext = this.defaultMatchingContext;
      }
    }

    updateMatchingContext(matchingContext) {
      // also accepts []!
      // if (matchingContext && this.draftObject.matchingContext) {
      //   const combinedContext = [
      //     ...matchingContext,
      //     ...this.draftObject.matchingContext,
      //   ].reduce(function(a, b) {
      //     if (a.indexOf(b) < 0) a.push(b);
      //     return a;
      //   }, []);

      //   this.draftObject.matchingContext = combinedContext;
      // } else
      if (matchingContext) {
        this.draftObject.matchingContext = matchingContext;
      }
    }

    updateDraft(updatedDraft, isSeeks) {
      if (this.isNew) {
        this.isNew = false;
      }

      this.draftObject[isSeeks] = updatedDraft;
    }

    publish() {
      // Post both needs
      if (!this.pendingPublishing) {
        this.pendingPublishing = true;

        // TODO: This should be a usecase/done via a different component
        // Check if this is a search
        const searchString = this.checkForSearchString(this.draftObject);
        if (searchString) {
          this.draftObject.searchString = searchString;
          //delete this.draftObject.is;
        }

        if (this.useCase && this.useCase.identifier) {
          this.draftObject.useCase = this.useCase.identifier;
        }

        const draft = this.getPublishObject(this.draftObject);

        this.needs__create(
          draft,
          this.$ngRedux.getState().getIn(["config", "defaultNodeUri"])
        );
      }
    }

    getPublishObject(draft) {
      if (!this.isOrSeeksIsValid(draft.is)) {
        delete draft.is;
      }
      if (!this.isOrSeeksIsValid(draft.seeks)) {
        delete draft.seeks;
      }
      return draft;
    }

    // returns true if the part has a valid title or any other detail
    isOrSeeksIsValid(isOrSeeks) {
      if (!isOrSeeks) {
        return false;
      }

      const title = get(isOrSeeks, "title");
      const hasValidTitle = title && title.length < this.characterLimit;

      let hasDetail = false;
      const details = Object.keys(isOrSeeks);
      for (let d of details) {
        if (isOrSeeks[d] && d !== "type") {
          hasDetail = true;
        }
      }
      return !!(hasValidTitle || hasDetail);
    }

    checkForSearchString(draft) {
      // draft has an is part -> not a pure search
      if (this.isOrSeeksIsValid(draft.is)) {
        return undefined;
      }

      // draft has no valid seeks part -> not a pure search
      if (!draft.seeks || !draft.seeks.title) {
        return undefined;
      }

      for (let detail of Object.keys(draft.seeks)) {
        if (detail !== "title" && detail !== "type" && draft.seeks[detail]) {
          return undefined;
        }
      }

      return draft.seeks.title;
    }

    createWhatsNew() {
      if (!this.pendingPublishing) {
        this.pendingPublishing = true;
        this.needs__whatsNew();
      }
    }
  }

  Controller.$inject = serviceDependencies;

  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      /*scope-isolation*/
    },
    template: template,
  };
}

export default //.controller('CreateNeedController', [...serviceDependencies, CreateNeedController])
angular
  .module("won.owner.components.createPost", [
    labelledHrModule,
    imageDropzoneModule,
    descriptionPickerModule,
    locationPickerModule,
    personPickerModule,
    travelActionPickerModule,
    tagsPickerModule,
    ttlPickerModule,
    createIsseeksModule,
    matchingContextModule,
    ngAnimate,
  ])
  .directive("wonCreatePost", genComponentConf).name;
<|endoftext|>


<commit_before>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import 'babel-polyfill';

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';

// Import root app
import App from 'containers/App';

// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */

import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import CSS reset and Global Styles
import './global-styles';

// Import root routes
import createRoutes from './routes';

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: makeSelectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';

injectTapEventPlugin();

const render = (messages) => {
  ReactDOM.render(
    <MuiThemeProvider muiTheme={getMuiTheme()}>
      <Provider store={store}>
        <LanguageProvider messages={messages}>
          <Router
            history={history}
            routes={rootRoute}
            render={
              // Scroll to top when going to a new page, imitating default browser
              // behaviour
              applyRouterMiddleware(useScroll())
            }
          />
        </LanguageProvider>
      </Provider>
    </MuiThemeProvider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
<commit_msg>configure material-ui<commit_after>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */

// Needed for redux-saga es6 generator support
import 'babel-polyfill';

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';

// Import root app
import App from 'containers/App';

// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';

// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';

// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */

import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import CSS reset and Global Styles
import './global-styles';

// Import root routes
import createRoutes from './routes';

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: makeSelectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

injectTapEventPlugin();

const render = (messages) => {
  ReactDOM.render(
    <MuiThemeProvider muiTheme={getMuiTheme()}>
      <Provider store={store}>
        <LanguageProvider messages={messages}>
          <Router
            history={history}
            routes={rootRoute}
            render={
              // Scroll to top when going to a new page, imitating default browser
              // behaviour
              applyRouterMiddleware(useScroll())
            }
          />
        </LanguageProvider>
      </Provider>
    </MuiThemeProvider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(import('intl'));
  }))
    .then(() => Promise.all([
      import('intl/locale-data/jsonp/en.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
  require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
<|endoftext|>


<commit_before>const fs = require('fs')
const { join } = require('path')
const express = require('express')
const router = express.Router()

const tmpDir = join(__dirname, '..', '..', 'tmp')
const templatesDir = join(__dirname, '..', 'api', 'templates')

router.use(require('cookie-parser')())
router.use(require('body-parser').json({ limit: '10mb' }))

router.get('/:layout/:theme/:owner/:name/:dir/:asset', (req, res) => {
  const { owner, name, dir, asset } = req.params
  res.setHeader('Cache-Control', 'no-cache')
  res.sendFile(join(tmpDir, owner, name, dir, asset))
})

router.get('/:layout/:theme/:owner/:name/:asset?', (req, res) => {
  const { layout, theme, owner, name, asset } = req.params
  const dir = join(tmpDir, owner, name)

  if (!fs.existsSync(dir)) {
    return res.status(404).send('Project does not exist.')
  }

  // ensure trailing slash exists after project name
  // so asset requests are constructed properly
  if (!asset && !req.path.endsWith('/')) {
    return res.redirect(301, req.originalUrl + '/')
  }

  res.setHeader('Cache-Control', 'no-cache')
  if (asset === 'styles.css') {
    const layoutCSS = fs.readFileSync(
      join(templatesDir, 'layouts', `${layout}.css`),
    )
    const themeCSS = fs.readFileSync(
      join(templatesDir, 'themes', `${theme}.css`),
    )
    res.type('css').send([layoutCSS, themeCSS].join('\n'))
  } else {
    res.sendFile(join(dir, asset || 'index.html'))
  }
})

module.exports = router
<commit_msg>Code clean up/comment<commit_after>const { existsSync, readFileSync: rfs } = require('fs')
const { join } = require('path')
const express = require('express')
const router = express.Router()

const tmpDir = join(__dirname, '..', '..', 'tmp')
const templatesDir = join(__dirname, '..', 'api', 'templates')

router.use(require('cookie-parser')())
router.use(require('body-parser').json({ limit: '10mb' }))

router.get('/:layout/:theme/:owner/:name/:dir/:asset', (req, res) => {
  const { owner, name, dir, asset } = req.params
  res.setHeader('Cache-Control', 'no-cache')
  res.sendFile(join(tmpDir, owner, name, dir, asset))
})

router.get('/:layout/:theme/:owner/:name/:asset?', (req, res) => {
  const { layout, theme, owner, name, asset } = req.params
  const dir = join(tmpDir, owner, name)

  if (!existsSync(dir)) {
    return res.status(404).send('Project does not exist.')
  }

  // ensure trailing slash exists after project name
  // so asset requests are constructed properly
  if (!asset && !req.path.endsWith('/')) {
    return res.redirect(301, req.originalUrl + '/')
  }

  res.setHeader('Cache-Control', 'no-cache')
  // dynamically construct and send CSS based on URL
  if (asset === 'styles.css') {
    res
      .type('css')
      .send(
        [
          rfs(join(templatesDir, 'layouts', `${layout}.css`)),
          rfs(join(templatesDir, 'themes', `${theme}.css`)),
        ].join('\n'),
      )
  } else {
    res.sendFile(join(dir, asset || 'index.html'))
  }
})

module.exports = router
<|endoftext|>