<commit_before>import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import styled from 'styled-components';

import Button from '../../shared/Button';
import Dropdown from '../../shared/Dropdown';
import Emojify from '../../shared/Emojify';
import Icon from '../../shared/Icon';

import CreateBuildDialog from '../CreateBuildDialog';
import Builds from './builds';

import permissions from '../../../lib/permissions';
import { repositoryProviderIcon } from '../../../lib/repositories';

const HeaderVitals = styled.div.attrs({
  className: 'flex flex-auto items-center my2'
})`
  flex-basis: 100%;

  @media (min-width: 768px) {
    flex-basis: 320px;
  }
`;

const HeaderBuilds = styled(Builds)`
  flex: 1 1 auto;
  margin-bottom: 5px;

  @media (min-width: 768px) {
    margin-left: 10px;
  }

  @media (min-width: 768px) and (max-width: 991px) {
    order: 3;
  }

  @media (min-width: 992px) {
    flex: 0 1 auto;
    margin-bottom: 0;
  }
`;

class Header extends React.Component {
  static propTypes = {
    pipeline: PropTypes.object.isRequired,
    buildState: PropTypes.string
  };

  state = {
    showingActionsDropdown: false,
    showingCreateBuildDialog: false
  };

  componentWillMount() {
    if (window.location.hash.split('?').shift() === '#new') {
      this.setState({
        showingCreateBuildDialog: true
      });
    }
  }

  render() {
    const actions = this.getAvailableActions();

    return (

          <HeaderVitals>

                  <Emojify text={this.props.pipeline.name} />

                  {this.renderDescription()}

            {this.renderProviderBadge()}
            {this.renderDropdownForActions(actions)}
          </HeaderVitals>
          <HeaderBuilds
            pipeline={this.props.pipeline}
            buildState={this.props.buildState}
          />
          {this.renderButtonsForActions(actions)}

        <CreateBuildDialog
          isOpen={this.state.showingCreateBuildDialog}
          onRequestClose={this.handleCreateBuildDialogClose}
          pipeline={this.props.pipeline}
        />

    );
  }

  renderProviderBadge() {
    const uri = this.props.pipeline.repository.provider.url;

    if (!uri) {
      return null;
    }

    return (

        <Icon
          title={uri}
          icon={repositoryProviderIcon(this.props.pipeline.repository.provider.__typename)}
        />

    );
  }

  getAvailableActions() {
    // NOTE: We "render" props here so we can show near-identical
    // action lists in the dropdown and header. `children` is assumed
    // to be any renderable thing. Have at it!
    return permissions(this.props.pipeline.permissions).collect(
      {
        allowed: "buildCreate",
        render: () => ({
          key: 'newBuild',
          onClick: this.handleBuildCreateClick,
          children: 'New Build'
        })
      },
      {
        allowed: "pipelineUpdate",
        render: () => ({
          key: 'pipelineSettings',
          href: `${this.props.pipeline.url}/settings`,
          children: 'Pipeline Settings'
        })
      }
    );
  }

  renderDropdownForActions(actions) {
    if (actions.length < 1) {
      return;
    }

    const content = actions.map(({ key, ...action }) => (

    ));

    return (
      <Dropdown
        className="sm-hide md-hide lg-hide"
        width={200}
        ref={(_actionsDropdown) => this._actionsDropdown = _actionsDropdown}
        onToggle={this.handleActionsDropdownToggle}
      >
        <Button
          outline={true}
          theme="default"
          className={classNames({ lime: this.state.showingActionsDropdown })}
          iconOnly={true}
        >
          <Icon icon="down-triangle" style={{ width: 7, height: 7 }} className="flex-none" />
        </Button>
        {content}
      </Dropdown>
    );
  }

  renderButtonsForActions(actions) {
    if (actions.length < 1) {
      return;
    }

    const content = actions.map(({ key, ...action }) => (
      <Button
        key={key}
        outline={true}
        theme="default"
        className="ml2 flex items-center"
        {...action}
      />
    ));

    return (

        {content}

    );
  }

  renderDescription() {
    const { pipeline } = this.props;

    if (pipeline.description) {
      return <Emojify text={pipeline.description} />;
    }

    // Hide passwords and limit to 8 dots in repository URLs
    return pipeline.repository.url.replace(
      /:([^\/@]{1,8})[^\/@]*@/,
      (match, password) => `:${password.replace(/./g, '•')}@`
    );
  }

  handleActionsDropdownToggle = (visible) => {
    this.setState({ showingActionsDropdown: visible });
  };

  handleBuildCreateClick = () => {
    if (this.state.showingActionsDropdown) {
      this._actionsDropdown.setShowing(false);
    }

    this.setState({ showingCreateBuildDialog: true });
  };

  handleCreateBuildDialogClose = () => {
    this.setState({ showingCreateBuildDialog: false });
  };
}

export default Relay.createContainer(Header, {
  fragments: {
    pipeline: () => Relay.QL`
      fragment on Pipeline {
        ${CreateBuildDialog.getFragment('pipeline')}
        ${Builds.getFragment('pipeline')}
        id
        name
        url
        description
        repository {
          url
          provider {
            __typename
            url
          }
        }
        permissions {
          pipelineUpdate {
            allowed
            code
            message
          }
          buildCreate {
            allowed
            code
            message
          }
        }
      }
    `
  }
});
<commit_msg>PipelineHeader: Org name for anonymous users<commit_after>// @flow

import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import styled from 'styled-components';

import Button from '../../shared/Button';
import Dropdown from '../../shared/Dropdown';
import Emojify from '../../shared/Emojify';
import Icon from '../../shared/Icon';

import CreateBuildDialog from '../CreateBuildDialog';
import Builds from './builds';

import permissions from '../../../lib/permissions';
import { repositoryProviderIcon } from '../../../lib/repositories';

const HeaderVitals = styled.div.attrs({
  className: 'flex flex-auto items-center my2'
})`
  flex-basis: 100%;

  @media (min-width: 768px) {
    flex-basis: 320px;
  }
`;

const HeaderBuilds = styled(Builds)`
  flex: 1 1 auto;
  margin-bottom: 5px;

  @media (min-width: 768px) {
    margin-left: 10px;
  }

  @media (min-width: 768px) and (max-width: 991px) {
    order: 3;
  }

  @media (min-width: 992px) {
    flex: 0 1 auto;
    margin-bottom: 0;
  }
`;

type Props = {
  pipeline: Object,
  viewer?: {
    id: string
  },
  buildState?: string
};

type State = {
  showingActionsDropdown: boolean,
  showingCreateBuildDialog: boolean
};

class Header extends React.Component<Props, State> {
  static propTypes = {
    pipeline: PropTypes.object.isRequired,
    viewer: PropTypes.object,
    buildState: PropTypes.string
  };

  state = {
    showingActionsDropdown: false,
    showingCreateBuildDialog: false
  };

  actionsDropdown: ?Dropdown;

  componentWillMount() {
    if (window.location.hash.split('?').shift() === '#new') {
      this.setState({
        showingCreateBuildDialog: true
      });
    }
  }

  render() {
    const actions = this.getAvailableActions();

    return (

          <HeaderVitals>

                {this.renderPipelineName()}

                  {this.renderDescription()}

            {this.renderProviderBadge()}
            {this.renderDropdownForActions(actions)}
          </HeaderVitals>
          <HeaderBuilds
            pipeline={this.props.pipeline}
            buildState={this.props.buildState}
          />
          {this.renderButtonsForActions(actions)}

        <CreateBuildDialog
          isOpen={this.state.showingCreateBuildDialog}
          onRequestClose={this.handleCreateBuildDialogClose}
          pipeline={this.props.pipeline}
        />

    );
  }

  renderPipelineName() {
    const isAnonymous = !this.props.viewer;

    return (

        {isAnonymous && <Emojify text={this.props.pipeline.organization.name} />}
        {isAnonymous &&  / }
        <Emojify text={this.props.pipeline.name} />

    );
  }

  renderProviderBadge() {
    const uri = this.props.pipeline.repository.provider.url;

    if (!uri) {
      return null;
    }

    return (

        <Icon
          title={uri}
          icon={repositoryProviderIcon(this.props.pipeline.repository.provider.__typename)}
        />

    );
  }

  getAvailableActions() {
    // NOTE: We "render" props here so we can show near-identical
    // action lists in the dropdown and header. `children` is assumed
    // to be any renderable thing. Have at it!
    return permissions(this.props.pipeline.permissions).collect(
      {
        allowed: "buildCreate",
        render: () => ({
          key: 'newBuild',
          onClick: this.handleBuildCreateClick,
          children: 'New Build'
        })
      },
      {
        allowed: "pipelineUpdate",
        render: () => ({
          key: 'pipelineSettings',
          href: `${this.props.pipeline.url}/settings`,
          children: 'Pipeline Settings'
        })
      }
    );
  }

  renderDropdownForActions(actions) {
    if (actions.length < 1) {
      return;
    }

    const content = actions.map(({ key, ...action }) => (

    ));

    return (
      <Dropdown
        className="sm-hide md-hide lg-hide"
        width={200}
        ref={(actionsDropdown) => this.actionsDropdown = actionsDropdown}
        onToggle={this.handleActionsDropdownToggle}
      >
        <Button
          outline={true}
          theme="default"
          className={classNames({ lime: this.state.showingActionsDropdown })}
          iconOnly={true}
        >
          <Icon icon="down-triangle" style={{ width: 7, height: 7 }} className="flex-none" />
        </Button>
        {content}
      </Dropdown>
    );
  }

  renderButtonsForActions(actions) {
    if (actions.length < 1) {
      return;
    }

    const content = actions.map(({ key, ...action }) => (
      <Button
        key={key}
        outline={true}
        theme="default"
        className="ml2 flex items-center"
        {...action}
      />
    ));

    return (

        {content}

    );
  }

  renderDescription() {
    const { pipeline } = this.props;

    if (pipeline.description) {
      return <Emojify text={pipeline.description} />;
    }

    // Hide passwords and limit to 8 dots in repository URLs
    return pipeline.repository.url.replace(
      /:([^\/@]{1,8})[^\/@]*@/,
      (match, password) => `:${password.replace(/./g, '•')}@`
    );
  }

  handleActionsDropdownToggle = (visible) => {
    this.setState({ showingActionsDropdown: visible });
  };

  handleBuildCreateClick = () => {
    if (this.state.showingActionsDropdown && this.actionsDropdown) {
      this.actionsDropdown.setShowing(false);
    }

    this.setState({ showingCreateBuildDialog: true });
  };

  handleCreateBuildDialogClose = () => {
    this.setState({ showingCreateBuildDialog: false });
  };
}

export default Relay.createContainer(Header, {
  fragments: {
    pipeline: () => Relay.QL`
      fragment on Pipeline {
        ${CreateBuildDialog.getFragment('pipeline')}
        ${Builds.getFragment('pipeline')}
        id
        name
        url
        description
        organization {
          name
        }
        repository {
          url
          provider {
            __typename
            url
          }
        }
        permissions {
          pipelineUpdate {
            allowed
            code
            message
          }
          buildCreate {
            allowed
            code
            message
          }
        }
      }
    `,
    viewer: () => Relay.QL`
      fragment on Viewer {
        __typename
      }
    `
  }
});
<|endoftext|>


<commit_before>/*
    Copyright 2012 Jaycliff Arcilla of Eversun Software Philippines Corporation (Davao branch)

    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.
*/

/*

    SoundBrix: Experimental HTML5 Sound Object Creation Library powered by Web Audio API (Version 1.3 - 06/30/2014)
    Author: Jaycliff Arcilla

    This library was created to provide sweet audio fallback options when crap happens (Flash Epic Fail).
    Moreover, my previous AoV client (Nigel S. Ball) is reasonably allergic to Flash, making this a perfect non-Flash audio solution for his websites.

    UPDATES:

    * v1.3 (06/30/2014) Refactored the sound object creation process and made several optimizations regarding the channel-switching playback of buffers
    * v1.2 (05/19/2014) Refactored checking for AudioContext constructor. Several optimizations.
    * v1.1 (09/05/2012) Made several enhancements to the creation process. Added gain nodes per sound source. Fixed volume setting method.
    * v1.0 (02/22/2012) Initial release.

    NOTES:

    * AudioBufferSourceNode can only be played once. To play another sound of the same source, another AudioBufferSourceNode must be created, which is stupid.
    * Callbacks MUST be set off using a timer (setTimeout) so as not to wait for the callback to finish executing to proceed with the next statements.

    ISSUES:

    * A gain node cannot accept new inputs starting from when the sound sources start playing. To counter this, a separate gain node for each sound source must be created. However, audio_context.destination doesn't seem to have this limitation.

    Passed JSLint checking! (http://www.jslint.com/)

    JSLINT OPTIONS:

    * Assume console, alert, ...
    * Assume a browser

*/

var SOUNDBRIX;
(function (global) {
    "use strict";
    var hasAudioContext,
        noop,
        loadSound,
        mergeSettings,
        soundbrix_audio_context;
    if (typeof SOUNDBRIX === "object" && typeof SOUNDBRIX.audioContext === "function") {
        console.log('An instance of SoundBrix already exists.');
        return;
    }
    (function hasAudioContextSetup() {
        var vendor_prefixes = ['ms', 'moz', 'webkit', 'o'], audio_context_string = 'AudioContext';
        hasAudioContext = function hasAudioContext() {
            var entry,
                length,
                x;
            if (!global.AudioContext) {
                length = vendor_prefixes.length;
                for (x = 0; x < length; x += 1) {
                    entry = global[vendor_prefixes[x] + audio_context_string];
                    if (typeof entry === "function") {
                        global.AudioContext = entry;
                        return true;
                    }
                }
                return false;
            }
            return true;
        };
    }());
    if (hasAudioContext()) {
        noop = function noop() {
            return;
        };
        soundbrix_audio_context = new global.AudioContext();
    } else {
        console.log("This host doesn't have a Web Audio API implementation.");
        return;
    }
    loadSound = function loadSound(url, callback) {
        var request = new XMLHttpRequest();
        // Load sound synchronously (the 'false' flag), 'true' means asynchronous
        // Avoid using synchronous operations in JavaScript
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';
        request.addEventListener('load', function () { callback(request.response); }, false);
        request.send();
    };
    // ds and us mean 'default settings' and 'user settings', respectively. Now you know. - Manny
    mergeSettings = function mergeSettings(ds, us) {
        var key, temp = {};
        for (key in ds) {
            if (ds.hasOwnProperty(key)) {
                temp[key] = ds[key];
            }
        }
        for (key in us) {
            if (us.hasOwnProperty(key)) {
                temp[key] = us[key];
            }
        }
        return temp;
    };
    (function soundBrixSetup() {
        var max_gain = 100, default_settings = {
            exp: false,
            loop: false,
            playback_rate: 1,
            gain: 100,
            max_channels: 1
        };
        // Type1 sound instances allow multiple instances to be played, but can't be stopped.
        function Type1(settings) {
            var that = this, gain_rate = settings.gain / max_gain, curve = gain_rate * gain_rate;
            function setMethods() {
                that.playSound = function playSound() {
                    var channel, gainNode;
                    channel = soundbrix_audio_context.createBufferSource();
                    channel.buffer = that.audio_buffer;
                    channel.loop = settings.loop;
                    channel.playbackRate.value = settings.playback_rate;
                    if (typeof soundbrix_audio_context.createGain !== "function") {
                        channel.connect(soundbrix_audio_context.destination);
                    } else {
                        gainNode = soundbrix_audio_context.createGain();
                        gainNode.connect(soundbrix_audio_context.destination);
                        // Using x * x curve to smooth out transition
                        gainNode.gain.value = curve;
                        channel.connect(gainNode);
                    }
                    if (typeof channel.start === "function") {
                        channel.start(0);
                    }
                };
                that.setVolume = function setVolume(value) {
                    var fraction;
                    if (value > max_gain) { value = max_gain; }
                    fraction = value / max_gain;
                    // Using x * x curve to smooth out transition
                    settings.gain = value;
                    curve = fraction * fraction;
                };
                that.setPlaybackRate = function setPlaybackRate(value) {
                    settings.playback_rate = value;
                };
            }
            function loadSuccess(buffer) {
                // This block will run when the buffer has been decoded. Insert all remaining sound object code here
                // For some instances, the createBuffer method is preferred over decodeAudioData to forcibly decode the buffer without waiting for callbacks
                //that.audio_buffer = soundbrix_audio_context.createBuffer(request.response, false);
                that.audio_buffer = buffer;
                setMethods();
                // The callback MUST be set off using a timer (setTimeout) so as not to wait for the callback to finish executing to proceed with the next statements
                if (typeof settings.callback === "function") { setTimeout(settings.callback, 0); }
            }
            function loadFail() {
                throw new Error('Failed to load source from ' + settings.source);
            }
            function loadCallback(response) {
                soundbrix_audio_context.decodeAudioData(response, loadSuccess, loadFail);
            }
            that.playSound = noop;
            that.stopSound = function stopSound() {
                console.log('This sound object cannot be stopped manually.');
                return;
            };
            that.setVolume = noop;
            that.setPlaybackRate = noop;
            loadSound(settings.source, loadCallback);
        }
        // Type2 sound instances utilize 'channels' to allow multiple instances of a sound source to be played.
        // Also, it's stoppable (stopSound)
        function Type2(settings) {
            var that = this, gainNode = [], gain_rate = settings.gain / max_gain, curve = gain_rate * gain_rate;
            that.channel_busy = [];
            that.source_channels = {};
            that.current_sound_channel = 0;
            that.audio_buffer = null;
            that.is_playing = false;
            // Sneakily increment the number of channels by one to provide a 'buffer' for setting up a new sound source. See the sound channel lag fix inside the that.playSound method
            //settings.max_channels += 1;
            function createChannels() {
                var i;
                for (i = 0; i < settings.max_channels; i += 1) {
                    that.source_channels[i] = soundbrix_audio_context.createBufferSource();
                    that.source_channels[i].buffer = that.audio_buffer;
                    that.source_channels[i].loop = settings.loop;
                    that.source_channels[i].playbackRate.value = settings.playback_rate;
                    if (typeof soundbrix_audio_context.createGain !== "function") {
                        console.log('No gain nodes.');
                        console.log(soundbrix_audio_context);
                        that.source_channels[i].connect(soundbrix_audio_context.destination);
                    } else {
                        gainNode[i] = soundbrix_audio_context.createGain();
                        // Using x * x curve to smooth out transition
                        gainNode[i].gain.value = curve;
                        that.source_channels[i].connect(gainNode[i]);
                        gainNode[i].connect(soundbrix_audio_context.destination);
                    }
                    that.channel_busy[i] = false;
                }
            }
            function setMethods() {
                that.playSound = function playSound() {
                    that.is_playing = true;
                    if (that.channel_busy[that.current_sound_channel]) {
                        that.current_sound_channel += 1;
                        if (that.current_sound_channel === settings.max_channels) {
                            that.current_sound_channel = 0;
                        }
                    }
                    if (typeof that.source_channels[that.current_sound_channel].start === "function") {
                        that.source_channels[that.current_sound_channel].start(0);
                    }
                    that.channel_busy[that.current_sound_channel] = true;
                    /*

                        The solution below fixes sound-playing lag caused by some latency when creating new AudioBufferSourceNode (via the context.createBufferSource() method)
                        Basically it re-initializes the sound channel following the current one to prepare the nextchannel for playback (and somewhat avoiding the said latency)

                    */
                    // Start sound channel lag fix
                    var next_channel;
                    next_channel = that.current_sound_channel + 1;
                    if (next_channel === settings.max_channels) {
                        next_channel = 0;
                    }
                    if (that.channel_busy[next_channel]) {
                        //if (that.source_channels[next_channel].stop !== undefined) { that.source_channels[next_channel].stop(0); }
                        // Simply replace the next busy channel with a new one. The old one will keep on playing and will eventually be collected.
                        that.source_channels[next_channel] = soundbrix_audio_context.createBufferSource();
                        that.source_channels[next_channel].buffer = that.audio_buffer;
                        that.source_channels[next_channel].loop = settings.loop;
                        that.source_channels[next_channel].playbackRate.value = settings.playback_rate;
                        if (typeof soundbrix_audio_context.createGain !== "function") {
                            that.source_channels[next_channel].connect(soundbrix_audio_context.destination);
                        } else {
                            gainNode[next_channel] = soundbrix_audio_context.createGain();
                            gainNode[next_channel].gain.value = curve;
                            that.source_channels[next_channel].connect(gainNode[next_channel]);
                            gainNode[next_channel].connect(soundbrix_audio_context.destination);
                        }
                        that.channel_busy[next_channel] = false;
                    }
                    // End sound channel lag fix
                };
                that.stopSound = function stopSound() {
                    var i;
                    if (that.is_playing) {
                        that.is_playing = false;
                        for (i = 0; i < settings.max_channels; i += 1) {
                            if (that.source_channels[i].stop !== undefined) {
                                // Let's check first if the current channel is 'busy' before calling stop. Why? Because Chrome throws an error when calling stop on unplayed buffer sources.
                                if (that.channel_busy[i]) {
                                    that.source_channels[i].stop(0);
                                }
                            }
                        }
                        createChannels();
                    }
                };
                that.setVolume = function setVolume(value) {
                    var fraction, i;
                    if (value > max_gain) { value = max_gain; }
                    fraction = value / max_gain;
                    // Using x * x curve to smooth out transition
                    settings.gain = value;
                    curve = fraction * fraction;
                    for (i = 0; i < gainNode.length; i += 1) {
                        gainNode[i].gain.value = curve;
                    }
                };
                that.setPlaybackRate = function setPlaybackRate(value) {
                    var i;
                    settings.playback_rate = value;
                    for (i = 0; i < settings.max_channels; i += 1) {
                        that.source_channels[i].playbackRate.value = value;
                    }
                };
            }
            function loadSuccess(buffer) {
                // This block will run when the buffer has been decoded. Insert all remaining sound object code here
                // For some instances, the createBuffer method is preferred over decodeAudioData to forcibly decode the buffer without waiting for callbacks
                //that.audio_buffer = soundbrix_audio_context.createBuffer(request.response, false);
                that.audio_buffer = buffer;
                createChannels();
                //console.log(that.source_channels[0]);
                setMethods();
                // The callback MUST be set off using a timer (setTimeout) so as not to wait for the callback to finish executing to proceed with the next statements
                if (typeof settings.callback === "function") { setTimeout(settings.callback, 0); }
            }
            function loadFail() {
                throw new Error('Failed to load source from ' + settings.source);
            }
            function loadCallback(response) {
                soundbrix_audio_context.decodeAudioData(response, loadSuccess, loadFail);
            }
            that.playSound = noop;
            that.stopSound = noop;
            that.setVolume = noop;
            that.setPlaybackRate = noop;
            loadSound(settings.source, loadCallback);
        }
        SOUNDBRIX = {
            createSound: function createSound(user_settings) {
                var settings;
                if (typeof user_settings !== "object") {
                    throw new Error('ERROR: A valid object parameter is required.');
                }
                user_settings.source = user_settings.source || user_settings.src || user_settings.href || user_settings.url || user_settings.location;
                if (user_settings.source === undefined) {
                    throw new Error('ERROR: No valid sound source url found!\nFailed to create sound object.');
                }
                settings = mergeSettings(default_settings, user_settings);
                // The actual gain value that should be in use for the buffer(s) must not be greater than one (1)
                if (settings.gain < 0) {
                    settings.gain = 0;
                } else {
                    if (settings.gain > max_gain) {
                        settings.gain = max_gain;
                    }
                }
                if (settings.exp) {
                    return new Type1(settings);
                }
                return new Type2(settings);
            }
        };
    }());
    if (typeof Object.defineProperty === "function") {
        Object.defineProperty(SOUNDBRIX, 'audioContext', {
            get: function get() {
                return soundbrix_audio_context;
            },
            set: function set(value) {
                console.log('This property is read-only. You entered: ' + value);
                return;
            },
            enumerable: true,
            configurable: false
        });
    }
    SOUNDBRIX.getAudioContext = function () {
        return soundbrix_audio_context;
    };
    if (typeof Object.freeze === "function") {
        Object.freeze(SOUNDBRIX);
    }
}(window));<commit_msg>Update setVolume method<commit_after>/*
    Copyright 2012 Jaycliff Arcilla of Eversun Software Philippines Corporation (Davao branch)

    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.
*/

/*

    SoundBrix: Experimental HTML5 Sound Object Creation Library powered by Web Audio API (Version 1.3 - 06/30/2014)
    Author: Jaycliff Arcilla

    This library was created to provide sweet audio fallback options when crap happens (Flash Epic Fail).
    Moreover, my previous AoV client (Nigel S. Ball) is reasonably allergic to Flash, making this a perfect non-Flash audio solution for his websites.

    UPDATES:

    * v1.3 (06/30/2014) Refactored the sound object creation process and made several optimizations regarding the channel-switching playback of buffers
    * v1.2 (05/19/2014) Refactored checking for AudioContext constructor. Several optimizations.
    * v1.1 (09/05/2012) Made several enhancements to the creation process. Added gain nodes per sound source. Fixed volume setting method.
    * v1.0 (02/22/2012) Initial release.

    NOTES:

    * AudioBufferSourceNode can only be played once. To play another sound of the same source, another AudioBufferSourceNode must be created, which is stupid.
    * Callbacks MUST be set off using a timer (setTimeout) so as not to wait for the callback to finish executing to proceed with the next statements.

    ISSUES:

    * A gain node cannot accept new inputs starting from when the sound sources start playing. To counter this, a separate gain node for each sound source must be created. However, audio_context.destination doesn't seem to have this limitation.

    Passed JSLint checking! (http://www.jslint.com/)

    JSLINT OPTIONS:

    * Assume console, alert, ...
    * Assume a browser

*/

var SOUNDBRIX;
(function (global) {
    "use strict";
    var hasAudioContext,
        noop,
        loadSound,
        mergeSettings,
        soundbrix_audio_context;
    if (typeof SOUNDBRIX === "object" && typeof SOUNDBRIX.audioContext === "function") {
        console.log('An instance of SoundBrix already exists.');
        return;
    }
    (function hasAudioContextSetup() {
        var vendor_prefixes = ['ms', 'moz', 'webkit', 'o'], audio_context_string = 'AudioContext';
        hasAudioContext = function hasAudioContext() {
            var entry,
                length,
                x;
            if (!global.AudioContext) {
                length = vendor_prefixes.length;
                for (x = 0; x < length; x += 1) {
                    entry = global[vendor_prefixes[x] + audio_context_string];
                    if (typeof entry === "function") {
                        global.AudioContext = entry;
                        return true;
                    }
                }
                return false;
            }
            return true;
        };
    }());
    if (hasAudioContext()) {
        noop = function noop() {
            return;
        };
        soundbrix_audio_context = new global.AudioContext();
    } else {
        console.log("This host doesn't have a Web Audio API implementation.");
        return;
    }
    loadSound = function loadSound(url, callback) {
        var request = new XMLHttpRequest();
        // Load sound synchronously (the 'false' flag), 'true' means asynchronous
        // Avoid using synchronous operations in JavaScript
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';
        request.addEventListener('load', function () { callback(request.response); }, false);
        request.send();
    };
    // ds and us mean 'default settings' and 'user settings', respectively. Now you know. - Manny
    mergeSettings = function mergeSettings(ds, us) {
        var key, temp = {};
        for (key in ds) {
            if (ds.hasOwnProperty(key)) {
                temp[key] = ds[key];
            }
        }
        for (key in us) {
            if (us.hasOwnProperty(key)) {
                temp[key] = us[key];
            }
        }
        return temp;
    };
    (function soundBrixSetup() {
        var max_gain = 100, default_settings = {
            exp: false,
            loop: false,
            playback_rate: 1,
            gain: 100,
            max_channels: 1
        };
        // Type1 sound instances allow multiple instances to be played, but can't be stopped.
        function Type1(settings) {
            var that = this, gain_rate = settings.gain / max_gain, curve = gain_rate * gain_rate;
            function setMethods() {
                that.playSound = function playSound() {
                    var channel, gainNode;
                    channel = soundbrix_audio_context.createBufferSource();
                    channel.buffer = that.audio_buffer;
                    channel.loop = settings.loop;
                    channel.playbackRate.value = settings.playback_rate;
                    if (typeof soundbrix_audio_context.createGain !== "function") {
                        channel.connect(soundbrix_audio_context.destination);
                    } else {
                        gainNode = soundbrix_audio_context.createGain();
                        gainNode.connect(soundbrix_audio_context.destination);
                        // Using x * x curve to smooth out transition
                        gainNode.gain.value = curve;
                        channel.connect(gainNode);
                    }
                    if (typeof channel.start === "function") {
                        channel.start(0);
                    }
                };
                that.setVolume = function setVolume(value) {
                    var fraction;
                    if (value > max_gain) {
                        value = max_gain;
                    } else {
                        if (value < 0) {
                            value = 0;
                        }
                    }
                    fraction = value / max_gain;
                    // Using x * x curve to smooth out transition
                    settings.gain = value;
                    curve = fraction * fraction;
                };
                that.setPlaybackRate = function setPlaybackRate(value) {
                    settings.playback_rate = value;
                };
            }
            function loadSuccess(buffer) {
                // This block will run when the buffer has been decoded. Insert all remaining sound object code here
                // For some instances, the createBuffer method is preferred over decodeAudioData to forcibly decode the buffer without waiting for callbacks
                //that.audio_buffer = soundbrix_audio_context.createBuffer(request.response, false);
                that.audio_buffer = buffer;
                setMethods();
                // The callback MUST be set off using a timer (setTimeout) so as not to wait for the callback to finish executing to proceed with the next statements
                if (typeof settings.callback === "function") { setTimeout(settings.callback, 0); }
            }
            function loadFail() {
                throw new Error('Failed to load source from ' + settings.source);
            }
            function loadCallback(response) {
                soundbrix_audio_context.decodeAudioData(response, loadSuccess, loadFail);
            }
            that.playSound = noop;
            that.stopSound = function stopSound() {
                console.log('This sound object cannot be stopped manually.');
                return;
            };
            that.setVolume = noop;
            that.setPlaybackRate = noop;
            loadSound(settings.source, loadCallback);
        }
        // Type2 sound instances utilize 'channels' to allow multiple instances of a sound source to be played.
        // Also, it's stoppable (stopSound)
        function Type2(settings) {
            var that = this, gainNode = [], gain_rate = settings.gain / max_gain, curve = gain_rate * gain_rate;
            that.channel_busy = [];
            that.source_channels = {};
            that.current_sound_channel = 0;
            that.audio_buffer = null;
            that.is_playing = false;
            // Sneakily increment the number of channels by one to provide a 'buffer' for setting up a new sound source. See the sound channel lag fix inside the that.playSound method
            //settings.max_channels += 1;
            function createChannels() {
                var i;
                for (i = 0; i < settings.max_channels; i += 1) {
                    that.source_channels[i] = soundbrix_audio_context.createBufferSource();
                    that.source_channels[i].buffer = that.audio_buffer;
                    that.source_channels[i].loop = settings.loop;
                    that.source_channels[i].playbackRate.value = settings.playback_rate;
                    if (typeof soundbrix_audio_context.createGain !== "function") {
                        console.log('No gain nodes.');
                        console.log(soundbrix_audio_context);
                        that.source_channels[i].connect(soundbrix_audio_context.destination);
                    } else {
                        gainNode[i] = soundbrix_audio_context.createGain();
                        // Using x * x curve to smooth out transition
                        gainNode[i].gain.value = curve;
                        that.source_channels[i].connect(gainNode[i]);
                        gainNode[i].connect(soundbrix_audio_context.destination);
                    }
                    that.channel_busy[i] = false;
                }
            }
            function setMethods() {
                that.playSound = function playSound() {
                    that.is_playing = true;
                    if (that.channel_busy[that.current_sound_channel]) {
                        that.current_sound_channel += 1;
                        if (that.current_sound_channel === settings.max_channels) {
                            that.current_sound_channel = 0;
                        }
                    }
                    if (typeof that.source_channels[that.current_sound_channel].start === "function") {
                        that.source_channels[that.current_sound_channel].start(0);
                    }
                    that.channel_busy[that.current_sound_channel] = true;
                    /*

                        The solution below fixes sound-playing lag caused by some latency when creating new AudioBufferSourceNode (via the context.createBufferSource() method)
                        Basically it re-initializes the sound channel following the current one to prepare the nextchannel for playback (and somewhat avoiding the said latency)

                    */
                    // Start sound channel lag fix
                    var next_channel;
                    next_channel = that.current_sound_channel + 1;
                    if (next_channel === settings.max_channels) {
                        next_channel = 0;
                    }
                    if (that.channel_busy[next_channel]) {
                        //if (that.source_channels[next_channel].stop !== undefined) { that.source_channels[next_channel].stop(0); }
                        // Simply replace the next busy channel with a new one. The old one will keep on playing and will eventually be collected.
                        that.source_channels[next_channel] = soundbrix_audio_context.createBufferSource();
                        that.source_channels[next_channel].buffer = that.audio_buffer;
                        that.source_channels[next_channel].loop = settings.loop;
                        that.source_channels[next_channel].playbackRate.value = settings.playback_rate;
                        if (typeof soundbrix_audio_context.createGain !== "function") {
                            that.source_channels[next_channel].connect(soundbrix_audio_context.destination);
                        } else {
                            gainNode[next_channel] = soundbrix_audio_context.createGain();
                            gainNode[next_channel].gain.value = curve;
                            that.source_channels[next_channel].connect(gainNode[next_channel]);
                            gainNode[next_channel].connect(soundbrix_audio_context.destination);
                        }
                        that.channel_busy[next_channel] = false;
                    }
                    // End sound channel lag fix
                };
                that.stopSound = function stopSound() {
                    var i;
                    if (that.is_playing) {
                        that.is_playing = false;
                        for (i = 0; i < settings.max_channels; i += 1) {
                            if (that.source_channels[i].stop !== undefined) {
                                // Let's check first if the current channel is 'busy' before calling stop. Why? Because Chrome throws an error when calling stop on unplayed buffer sources.
                                if (that.channel_busy[i]) {
                                    that.source_channels[i].stop(0);
                                }
                            }
                        }
                        createChannels();
                    }
                };
                that.setVolume = function setVolume(value) {
                    var fraction, i;
                    if (value > max_gain) {
                        value = max_gain;
                    } else {
                        if (value < 0) {
                            value = 0;
                        }
                    }
                    fraction = value / max_gain;
                    // Using x * x curve to smooth out transition
                    settings.gain = value;
                    curve = fraction * fraction;
                    for (i = 0; i < gainNode.length; i += 1) {
                        gainNode[i].gain.value = curve;
                    }
                };
                that.setPlaybackRate = function setPlaybackRate(value) {
                    var i;
                    settings.playback_rate = value;
                    for (i = 0; i < settings.max_channels; i += 1) {
                        that.source_channels[i].playbackRate.value = value;
                    }
                };
            }
            function loadSuccess(buffer) {
                // This block will run when the buffer has been decoded. Insert all remaining sound object code here
                // For some instances, the createBuffer method is preferred over decodeAudioData to forcibly decode the buffer without waiting for callbacks
                //that.audio_buffer = soundbrix_audio_context.createBuffer(request.response, false);
                that.audio_buffer = buffer;
                createChannels();
                //console.log(that.source_channels[0]);
                setMethods();
                // The callback MUST be set off using a timer (setTimeout) so as not to wait for the callback to finish executing to proceed with the next statements
                if (typeof settings.callback === "function") { setTimeout(settings.callback, 0); }
            }
            function loadFail() {
                throw new Error('Failed to load source from ' + settings.source);
            }
            function loadCallback(response) {
                soundbrix_audio_context.decodeAudioData(response, loadSuccess, loadFail);
            }
            that.playSound = noop;
            that.stopSound = noop;
            that.setVolume = noop;
            that.setPlaybackRate = noop;
            loadSound(settings.source, loadCallback);
        }
        SOUNDBRIX = {
            createSound: function createSound(user_settings) {
                var settings;
                if (typeof user_settings !== "object") {
                    throw new Error('ERROR: A valid object parameter is required.');
                }
                user_settings.source = user_settings.source || user_settings.src || user_settings.href || user_settings.url || user_settings.location;
                if (user_settings.source === undefined) {
                    throw new Error('ERROR: No valid sound source url found!\nFailed to create sound object.');
                }
                settings = mergeSettings(default_settings, user_settings);
                // The actual gain value that should be in use for the buffer(s) must not be greater than one (1)
                if (settings.gain < 0) {
                    settings.gain = 0;
                } else {
                    if (settings.gain > max_gain) {
                        settings.gain = max_gain;
                    }
                }
                if (settings.exp) {
                    return new Type1(settings);
                }
                return new Type2(settings);
            }
        };
    }());
    if (typeof Object.defineProperty === "function") {
        Object.defineProperty(SOUNDBRIX, 'audioContext', {
            get: function get() {
                return soundbrix_audio_context;
            },
            set: function set(value) {
                console.log('This property is read-only. You entered: ' + value);
                return;
            },
            enumerable: true,
            configurable: false
        });
    }
    SOUNDBRIX.getAudioContext = function () {
        return soundbrix_audio_context;
    };
    if (typeof Object.freeze === "function") {
        Object.freeze(SOUNDBRIX);
    }
}(window));<|endoftext|>


<commit_before>//* @public
/**
	_moon.Panel_ is the default kind for controls created inside a
	moon.Panels container.  Typically, a _moon.Panels_
	will contain several instances of _moon.Panel_.

	The built-in features of _moon.Panel_ include a header and a FittableRows
	layout for the main body content.
*/

enyo.kind({
	name: "moon.Panel",
	published: {
		//* Facade for the header's _title_ property
		title: "",
		//* Facade for the header's _titleAbove_ property
		titleAbove: "",
		//* Facade for the header's _titleBelow_ property
		titleBelow: "",
		//* Facade for the header's _subTitleBelow_ property
		subTitleBelow: "",
		/**
			If true, the header's _titleAbove_ property is automatically populated
			with the panel index
		*/
		autoNumber: true,
		//* Facade for the header's _small_ property
		smallHeader: false,
		//* If true, the header collapses when the panel body is scrolled down
		collapsingHeader: false,
		//* Title's _allowHtml_ property
		allowHtmlHeader: false,
		//* URL of a background image for the header
		headerBackgroundImage: null,
		//* Position properties for background image for the header
		headerBackgroundPosition: "top right"
		//* Header options
		headerOptions: null
	},
	events: {
		//* Fires when this panel has completed its pre-arrangement transition.
		onPreTransitionComplete: "",
		//* Fires when this panel has completed its post-arrangement transition.
		onPostTransitionComplete: ""
	},
	handlers: {
		onScroll: "scroll",
		ontap: "handleBreadcrumbTap",
		onPanelsPostTransitionFinished: "panelsTransitionFinishHandler"
	},

	//* @protected
	spotlight: "container",
	fit: true,
	classes: "moon-panel",
	layoutKind: "FittableRowsLayout",
	headerOption: null, //* Deprecated
	panelTools : [
		{name: "viewport", classes: "moon-panel-viewport", components: [
			{name: "contentWrapper", kind:"FittableRows", classes: "moon-panel-content-wrapper", components: [
				{name: "panelBody", kind: "FittableRows", fit: true, classes: "moon-panel-body"}
			]}
		]},
		{name: "breadcrumb", classes: "moon-panel-breadcrumb", components: [
			{name: "breadcrumbViewport", classes: "moon-panel-breadcrumb-viewport", components: [
				{name: "breadcrumbBackground", classes: "moon-panel-mini-header-wrapper", components: [
					{name: "breadcrumbTitleAbove", classes: "moon-panel-mini-header-title-above"},
					{name: "breadcrumbText", kind: "moon.MarqueeText", classes: "moon-panel-mini-header"}
				]}
			]}
		]},
		{name: "animator", kind: "StyleAnimator", onComplete: "animationComplete"}
	],
	headerConfig : {name: "header", kind: "moon.Header", onComplete: "headerAnimationComplete", isChrome: true},
	bindings: [
		{from: ".title", to: ".$.header.title"},
		{from: ".title", to: ".$.breadcrumbText.content"},
		{from: ".titleAbove", to: ".$.header.titleAbove"},
		{from: ".titleAbove", to: ".$.breadcrumbTitleAbove.content"},
		{from: ".titleBelow", to: ".$.header.titleBelow"},
		{from: ".subTitleBelow", to: ".$.header.subTitleBelow"},
		{from: ".smallHeader", to: ".$.header.small"},
		{from: ".allowHtmlHeader", to: ".$.header.allowHtml"},
		{from: ".headerBackgroundSrc", to: ".$.header.backgroundSrc"},
		{from: ".headerBackgroundPosition", to: ".$.header.backgroundPosition"}
	],

	headerComponents: [],
	isBreadcrumb: false,
	isHeaderCollapsed: false,
	shrinking: false,
	growing: false,

	create: function() {
		this.inherited(arguments);
		// FIXME: Need to determine whether headerComponents was passed on the instance or kind to get the ownership correct
		if (this.headerComponents) {
			var hc = enyo.constructorForKind(this.kind).prototype.headerComponents;
			var hcOwner = (hc == this.headerComponents) ? this : this.getInstanceOwner();
			this.$.header.createComponents(this.headerComponents, {owner: hcOwner});
		}
		this.autoNumberChanged();
	},
	initComponents: function() {
		this.createTools();
		this.controlParentName = "panelBody";
		this.discoverControlParent();
		this.inherited(arguments);
	},
	createTools: function() {
		// Create everything but the header
		this.createChrome(this.panelTools);
		// Special-handling for header, which can have its options modified by the instance
		var hc = enyo.clone(this.headerConfig || {});
<<<<<<>>>>>> master
		this.$.contentWrapper.createComponent(hc, {owner:this});
	},
	//* On reflow, update _this.$.contentWrapper_ bounds
	reflow: function() {
		this.inherited(arguments);
		this.getInitAnimationValues();
		this.updateViewportSize();
		this.shrinkWidthAnimation = this.createShrinkingWidthAnimation();
		this.shrinkHeightAnimation = this.createShrinkingHeightAnimation();
		this.growWidthAnimation = this.createGrowingWidthAnimation();
		this.growHeightAnimation = this.createGrowingHeightAnimation();
	},
	//* Update _this.$.contentWrapper_ to have the height/width of _this_
	updateViewportSize: function() {
		var node = this.hasNode();

		if (!node || this.isBreadcrumb) {
			return;
		}

		this.$.viewport.applyStyle("height", this.initialHeight + "px");
		this.$.viewport.applyStyle("width", this.initialWidth + "px");
	},
	//* Forcibly applies layout kind changes to _this.$.panelBody_.
	layoutKindChanged: function() {
		this.$.panelBody.setLayoutKind(this.getLayoutKind());
		this.inherited(arguments);
	},
	//* Updates _this.titleAbove_ when _this.autoNumber_ changes.
	autoNumberChanged: function() {
		if (this.getAutoNumber() === true && this.container) {
			this.setTitleAbove(this.generateAutoNumber());
		}
	},
	//* When _this.isBreadcrumb_ changes, update spottability
	isBreadcrumbChanged: function() {
		if (this.isBreadcrumb) {
			this.addSpottableBreadcrumbProps();
		} else {
			this.removeSpottableBreadcrumbProps();
		}
	},
	handleBreadcrumbTap: function(inSender, inEvent) {
		if (!this.isBreadcrumb) {
			return;
		}
	},
	scroll: function(inSender, inEvent) {
		if (this.collapsingHeader && !this.smallHeader) {
			if (inEvent.originator.y < 0) {
				this.collapseHeader();
			} else {
				this.expandHeader();
			}
		}
	},
	collapseHeader: function() {
		if (!this.isHeaderCollapsed) {
			this.$.header.collapseToSmall();
			this.isHeaderCollapsed = true;
		}
	},
	expandHeader: function() {
		if (this.isHeaderCollapsed) {
			this.$.header.expandToLarge();
			this.isHeaderCollapsed = false;
		}
	},
	generateAutoNumber: function() {
		var adjustedIndex = this.indexInContainer() + 1;
		return (adjustedIndex < 10) ? "0"+ adjustedIndex : adjustedIndex;
	},
	addSpottableBreadcrumbProps: function() {
		this.$.breadcrumbBackground.spotlight = true;
	},
	removeSpottableBreadcrumbProps: function() {
		this.$.breadcrumbBackground.spotlight = false;
		this.$.breadcrumbBackground.removeClass("spotlight");
	},
	//* Updates panel header dynamically.
	getHeader: function() {
		return this.$.header;
	},
	shrinkPanel: function() {
		this.growing = false;
		this.shrinking = true;
		this.showingSmallHeader = false;
		this.shrinkingHeightAnimation();
	},
	growPanel: function() {
		this.growing = true;
		this.shrinking = false;
		this.showingSmallHeader = true;
		this.growingWidthAnimation();
	},
	//* @protected
	getInitAnimationValues: function() {
		var node = this.hasNode();
		this.initialHeight = node.offsetHeight;
		this.initialWidth = node.offsetWidth;
	},
	shrinkingHeightAnimation: function() {
		this.haltAnimations();
		this.$.animator.play(this.shrinkHeightAnimation.name);
	},
	shrinkingWidthAnimation: function() {
		this.haltAnimations();

		this.preTransitionComplete();
		// NOTE - Skipping width shrink animation
		// this.$.breadcrumbBackground.applyStyle("width", "300px");
		// this.$.animator.play(this.shrinkWidthAnimation.name);
	},
	growingHeightAnimation: function() {
		this.haltAnimations();
		this.$.animator.play(this.growHeightAnimation.name);
	},
	growingWidthAnimation: function() {
		this.haltAnimations();

		this.growingHeightAnimation();
		// NOTE - Skipping width grow animation
		// this.$.animator.play(this.growWidthAnimation.name);
	},
	haltAnimations: function() {
		this.$.animator.stop();
		this.$.animator.pause(this.growWidthAnimation.name);
		this.$.animator.pause(this.growHeightAnimation.name);
		this.$.animator.pause(this.shrinkWidthAnimation.name);
		this.$.animator.pause(this.shrinkHeightAnimation.name);
	},
	panelsTransitionFinishHandler: function(inSender, inEvent) {
		// run miniHeader marquee when we're collapsed
		if(this.showingSmallHeader) {
			this.$.breadcrumbText.startMarquee();
		} else {
			this.$.breadcrumbText.stopMarquee();
			if (inEvent.active == inEvent.index) {
				this.$.header.startMarquee();
			}
		}
		return true;
	},
	preTransitionComplete: function() {
		this.shrinking = false;
		this.set("isBreadcrumb", true);
		this.doPreTransitionComplete();
	},
	postTransitionComplete: function() {
		this.growing = false;
		this.set("isBreadcrumb", false);
		this.doPostTransitionComplete();
		this.resized();
	},
	preTransition: function(inFromIndex, inToIndex, options) {
		this.$.header.stopMarquee();
		this.$.breadcrumbText.stopMarquee();

		if (!this.shrinking && options.isBreadcrumb && (!this.isBreadcrumb || this.growing)) {
			this.shrinkPanel();
			return true;
		}

		return false;
	},
	postTransition: function(inFromIndex, inToIndex, options) {
		if (!this.growing && !options.isBreadcrumb && (this.isBreadcrumb || this.shrinking)) {
			this.growPanel();
			return true;
		}

		return false;
	},
	animationComplete: function(inSender, inEvent) {
		switch (inEvent.animation.name) {
		case "shrinkHeight":
			this.shrinkingWidthAnimation();
			return true;
		case "shrinkWidth":
			this.preTransitionComplete();
			return true;
		case "growWidth":
			this.growingHeightAnimation();
			return true;
		case "growHeight":
			this.postTransitionComplete();
			return true;
		}
	},
	headerAnimationComplete: function(inSender, inEvent) {
		switch (inEvent.animation.name) {
		case "collapseToSmall":
		case "expandToLarge":
			// FIXME: It would be better to call this during the animation so it resizes
			// smoothly, but that's not possible with CSS transitions; it will jump now
			this.resized();
			break;
		}
	},
	createGrowingWidthAnimation: function() {
		return this.$.animator.newAnimation({
			name: "growWidth",
			duration: 225,
			timingFunction: "cubic-bezier(.25,.1,.25,1)",
			keyframes: {
				0: [
					{control: this.$.viewport, properties: { "width": "current" }}

				],
				100: [
					{control: this.$.viewport, properties: { "width": this.initialWidth + "px" }}
				]
			}
		});
	},
	createGrowingHeightAnimation: function() {
		return this.$.animator.newAnimation({
			name: "growHeight",
			duration: 400,
			timingFunction: "cubic-bezier(.25,.1,.25,1)",
			keyframes: {
				0: [
					{control: this.$.viewport, properties: {"height"  : "0px"}},
					{control: this.$.breadcrumbViewport, properties: { "height": "current" }}
				],
				50: [
					{control: this.$.breadcrumbViewport, properties: { "height": "0px" }}
				],
				100: [
					{control: this.$.viewport, properties: {"height" : this.initialHeight + "px"}}
				]
			}
		});
	},
	createShrinkingWidthAnimation: function() {
		return this.$.animator.newAnimation({
			name: "shrinkWidth",
			duration: 225,
			timingFunction: "cubic-bezier(.68,.4,.56,.98)",
			keyframes: {
				0: [
					{control: this.$.breadcrumbBackground, properties: { "width": "current" }}
				],
				100: [
					{control: this.$.breadcrumbBackground, properties: { "width": "current" }}
				]
			}
		});
	},
	createShrinkingHeightAnimation: function() {
		return this.$.animator.newAnimation({
			name: "shrinkHeight",
			duration: 500,
			timingFunction: "cubic-bezier(.25,.1,.25,1)",
			keyframes: {
				0: [
					{control: this.$.viewport, properties: { "height"  : "current" }}
				],
				50: [
					{control: this.$.breadcrumbViewport, properties: { "height": "current" }}
				],
				100: [
					{control: this.$.viewport, properties: { "height"  : "0px" }},
					{control: this.$.breadcrumbViewport, properties: { "height": "370px" }}
				]
			}
		});
	}
});
<commit_msg>Fix merge conflict. Enyo-DCO-1.1-Signed-Off-By: Kevin Schaaf (kevin.schaaf@lge.com)<commit_after>//* @public
/**
	_moon.Panel_ is the default kind for controls created inside a
	moon.Panels container.  Typically, a _moon.Panels_
	will contain several instances of _moon.Panel_.

	The built-in features of _moon.Panel_ include a header and a FittableRows
	layout for the main body content.
*/

enyo.kind({
	name: "moon.Panel",
	published: {
		//* Facade for the header's _title_ property
		title: "",
		//* Facade for the header's _titleAbove_ property
		titleAbove: "",
		//* Facade for the header's _titleBelow_ property
		titleBelow: "",
		//* Facade for the header's _subTitleBelow_ property
		subTitleBelow: "",
		/**
			If true, the header's _titleAbove_ property is automatically populated
			with the panel index
		*/
		autoNumber: true,
		//* Facade for the header's _small_ property
		smallHeader: false,
		//* If true, the header collapses when the panel body is scrolled down
		collapsingHeader: false,
		//* Title's _allowHtml_ property
		allowHtmlHeader: false,
		//* URL of a background image for the header
		headerBackgroundImage: null,
		//* Position properties for background image for the header
		headerBackgroundPosition: "top right",
		//* Header options
		headerOptions: null
	},
	events: {
		//* Fires when this panel has completed its pre-arrangement transition.
		onPreTransitionComplete: "",
		//* Fires when this panel has completed its post-arrangement transition.
		onPostTransitionComplete: ""
	},
	handlers: {
		onScroll: "scroll",
		ontap: "handleBreadcrumbTap",
		onPanelsPostTransitionFinished: "panelsTransitionFinishHandler"
	},

	//* @protected
	spotlight: "container",
	fit: true,
	classes: "moon-panel",
	layoutKind: "FittableRowsLayout",
	headerOption: null, //* Deprecated
	panelTools : [
		{name: "viewport", classes: "moon-panel-viewport", components: [
			{name: "contentWrapper", kind:"FittableRows", classes: "moon-panel-content-wrapper", components: [
				{name: "panelBody", kind: "FittableRows", fit: true, classes: "moon-panel-body"}
			]}
		]},
		{name: "breadcrumb", classes: "moon-panel-breadcrumb", components: [
			{name: "breadcrumbViewport", classes: "moon-panel-breadcrumb-viewport", components: [
				{name: "breadcrumbBackground", classes: "moon-panel-mini-header-wrapper", components: [
					{name: "breadcrumbTitleAbove", classes: "moon-panel-mini-header-title-above"},
					{name: "breadcrumbText", kind: "moon.MarqueeText", classes: "moon-panel-mini-header"}
				]}
			]}
		]},
		{name: "animator", kind: "StyleAnimator", onComplete: "animationComplete"}
	],
	headerConfig : {name: "header", kind: "moon.Header", onComplete: "headerAnimationComplete", isChrome: true},
	bindings: [
		{from: ".title", to: ".$.header.title"},
		{from: ".title", to: ".$.breadcrumbText.content"},
		{from: ".titleAbove", to: ".$.header.titleAbove"},
		{from: ".titleAbove", to: ".$.breadcrumbTitleAbove.content"},
		{from: ".titleBelow", to: ".$.header.titleBelow"},
		{from: ".subTitleBelow", to: ".$.header.subTitleBelow"},
		{from: ".smallHeader", to: ".$.header.small"},
		{from: ".allowHtmlHeader", to: ".$.header.allowHtml"},
		{from: ".headerBackgroundSrc", to: ".$.header.backgroundSrc"},
		{from: ".headerBackgroundPosition", to: ".$.header.backgroundPosition"}
	],

	headerComponents: [],
	isBreadcrumb: false,
	isHeaderCollapsed: false,
	shrinking: false,
	growing: false,

	create: function() {
		this.inherited(arguments);
		// FIXME: Need to determine whether headerComponents was passed on the instance or kind to get the ownership correct
		if (this.headerComponents) {
			var hc = enyo.constructorForKind(this.kind).prototype.headerComponents;
			var hcOwner = (hc == this.headerComponents) ? this : this.getInstanceOwner();
			this.$.header.createComponents(this.headerComponents, {owner: hcOwner});
		}
		this.autoNumberChanged();
	},
	initComponents: function() {
		this.createTools();
		this.controlParentName = "panelBody";
		this.discoverControlParent();
		this.inherited(arguments);
	},
	createTools: function() {
		// Create everything but the header
		this.createChrome(this.panelTools);
		// Special-handling for header, which can have its options modified by the instance
		var hc = enyo.clone(this.headerConfig || {});
		hc.addBefore = this.$.panelBody;
		enyo.mixin(hc, this.headerOption);
		this.$.contentWrapper.createComponent(hc, {owner:this});
	},
	//* On reflow, update _this.$.contentWrapper_ bounds
	reflow: function() {
		this.inherited(arguments);
		this.getInitAnimationValues();
		this.updateViewportSize();
		this.shrinkWidthAnimation = this.createShrinkingWidthAnimation();
		this.shrinkHeightAnimation = this.createShrinkingHeightAnimation();
		this.growWidthAnimation = this.createGrowingWidthAnimation();
		this.growHeightAnimation = this.createGrowingHeightAnimation();
	},
	//* Update _this.$.contentWrapper_ to have the height/width of _this_
	updateViewportSize: function() {
		var node = this.hasNode();

		if (!node || this.isBreadcrumb) {
			return;
		}

		this.$.viewport.applyStyle("height", this.initialHeight + "px");
		this.$.viewport.applyStyle("width", this.initialWidth + "px");
	},
	//* Forcibly applies layout kind changes to _this.$.panelBody_.
	layoutKindChanged: function() {
		this.$.panelBody.setLayoutKind(this.getLayoutKind());
		this.inherited(arguments);
	},
	//* Updates _this.titleAbove_ when _this.autoNumber_ changes.
	autoNumberChanged: function() {
		if (this.getAutoNumber() === true && this.container) {
			this.setTitleAbove(this.generateAutoNumber());
		}
	},
	//* When _this.isBreadcrumb_ changes, update spottability
	isBreadcrumbChanged: function() {
		if (this.isBreadcrumb) {
			this.addSpottableBreadcrumbProps();
		} else {
			this.removeSpottableBreadcrumbProps();
		}
	},
	handleBreadcrumbTap: function(inSender, inEvent) {
		if (!this.isBreadcrumb) {
			return;
		}
	},
	scroll: function(inSender, inEvent) {
		if (this.collapsingHeader && !this.smallHeader) {
			if (inEvent.originator.y < 0) {
				this.collapseHeader();
			} else {
				this.expandHeader();
			}
		}
	},
	collapseHeader: function() {
		if (!this.isHeaderCollapsed) {
			this.$.header.collapseToSmall();
			this.isHeaderCollapsed = true;
		}
	},
	expandHeader: function() {
		if (this.isHeaderCollapsed) {
			this.$.header.expandToLarge();
			this.isHeaderCollapsed = false;
		}
	},
	generateAutoNumber: function() {
		var adjustedIndex = this.indexInContainer() + 1;
		return (adjustedIndex < 10) ? "0"+ adjustedIndex : adjustedIndex;
	},
	addSpottableBreadcrumbProps: function() {
		this.$.breadcrumbBackground.spotlight = true;
	},
	removeSpottableBreadcrumbProps: function() {
		this.$.breadcrumbBackground.spotlight = false;
		this.$.breadcrumbBackground.removeClass("spotlight");
	},
	//* Updates panel header dynamically.
	getHeader: function() {
		return this.$.header;
	},
	shrinkPanel: function() {
		this.growing = false;
		this.shrinking = true;
		this.showingSmallHeader = false;
		this.shrinkingHeightAnimation();
	},
	growPanel: function() {
		this.growing = true;
		this.shrinking = false;
		this.showingSmallHeader = true;
		this.growingWidthAnimation();
	},
	//* @protected
	getInitAnimationValues: function() {
		var node = this.hasNode();
		this.initialHeight = node.offsetHeight;
		this.initialWidth = node.offsetWidth;
	},
	shrinkingHeightAnimation: function() {
		this.haltAnimations();
		this.$.animator.play(this.shrinkHeightAnimation.name);
	},
	shrinkingWidthAnimation: function() {
		this.haltAnimations();

		this.preTransitionComplete();
		// NOTE - Skipping width shrink animation
		// this.$.breadcrumbBackground.applyStyle("width", "300px");
		// this.$.animator.play(this.shrinkWidthAnimation.name);
	},
	growingHeightAnimation: function() {
		this.haltAnimations();
		this.$.animator.play(this.growHeightAnimation.name);
	},
	growingWidthAnimation: function() {
		this.haltAnimations();

		this.growingHeightAnimation();
		// NOTE - Skipping width grow animation
		// this.$.animator.play(this.growWidthAnimation.name);
	},
	haltAnimations: function() {
		this.$.animator.stop();
		this.$.animator.pause(this.growWidthAnimation.name);
		this.$.animator.pause(this.growHeightAnimation.name);
		this.$.animator.pause(this.shrinkWidthAnimation.name);
		this.$.animator.pause(this.shrinkHeightAnimation.name);
	},
	panelsTransitionFinishHandler: function(inSender, inEvent) {
		// run miniHeader marquee when we're collapsed
		if(this.showingSmallHeader) {
			this.$.breadcrumbText.startMarquee();
		} else {
			this.$.breadcrumbText.stopMarquee();
			if (inEvent.active == inEvent.index) {
				this.$.header.startMarquee();
			}
		}
		return true;
	},
	preTransitionComplete: function() {
		this.shrinking = false;
		this.set("isBreadcrumb", true);
		this.doPreTransitionComplete();
	},
	postTransitionComplete: function() {
		this.growing = false;
		this.set("isBreadcrumb", false);
		this.doPostTransitionComplete();
		this.resized();
	},
	preTransition: function(inFromIndex, inToIndex, options) {
		this.$.header.stopMarquee();
		this.$.breadcrumbText.stopMarquee();

		if (!this.shrinking && options.isBreadcrumb && (!this.isBreadcrumb || this.growing)) {
			this.shrinkPanel();
			return true;
		}

		return false;
	},
	postTransition: function(inFromIndex, inToIndex, options) {
		if (!this.growing && !options.isBreadcrumb && (this.isBreadcrumb || this.shrinking)) {
			this.growPanel();
			return true;
		}

		return false;
	},
	animationComplete: function(inSender, inEvent) {
		switch (inEvent.animation.name) {
		case "shrinkHeight":
			this.shrinkingWidthAnimation();
			return true;
		case "shrinkWidth":
			this.preTransitionComplete();
			return true;
		case "growWidth":
			this.growingHeightAnimation();
			return true;
		case "growHeight":
			this.postTransitionComplete();
			return true;
		}
	},
	headerAnimationComplete: function(inSender, inEvent) {
		switch (inEvent.animation.name) {
		case "collapseToSmall":
		case "expandToLarge":
			// FIXME: It would be better to call this during the animation so it resizes
			// smoothly, but that's not possible with CSS transitions; it will jump now
			this.resized();
			break;
		}
	},
	createGrowingWidthAnimation: function() {
		return this.$.animator.newAnimation({
			name: "growWidth",
			duration: 225,
			timingFunction: "cubic-bezier(.25,.1,.25,1)",
			keyframes: {
				0: [
					{control: this.$.viewport, properties: { "width": "current" }}

				],
				100: [
					{control: this.$.viewport, properties: { "width": this.initialWidth + "px" }}
				]
			}
		});
	},
	createGrowingHeightAnimation: function() {
		return this.$.animator.newAnimation({
			name: "growHeight",
			duration: 400,
			timingFunction: "cubic-bezier(.25,.1,.25,1)",
			keyframes: {
				0: [
					{control: this.$.viewport, properties: {"height"  : "0px"}},
					{control: this.$.breadcrumbViewport, properties: { "height": "current" }}
				],
				50: [
					{control: this.$.breadcrumbViewport, properties: { "height": "0px" }}
				],
				100: [
					{control: this.$.viewport, properties: {"height" : this.initialHeight + "px"}}
				]
			}
		});
	},
	createShrinkingWidthAnimation: function() {
		return this.$.animator.newAnimation({
			name: "shrinkWidth",
			duration: 225,
			timingFunction: "cubic-bezier(.68,.4,.56,.98)",
			keyframes: {
				0: [
					{control: this.$.breadcrumbBackground, properties: { "width": "current" }}
				],
				100: [
					{control: this.$.breadcrumbBackground, properties: { "width": "current" }}
				]
			}
		});
	},
	createShrinkingHeightAnimation: function() {
		return this.$.animator.newAnimation({
			name: "shrinkHeight",
			duration: 500,
			timingFunction: "cubic-bezier(.25,.1,.25,1)",
			keyframes: {
				0: [
					{control: this.$.viewport, properties: { "height"  : "current" }}
				],
				50: [
					{control: this.$.breadcrumbViewport, properties: { "height": "current" }}
				],
				100: [
					{control: this.$.viewport, properties: { "height"  : "0px" }},
					{control: this.$.breadcrumbViewport, properties: { "height": "370px" }}
				]
			}
		});
	}
});
<|endoftext|>