<commit_before>import React from 'react';

import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';

const CastEfficiency = ({ categories, abilities }) => {
  if (!abilities) {
    return
Loading...
;
  }

  return (

        {Object.keys(categories).map((key) => (

              {categories[key]}
              <dfn data-tip="Casts Per Minute">CPM</dfn>
              <dfn data-tip="The max possible casts is a super simplified calculation based on the Haste you get from your gear alone. Any Haste increasers such as from talents, Bloodlust and boss abilities are not taken into consideration, so this is always lower than actually possible for abilities affected by Haste.">Cast efficiency</dfn>
              Overhealing

          {abilities
            .filter(item => item.ability.category === categories[key])
            .map(({ ability, cpm, maxCpm, casts, maxCasts, castEfficiency, overhealing, canBeImproved }) => {
              const name = ability.name || ability.spell.name;
              return (

                    <SpellLink id={ability.spell.id} style={{ color: '#fff' }}>
                      <SpellIcon id={ability.spell.id} noLink /> {name}
                    </SpellLink>

                    {cpm.toFixed(2)}

                    {casts}{maxCasts === Infinity ? '' : `/${Math.floor(maxCasts)}`} casts

                    {maxCasts === Infinity ? '' : (
                      <div
                        className="performance-bar"
                        style={{ width: `${castEfficiency * 100}%`, backgroundColor: canBeImproved ? '#ff8000' : '#70b570' }}
                      />
                    )}

                    {maxCpm !== null ? `${(castEfficiency * 100).toFixed(2)}%` : ''}

                    {overhealing !== null ? `${(overhealing * 100).toFixed(2)}%` : '-'}

                    {canBeImproved && !ability.noCanBeImproved && 'Can be improved.'}

              );
            })}

        ))}

  );
};
CastEfficiency.propTypes = {
  abilities: React.PropTypes.arrayOf(React.PropTypes.shape({
    ability: React.PropTypes.shape({
      name: React.PropTypes.string.isRequired,
      spellId: React.PropTypes.number.isRequired,
      icon: React.PropTypes.string.isRequired,
    }),
    cpm: React.PropTypes.number.isRequired,
    maxCpm: React.PropTypes.number,
    casts: React.PropTypes.number.isRequired,
    maxCasts: React.PropTypes.number.isRequired,
    castEfficiency: React.PropTypes.number,
    canBeImproved: React.PropTypes.bool.isRequired,
  })).isRequired,
};

export default CastEfficiency;
<commit_msg>(fix) Main CastEfficiency ability PropTypes requirements. Removed ability.name requiremend (is only optinal) Added requirements for ability.spell = {name: ..., id: ....}<commit_after>import React from 'react';

import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';

const CastEfficiency = ({ categories, abilities }) => {
  if (!abilities) {
    return
Loading...
;
  }

  return (

        {Object.keys(categories).map((key) => (

              {categories[key]}
              <dfn data-tip="Casts Per Minute">CPM</dfn>
              <dfn data-tip="The max possible casts is a super simplified calculation based on the Haste you get from your gear alone. Any Haste increasers such as from talents, Bloodlust and boss abilities are not taken into consideration, so this is always lower than actually possible for abilities affected by Haste.">Cast efficiency</dfn>
              Overhealing

          {abilities
            .filter(item => item.ability.category === categories[key])
            .map(({ ability, cpm, maxCpm, casts, maxCasts, castEfficiency, overhealing, canBeImproved }) => {
              const name = ability.name || ability.spell.name;
              return (

                    <SpellLink id={ability.spell.id} style={{ color: '#fff' }}>
                      <SpellIcon id={ability.spell.id} noLink /> {name}
                    </SpellLink>

                    {cpm.toFixed(2)}

                    {casts}{maxCasts === Infinity ? '' : `/${Math.floor(maxCasts)}`} casts

                    {maxCasts === Infinity ? '' : (
                      <div
                        className="performance-bar"
                        style={{ width: `${castEfficiency * 100}%`, backgroundColor: canBeImproved ? '#ff8000' : '#70b570' }}
                      />
                    )}

                    {maxCpm !== null ? `${(castEfficiency * 100).toFixed(2)}%` : ''}

                    {overhealing !== null ? `${(overhealing * 100).toFixed(2)}%` : '-'}

                    {canBeImproved && !ability.noCanBeImproved && 'Can be improved.'}

              );
            })}

        ))}

  );
};
CastEfficiency.propTypes = {
  abilities: React.PropTypes.arrayOf(React.PropTypes.shape({
    ability: React.PropTypes.shape({
      name: React.PropTypes.string,
      category: React.PropTypes.string.isRequired,
      spell: React.PropTypes.shape({
        id: React.PropTypes.number.isRequired,
        name: React.PropTypes.string.isRequired
      }).isRequired
    }).isRequired,
    cpm: React.PropTypes.number.isRequired,
    maxCpm: React.PropTypes.number,
    casts: React.PropTypes.number.isRequired,
    maxCasts: React.PropTypes.number.isRequired,
    castEfficiency: React.PropTypes.number,
    canBeImproved: React.PropTypes.bool.isRequired,
  })).isRequired,
};

export default CastEfficiency;
<|endoftext|>


<commit_before>r.liveupdate.editor = {
    init: function () {
        this.$listing = $('.liveupdate-listing')
        this.$buttonRow = $(r.templates.make('liveupdate/edit-buttons', {
            strikeLabel: r._('strike'),
            deleteLabel: r._('delete')
        }))

        this.$listing
            .on('confirm', '.strike', $.proxy(this, 'strike'))
            .on('confirm', '.delete', $.proxy(this, 'delete_'))
            .on('more-updates', $.proxy(this, 'onMoreUpdates'))

        this._addButtons(this.$listing.find('tr.thing td'))
    },

    onMoreUpdates: function (ev, updates) {
        this._addButtons(updates.filter('tr.thing').find('td'))
    },

    _addButtons: function (updates) {
        updates.each($.proxy(function (index, el) {
            var $buttonRow = this.$buttonRow.clone()
            var $el = $(el)

            if ($el.thing().hasClass('stricken')) {
                $buttonRow.find('button.strike').parent().remove()
            }

            $buttonRow.find('button').each(function (index, el) {
                new r.ui.ConfirmButton({'el': el})
            })

            $el.append($buttonRow)
        }, this))
    },

    strike: function (ev) {
        var $update = $(ev.target).thing()
        var $button = $update.find('.strike.confirm-button')

        $button.text(r._('striking...'))

        $.ajax({
            'type': 'POST',
            'dataType': 'json',
            'url': '/api/live/' + r.config.liveupdate_event + '/strike_update',
            'data': {
                'id': $update.thing_id(),
                'uh': r.config.modhash
            }
        }).done(function () {
            $update.addClass('stricken')
            $button.text(r._('stricken'))
        })
    },

    delete_: function (ev) {
        var $update = $(ev.target).thing()
        var $button = $update.find('.delete.confirm-button')

        $button.text(r._('deleting...'))

        $.ajax({
            'type': 'POST',
            'dataType': 'json',
            'url': '/api/live/' + r.config.liveupdate_event + '/delete_update',
            'data': {
                'id': $update.thing_id(),
                'uh': r.config.modhash
            }
        }).done(function () {
            $button.text(r._('deleted'))
            $update.fadeOut(function () {
                $(this).remove()
            })
        })
    }
}

$.insert_liveupdates = function (things, append) {
    var $listing = $('.liveupdate-listing'),
        $initial = $listing.find('tr.initial')

    _.each(things, function (thing) {
        var $newThing = $($.unsafe(thing.data.content))
        r.liveupdate.editor._addButtons($newThing.find('td'))
        $initial.after($newThing)
    })
}

$(function () { r.liveupdate.editor.init() })
<commit_msg>Reload page when inserting new update and no listing present.<commit_after>r.liveupdate.editor = {
    init: function () {
        this.$listing = $('.liveupdate-listing')
        this.$buttonRow = $(r.templates.make('liveupdate/edit-buttons', {
            strikeLabel: r._('strike'),
            deleteLabel: r._('delete')
        }))

        this.$listing
            .on('confirm', '.strike', $.proxy(this, 'strike'))
            .on('confirm', '.delete', $.proxy(this, 'delete_'))
            .on('more-updates', $.proxy(this, 'onMoreUpdates'))

        this._addButtons(this.$listing.find('tr.thing td'))
    },

    onMoreUpdates: function (ev, updates) {
        this._addButtons(updates.filter('tr.thing').find('td'))
    },

    _addButtons: function (updates) {
        updates.each($.proxy(function (index, el) {
            var $buttonRow = this.$buttonRow.clone()
            var $el = $(el)

            if ($el.thing().hasClass('stricken')) {
                $buttonRow.find('button.strike').parent().remove()
            }

            $buttonRow.find('button').each(function (index, el) {
                new r.ui.ConfirmButton({'el': el})
            })

            $el.append($buttonRow)
        }, this))
    },

    strike: function (ev) {
        var $update = $(ev.target).thing()
        var $button = $update.find('.strike.confirm-button')

        $button.text(r._('striking...'))

        $.ajax({
            'type': 'POST',
            'dataType': 'json',
            'url': '/api/live/' + r.config.liveupdate_event + '/strike_update',
            'data': {
                'id': $update.thing_id(),
                'uh': r.config.modhash
            }
        }).done(function () {
            $update.addClass('stricken')
            $button.text(r._('stricken'))
        })
    },

    delete_: function (ev) {
        var $update = $(ev.target).thing()
        var $button = $update.find('.delete.confirm-button')

        $button.text(r._('deleting...'))

        $.ajax({
            'type': 'POST',
            'dataType': 'json',
            'url': '/api/live/' + r.config.liveupdate_event + '/delete_update',
            'data': {
                'id': $update.thing_id(),
                'uh': r.config.modhash
            }
        }).done(function () {
            $button.text(r._('deleted'))
            $update.fadeOut(function () {
                $(this).remove()
            })
        })
    }
}

$.insert_liveupdates = function (things, append) {
    var $listing = $('.liveupdate-listing'),
        $initial = $listing.find('tr.initial')

    // this must've been the first update. refresh to get a proper listing.
    if (!$listing.length)
        window.location.reload()

    _.each(things, function (thing) {
        var $newThing = $($.unsafe(thing.data.content))
        r.liveupdate.editor._addButtons($newThing.find('td'))
        $initial.after($newThing)
    })
}

$(function () { r.liveupdate.editor.init() })
<|endoftext|>


<commit_before>'use strict';

var app = require('app');
var ipc = require('ipc');
var path = require('path');
var BrowserWindow = require('browser-window');
var env = require('./vendor/electron_boilerplate/env_config');
var devHelper = require('./vendor/electron_boilerplate/dev_helper');
var windowStateKeeper = require('./vendor/electron_boilerplate/window_state');
var tray = require('./tray');

// global variable
var APP_NAME = 'Rocket.Chat';
var INDEX = 'https://rocket.chat/home';
// var INDEX = 'file://' + path.join( __dirname, 'app.html' );

let flagQuitApp = false;
let mainWindow;

// Preserver of the window size and position between app launches.
var mainWindowState = windowStateKeeper('main', {
    width: 1000,
    height: 600
});

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    tray.destroy();
    if (process.platform !== 'darwin') {
        quit();
    }
});

app.on('activate-with-no-open-windows', function() {
    if (!mainWindow) {
        appReady();
    } else {
        mainWindow.show();
    }
});

var willQuit = false;

app.on('before-quit', function() {
    willQuit = true;
});

app.on('ready', appReady);

function initWindow() {
    var win = new BrowserWindow({
        'title': APP_NAME,
        // Standard icon looks somehow very thin in the taskbar
        'icon': path.resolve(path.join(__dirname, 'icons', 'tray', 'icon-tray.png')),
        'node-integration': false,
        'accept-first-mouse': true,
        'show': false,
        'x': mainWindowState.x,
        'y': mainWindowState.y,
        'width': mainWindowState.width,
        'height': mainWindowState.height,
        'preload': path.resolve(path.join(__dirname, 'preload.js')),
        'web-preferences': {
            'web-security': false
        }
    });

    if (mainWindowState.isMaximized) {
        win.maximize();
    }

    if (env.name === 'development') {
        devHelper.setDevMenu();
        win.openDevTools();
    }

    return win;
}

function appReady() {
    let appWindow;

    appWindow = initWindow();
    appWindow.hide();
    appWindow.webContents.on('did-finish-load', function() {
        //prevent flicker workaround
        mainWindow.setAlwaysOnTop(true);
        appWindow.show();
        setTimeout(function() {
            mainWindow.close();
        }, 100);
    });

    mainWindow = initWindow();
    mainWindow.loadUrl(INDEX);

    tray.createAppTray(mainWindow);
    tray.bindOnQuit(onQuitApp);

    appWindow.on('close', function(event) {
        flagQuitApp = true;
    });

    mainWindow.on('close', function(event) {
        if (mainWindow !== null && !flagQuitApp) {
            tray.minimizeMainWindow();
            event.preventDefault();
        } else {
           mainWindowState.saveState(mainWindow);
           appWindow.close();
        }
    });

    mainWindow.on('closed', function() {
        mainWindow = null;
    });

    mainWindow.webContents.on('did-finish-load', function() {
        mainWindow.show();
    });

    mainWindow.webContents.on('new-window', function(ev, url, target) {
        if (target === '_system') {
            ev.preventDefault();
            require('shell').openExternal(url);
        } else if (target === '_blank') {
            ev.preventDefault();
            appWindow.loadUrl(url);
        }
    });
}

function onQuitApp() {
    if (!flagQuitApp) {
        flagQuitApp = true;
        if (mainWindow) {
            mainWindow.close();
        }
    }
}

function quit() {
    if (process.platform !== 'darwin') {
        app.quit();
    }
}

ipc.on('open-dev', function() {
    mainWindow.openDevTools();
});

ipc.on('unread-changed', function(event, unread) {
    let showAlert = (unread !== null && unread !== undefined && unread !== '');
    if (process.platform === 'darwin') {
        app.dock.setBadge(String(unread || ''));
    }
    tray.showTrayAlert(showAlert);
});
<commit_msg>Remove tray when appWindow closes<commit_after>'use strict';

var app = require('app');
var ipc = require('ipc');
var path = require('path');
var BrowserWindow = require('browser-window');
var env = require('./vendor/electron_boilerplate/env_config');
var devHelper = require('./vendor/electron_boilerplate/dev_helper');
var windowStateKeeper = require('./vendor/electron_boilerplate/window_state');
var tray = require('./tray');

// global variable
var APP_NAME = 'Rocket.Chat';
var INDEX = 'https://rocket.chat/home';
// var INDEX = 'file://' + path.join( __dirname, 'app.html' );

let flagQuitApp = false;
let mainWindow;

// Preserver of the window size and position between app launches.
var mainWindowState = windowStateKeeper('main', {
    width: 1000,
    height: 600
});

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    if (process.platform !== 'darwin') {
        quit();
    }
});

app.on('activate-with-no-open-windows', function() {
    if (!mainWindow) {
        appReady();
    } else {
        mainWindow.show();
    }
});

var willQuit = false;

app.on('before-quit', function() {
    willQuit = true;
});

app.on('ready', appReady);

function initWindow() {
    var win = new BrowserWindow({
        'title': APP_NAME,
        // Standard icon looks somehow very thin in the taskbar
        'icon': path.resolve(path.join(__dirname, 'icons', 'tray', 'icon-tray.png')),
        'node-integration': false,
        'accept-first-mouse': true,
        'show': false,
        'x': mainWindowState.x,
        'y': mainWindowState.y,
        'width': mainWindowState.width,
        'height': mainWindowState.height,
        'preload': path.resolve(path.join(__dirname, 'preload.js')),
        'web-preferences': {
            'web-security': false
        }
    });

    if (mainWindowState.isMaximized) {
        win.maximize();
    }

    if (env.name === 'development') {
        devHelper.setDevMenu();
        win.openDevTools();
    }

    return win;
}

function appReady() {
    let appWindow;

    appWindow = initWindow();
    appWindow.hide();
    appWindow.webContents.on('did-finish-load', function() {
        //prevent flicker workaround
        mainWindow.setAlwaysOnTop(true);
        appWindow.show();
        setTimeout(function() {
            mainWindow.close();
        }, 100);
    });

    mainWindow = initWindow();
    mainWindow.loadUrl(INDEX);

    tray.createAppTray(mainWindow);
    tray.bindOnQuit(onQuitApp);

    appWindow.on('close', function(event) {
        flagQuitApp = true;
        tray.destroy();
    });

    mainWindow.on('close', function(event) {
        if (mainWindow !== null && !flagQuitApp) {
            tray.minimizeMainWindow();
            event.preventDefault();
        } else {
           mainWindowState.saveState(mainWindow);
           appWindow.close();
        }
    });

    mainWindow.on('closed', function() {
        mainWindow = null;
    });

    mainWindow.webContents.on('did-finish-load', function() {
        mainWindow.show();
    });

    mainWindow.webContents.on('new-window', function(ev, url, target) {
        if (target === '_system') {
            ev.preventDefault();
            require('shell').openExternal(url);
        } else if (target === '_blank') {
            ev.preventDefault();
            appWindow.loadUrl(url);
        }
    });
}

function onQuitApp() {
    if (!flagQuitApp) {
        flagQuitApp = true;
        if (mainWindow) {
            mainWindow.close();
        }
    }
}

function quit() {
    if (process.platform !== 'darwin') {
        app.quit();
    }
}

ipc.on('open-dev', function() {
    mainWindow.openDevTools();
});

ipc.on('unread-changed', function(event, unread) {
    let showAlert = (unread !== null && unread !== undefined && unread !== '');
    if (process.platform === 'darwin') {
        app.dock.setBadge(String(unread || ''));
    }
    tray.showTrayAlert(showAlert);
});
<|endoftext|>


<commit_before>var engine = require("engine.io-stream/client"),
  multilevel = require('multilevel'),
  manifest = require('./manifest.json');

var connection = engine('/messages'),
  db = multilevel.client(manifest);

connection.pipe(db.createRpcStream()).pipe(connection);

document.querySelector('form').addEventListener('submit', function (event) {
  var message = document.querySelector('input').value;
  if (message) {
    db.put(Date.now(), { text: message });
  }
  event.preventDefault();
});

window.db = db;
<commit_msg>static stream of messages<commit_after>var engine = require("engine.io-stream/client"),
  multilevel = require('multilevel'),
  manifest = require('./manifest.json');

var connection = engine('/messages'),
  db = multilevel.client(manifest);

connection.pipe(db.createRpcStream()).pipe(connection);

document.querySelector('form').addEventListener('submit', function (event) {
  var message = document.querySelector('input').value;
  if (message) {
    db.put(Date.now(), { text: message });
  }
  event.preventDefault();
});

db.createReadStream().on('data', function (item) {
  var li = document.createElement('li');
  li.innerHTML = item.value.text;
  document.querySelector('ul#messages').appendChild(li);
});

window.db = db;
<|endoftext|>


<commit_before>
var Transform = require('../../Transform');
var isType = require('../../helper/isType');
var UglifyJS = require('uglify-js');
var fs = require('fs');
var path = require('path');
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var SourceMapGenerator = require('source-map').SourceMapGenerator;

var _loader = (function() {
	var src = fs.readFileSync(require.resolve('./loader'), 'utf8');

	var loader = UglifyJS.minify(src, {
		fromString: true,
		outSourceMap: '/loader.js'
	});

	loader.src = src;
	return loader;
}());

function createLoader(loaderPath) {
	loaderPath = loaderPath || '/loader.js';

	var map = JSON.parse(_loader.map);
	map.file = loaderPath;
	map.sources = [loaderPath];

	return {
		event: 'update',
		path: loaderPath,
		content: {
			type: 'application/javascript',
			data: _loader.src,
			minified: _loader.code,
			sourceMap: map,
			dependencies: []
		}
	};
}

function loadJavaScriptAsset(asset) {
	var mappings = [];
	var map = new SourceMapConsumer(asset.content.sourceMap);
	map.eachMapping(function(mapping) {
		mappings.push(mapping);
	});

	return {
		mappings: mappings,
		numberOfLines: asset.content.minified.split('\n').length,
		asset: asset
	};
}

function addModuleSourceMap(generator, module) {
	var lineOffset = generator.lineOffset;
	var mappings = module.mappings;

	for (var i = 0; i < mappings.length; i++) {
		var inputMapping = mappings[i];
		var outputMapping = {
			generated: {
				line: inputMapping.generatedLine + lineOffset,
				column: inputMapping.generatedColumn
			},
			original: {
				line: inputMapping.originalLine,
				column: inputMapping.originalColumn
			},
			source: inputMapping.source,
			name: inputMapping.name
		};

		generator.addMapping(outputMapping);
	}

	generator.lineOffset += module.numberOfLines;
	return generator;
}

module.exports = Transform.create(function(options) {
	options = options || {};
	var entryPath = ('' + [options.entryPath]) || '/app.js';
	var outputPath = ('' + [options.outputPath]) || (entryPath.replace(/\.js$/, '') + '.bundle.js');
	var outputMapPath = ('' + [options.outputMapPath]) || (outputPath + '.map');
	var loaderPath = ('' + [options.loaderPath]) || '/loader.js';
	var loader = null;
	var modules = {};

	var bundleHasBeenBuilt = false;
	var bundleErrors = [];

	var bundleLastTime = Date.now();
	var bundleTimer = 0;
	var bundleCallback;

	function resolvePath(currentPath, requirePath) {
		if (/^\.+\//.test(requirePath)) {
			requirePath = path.resolve(path.dirname(currentPath), requirePath);
		}

		if (/^\//.test(requirePath)) {
			return modules[requirePath + '.js'] || modules[requirePath];
		} else {
			var segments = path.dirname(currentPath).replace(/^\//, '').split('/');
			segments.unshift('');

			for (var i = segments.length; i > 0; i--) {
				var commonPath = segments.slice(0, i).join('/') + '/node_modules/' + requirePath;
				var requiredModule =
					modules[commonPath + '.js'] ||
					modules[commonPath + '/index.js'] ||
					modules[commonPath];

				if (requiredModule) {
					return requiredModule;
				}
			}
		}
	}

	function bundleError(message) {
		var error = new Error(message);
		if (bundleHasBeenBuilt) {
			bundleCallback(error);
		} else {
			bundleErrors.push(error);
			if (!bundleTimer) {
				bundleTimer = setTimeout(function() {
					bundleErrors.forEach(function(error) {
						bundleCallback(error);
					});
				}, 2000);
			}
		}
	}

	function createBundle() {
		clearTimeout(bundleTimer);
		bundleTimer = 0;
		bundleErrors = [];

		var now = Date.now();
		var remainingTime = 100 - (now - bundleLastTime);
		if (remainingTime > 0) {
			bundleTimer = setTimeout(createBundle, remainingTime);
			return;
		}

		bundleLastTime = now;
		var startTime = now;

		var entryModule = resolvePath('/', entryPath);
		if (!entryModule) {
			return bundleError('Could not find JS entry module: ' + entryPath);
		}

		var usedModules = {};
		var missingModules = [entryModule];
		var index = 0;

		while (missingModules.length > 0) {
			var module = missingModules.shift();
			usedModules[module.asset.path] = module;

			module.index = index++;
			module.dependencies = {};

			var requirePaths = module.asset.content.dependencies;
			for (var i = 0; i < requirePaths.length; i++) {
				var requirePath = requirePaths[i];
				var requireModule = resolvePath(module.asset.path, requirePath);
				if (!requireModule) {
					return bundleError('In module ' + module.asset.path + ' could not find required module: ' + requirePath);
				}

				module.dependencies[requirePath] = requireModule;
				if (!(requireModule.asset.path in usedModules)) {
					missingModules.push(requireModule);
				}
			}
		}

		usedModules = Object.keys(usedModules).map(function(modulePath, index) {
			return usedModules[modulePath];
		});

		var bundleSourceMap = new SourceMapGenerator({
			file: outputPath
		});
		bundleSourceMap.lineOffset = 0;
		addModuleSourceMap(bundleSourceMap, loader);

		var loaderMappings = {};
		var loaderModules = usedModules.map(function(module) {
			addModuleSourceMap(bundleSourceMap, module);

			for (var requirePath in module.dependencies) {
				var requireModule = module.dependencies[requirePath];

				loaderMappings[requirePath] = loaderMappings[requirePath] || {};
				loaderMappings[requirePath][module.index] = requireModule.index;
			}

			return module.asset.content.minified;
		});

		loaderModules = loaderModules.join(',\n');
		loaderMappings = '{' + Object.keys(loaderMappings).sort().map(function(requirePath) {
			var mapping = loaderMappings[requirePath];
			return (JSON.stringify(requirePath) + ':{' +
				Object.keys(mapping).sort().map(function(from) {
					return from + ':' + mapping[from];
				}).join(',') + '}'
			);
		}).join(',') + '}';

		var bundle = loader.asset.content.minified.replace(/\[\],\{\},0/, function() {
			return '[\n' + loaderModules + '],' + loaderMappings + ',0';
		}) + '\n//@ sourceMappingURL=' + path.relative(path.dirname(outputPath), outputMapPath);

		var endTime = new Date();
		var bundleTime = endTime - startTime;

		bundleHasBeenBuilt = true;

		bundleCallback(null, {
			event: 'update',
			path: outputPath,
			content: {
				type: 'application/javascript',
				data: bundle
			},
			transforms: [
				{
					name: 'bundleJavaScript',
					importedModules: Object.keys(modules).length,
					usedModules: Object.keys(usedModules).length,
					time: bundleTime
				}
			]
		});

		bundleCallback(null, {
			event: 'update',
			path: outputMapPath,
			content: {
				type: 'application/json',
				data: bundleSourceMap.toString()
			},
			transforms: [
				{
					name: 'bundleJavaScript',
					importedModules: Object.keys(modules).length,
					usedModules: Object.keys(usedModules).length,
					time: bundleTime
				}
			]
		});
	}

	return function(asset, callback) {
		callback(null, asset);

		if (asset.event === 'delete') {
			delete modules[asset.path];
		} else if (asset.event === 'update' && isType.javaScript(asset)) {

			if (!asset.content.minified) {
				callback(new Error('Can only bundle minified JavaScript modules.'));
				return;
			}

			if (!loader) {
				loader = loadJavaScriptAsset(createLoader(loaderPath));
				callback(null, loader.asset);
			}

			modules[asset.path] = loadJavaScriptAsset(asset);
			bundleCallback = callback;
			createBundle();

		}
	};
});
<commit_msg>Aesthetics in bundled code.<commit_after>
var Transform = require('../../Transform');
var isType = require('../../helper/isType');
var UglifyJS = require('uglify-js');
var fs = require('fs');
var path = require('path');
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var SourceMapGenerator = require('source-map').SourceMapGenerator;

var _loader = (function() {
	var src = fs.readFileSync(require.resolve('./loader'), 'utf8');

	var loader = UglifyJS.minify(src, {
		fromString: true,
		outSourceMap: '/loader.js'
	});

	loader.src = src;
	return loader;
}());

function createLoader(loaderPath) {
	loaderPath = loaderPath || '/loader.js';

	var map = JSON.parse(_loader.map);
	map.file = loaderPath;
	map.sources = [loaderPath];

	return {
		event: 'update',
		path: loaderPath,
		content: {
			type: 'application/javascript',
			data: _loader.src,
			minified: _loader.code,
			sourceMap: map,
			dependencies: []
		}
	};
}

function loadJavaScriptAsset(asset) {
	var mappings = [];
	var map = new SourceMapConsumer(asset.content.sourceMap);
	map.eachMapping(function(mapping) {
		mappings.push(mapping);
	});

	return {
		mappings: mappings,
		numberOfLines: asset.content.minified.split('\n').length,
		asset: asset
	};
}

function addModuleSourceMap(generator, module) {
	var lineOffset = generator.lineOffset;
	var mappings = module.mappings;

	for (var i = 0; i < mappings.length; i++) {
		var inputMapping = mappings[i];
		var outputMapping = {
			generated: {
				line: inputMapping.generatedLine + lineOffset,
				column: inputMapping.generatedColumn
			},
			original: {
				line: inputMapping.originalLine,
				column: inputMapping.originalColumn
			},
			source: inputMapping.source,
			name: inputMapping.name
		};

		generator.addMapping(outputMapping);
	}

	generator.lineOffset += module.numberOfLines;
	return generator;
}

module.exports = Transform.create(function(options) {
	options = options || {};
	var entryPath = ('' + [options.entryPath]) || '/app.js';
	var outputPath = ('' + [options.outputPath]) || (entryPath.replace(/\.js$/, '') + '.bundle.js');
	var outputMapPath = ('' + [options.outputMapPath]) || (outputPath + '.map');
	var loaderPath = ('' + [options.loaderPath]) || '/loader.js';
	var loader = null;
	var modules = {};

	var bundleHasBeenBuilt = false;
	var bundleErrors = [];

	var bundleLastTime = Date.now();
	var bundleTimer = 0;
	var bundleCallback;

	function resolvePath(currentPath, requirePath) {
		if (/^\.+\//.test(requirePath)) {
			requirePath = path.resolve(path.dirname(currentPath), requirePath);
		}

		if (/^\//.test(requirePath)) {
			return modules[requirePath + '.js'] || modules[requirePath];
		} else {
			var segments = path.dirname(currentPath).replace(/^\//, '').split('/');
			segments.unshift('');

			for (var i = segments.length; i > 0; i--) {
				var commonPath = segments.slice(0, i).join('/') + '/node_modules/' + requirePath;
				var requiredModule =
					modules[commonPath + '.js'] ||
					modules[commonPath + '/index.js'] ||
					modules[commonPath];

				if (requiredModule) {
					return requiredModule;
				}
			}
		}
	}

	function bundleError(message) {
		var error = new Error(message);
		if (bundleHasBeenBuilt) {
			bundleCallback(error);
		} else {
			bundleErrors.push(error);
			if (!bundleTimer) {
				bundleTimer = setTimeout(function() {
					bundleErrors.forEach(function(error) {
						bundleCallback(error);
					});
				}, 2000);
			}
		}
	}

	function createBundle() {
		clearTimeout(bundleTimer);
		bundleTimer = 0;
		bundleErrors = [];

		var now = Date.now();
		var remainingTime = 100 - (now - bundleLastTime);
		if (remainingTime > 0) {
			bundleTimer = setTimeout(createBundle, remainingTime);
			return;
		}

		bundleLastTime = now;
		var startTime = now;

		var entryModule = resolvePath('/', entryPath);
		if (!entryModule) {
			return bundleError('Could not find JS entry module: ' + entryPath);
		}

		var usedModules = {};
		var missingModules = [entryModule];
		var index = 0;

		while (missingModules.length > 0) {
			var module = missingModules.shift();
			usedModules[module.asset.path] = module;

			module.index = index++;
			module.dependencies = {};

			var requirePaths = module.asset.content.dependencies;
			for (var i = 0; i < requirePaths.length; i++) {
				var requirePath = requirePaths[i];
				var requireModule = resolvePath(module.asset.path, requirePath);
				if (!requireModule) {
					return bundleError('In module ' + module.asset.path + ' could not find required module: ' + requirePath);
				}

				module.dependencies[requirePath] = requireModule;
				if (!(requireModule.asset.path in usedModules)) {
					missingModules.push(requireModule);
				}
			}
		}

		usedModules = Object.keys(usedModules).map(function(modulePath, index) {
			return usedModules[modulePath];
		});

		var bundleSourceMap = new SourceMapGenerator({
			file: outputPath
		});
		bundleSourceMap.lineOffset = 0;
		addModuleSourceMap(bundleSourceMap, loader);

		var loaderMappings = {};
		var loaderModules = usedModules.map(function(module) {
			addModuleSourceMap(bundleSourceMap, module);

			for (var requirePath in module.dependencies) {
				var requireModule = module.dependencies[requirePath];

				loaderMappings[requirePath] = loaderMappings[requirePath] || {};
				loaderMappings[requirePath][module.index] = requireModule.index;
			}

			return module.asset.content.minified;
		});

		loaderModules = loaderModules.join(',\n');
		loaderMappings = '{' + Object.keys(loaderMappings).sort().map(function(requirePath) {
			var mapping = loaderMappings[requirePath];
			return (JSON.stringify(requirePath) + ':{' +
				Object.keys(mapping).sort().map(function(from) {
					return from + ':' + mapping[from];
				}).join(',') + '}'
			);
		}).join(',') + '}';

		var bundle = loader.asset.content.minified.replace(/\[\],\{\},0/, function() {
			return '[\n' + loaderModules + '\n],' + loaderMappings + ',0';
		}) + '\n//@ sourceMappingURL=' + path.relative(path.dirname(outputPath), outputMapPath);

		var endTime = new Date();
		var bundleTime = endTime - startTime;

		bundleHasBeenBuilt = true;

		bundleCallback(null, {
			event: 'update',
			path: outputPath,
			content: {
				type: 'application/javascript',
				data: bundle
			},
			transforms: [
				{
					name: 'bundleJavaScript',
					importedModules: Object.keys(modules).length,
					usedModules: Object.keys(usedModules).length,
					time: bundleTime
				}
			]
		});

		bundleCallback(null, {
			event: 'update',
			path: outputMapPath,
			content: {
				type: 'application/json',
				data: bundleSourceMap.toString()
			},
			transforms: [
				{
					name: 'bundleJavaScript',
					importedModules: Object.keys(modules).length,
					usedModules: Object.keys(usedModules).length,
					time: bundleTime
				}
			]
		});
	}

	return function(asset, callback) {
		callback(null, asset);

		if (asset.event === 'delete') {
			delete modules[asset.path];
		} else if (asset.event === 'update' && isType.javaScript(asset)) {

			if (!asset.content.minified) {
				callback(new Error('Can only bundle minified JavaScript modules.'));
				return;
			}

			if (!loader) {
				loader = loadJavaScriptAsset(createLoader(loaderPath));
				callback(null, loader.asset);
			}

			modules[asset.path] = loadJavaScriptAsset(asset);
			bundleCallback = callback;
			createBundle();

		}
	};
});
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *//**
  * Sample React Native App
  * https://github.com/facebook/react-native
  */
 'use strict';

 import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   View
 } from 'react-native';

 import {
   ViroSceneNavigator,
   ViroScene,
   ViroBox,
   ViroMaterials,
   ViroNode,
   ViroOrbitCamera,
   ViroCamera,
   ViroAmbientLight,
   ViroOmniLight,
   ViroSpotLight,
   ViroDirectionalLight,
   ViroImage,
   ViroVideo,
   Viro360Image,
   Viro360Video,
   ViroFlexView,
   ViroUtils,
   ViroText,
   ViroAnimations,
   ViroAnimatedComponent,
   ViroQuad,
   ViroSkyBox,
   ViroSphere,
   Viro3DObject,
   ViroSpinner,
 } from 'react-viro';

 let polarToCartesian = ViroUtils.polarToCartesian;

var createReactClass = require('create-react-class');

 // **This test has not been done.  This is placeholder for scene and navigation arrows**

 var ViroFlexViewLayoutTest = createReactClass({

   getInitialState() {
     return {
        flexViewLayout:1,
     };
   },

   render: function() {
     return (
      <ViroScene>
        {this._chooseFlexLayout()}
        <ViroText style={styles.baseTextTwo}  position={[-4,0, -3]} width={2} height={2}
                 text={"Change flexbox Layout"}
                 onClick={this._toggleFlexboxLayout}/>
      </ViroScene>

     );
   },

  _toggleFlexboxLayout() {
    var newflexboxLayout = this.state.flexViewLayout + 1;
    if (newflexboxLayout > 4){
        newflexboxLayout = 1;
    }
    console.log("New flexlayout: " + newflexboxLayout);
    this.setState({
                  flexViewLayout:newflexboxLayout
            });
  },
  _chooseFlexLayout() {
      if(this.state.flexViewLayout==1) {
          return this._flexLayoutTwo();
      } else if(this.state.flexViewLayout==2) {
          return this._flexLayoutTwo();
      } else if(this.state.flexViewLayout==3) {
          return this._flexLayoutThree();
      } else if(this.state.flexLayout==4) {
          return this._flexLayoutOne();
      }
},
  _flexLayoutOne() {
    return (
      <ViroFlexView style={styles.titleContainer} position={[0, 0, -4]} rotation={[0, 0, 0]} height={2} width={4}>
        <ViroFlexView style={styles.rowContainer}>
          <ViroText style={styles.prodDescriptionText} text="Refresh Rate: 240CMR(Effective)" />
        </ViroFlexView>
        <ViroFlexView style={styles.rowContainer}>
          <ViroText style={styles.prodDescriptionText} text="Backlight: LED" />
        </ViroFlexView>
        <ViroFlexView style={styles.rowContainer}>
          <ViroText style={styles.prodDescriptionText} text="Dimensions(W x H x D): TV without stand: 44.9 x 24.5 x 2.4" />
        </ViroFlexView>
      </ViroFlexView>
    );
  },

  _flexLayoutTwo() {
    return (
      <ViroFlexView
        style={styles.galleryContainer} position={[0, 0, -4]}
        width={5} height={5}  rotation={[0, 0, 0]}>
        <ViroFlexView style={styles.horizontalFlex}>
          <ViroFlexView style={styles.centerText}>
            <ViroText style={styles.elementText} text="Real Estate"/>
            <ViroImage style={{flex:.8}} source={require('./res/sun_2302.jpg')} />
          </ViroFlexView>
          <ViroFlexView style={styles.centerText}>
            <ViroText style={styles.elementText} text="Adventure"/>
            <ViroImage style={{flex:.8}} source={require('./res/seattle1.jpg')} />
          </ViroFlexView>
        </ViroFlexView>
        <ViroFlexView style={styles.horizontalFlex} >
          <ViroFlexView style={styles.centerText}>
            <ViroText style={styles.elementText} text="Travel"/>
            <ViroImage style={{flex:.8}} source={require('./res/heart_d.jpg')} />
          </ViroFlexView>
          <ViroFlexView style={styles.centerText}>
            <ViroText style={styles.elementText} text="Sports"/>
            <ViroImage style={{flex:.8}} source={require('./res/grid_bg.jpg')} />
          </ViroFlexView>
        </ViroFlexView>
      </ViroFlexView>
    );
  },

  //Taken from: https://github.com/browniefed/react-native-screens/blob/master/screens/login/index.js
  _flexLayoutThree() {
    return (
      <ViroFlexView position={[0, 0, -4]} height={5} width={5}>
        <ViroFlexView style={{flex:1}} >
          <ViroFlexView style={styles.layout3markWrap} >
            <ViroImage style={styles.layout3mark} source={require('./res/card_main.png')} />
          </ViroFlexView>
          <ViroFlexView style={styles.layout3wrapper}>
            <ViroFlexView style={styles.layout3inputWrap}>
              <ViroFlexView style={styles.layout3iconWrap}>
                <ViroImage source={require('./res/grid_bg.jpg')} style={styles.layout3icon} />
              </ViroFlexView>
              <ViroText text="Username" style={styles.layout3input}  />
            </ViroFlexView>
            <ViroFlexView style={styles.layout3inputWrap}>
              <ViroFlexView style={styles.layout3iconWrap}>
                <ViroImage source={require('./res/grid_bg.jpg')} style={styles.layout3icon} />
              </ViroFlexView>
              <ViroText style={styles.layout3input} text="Password" />
            </ViroFlexView>
            <ViroFlexView style={{flex:.3}}>
                <ViroText style={styles.layout3forgotPasswordText} text="Forgot Password?" />
              </ViroFlexView>
              <ViroFlexView style={styles.layout3button}>
                <ViroText style={styles.layout3buttonText} text="First In" />
              </ViroFlexView>
          </ViroFlexView>
          <ViroFlexView style={styles.layout3container}>
            <ViroFlexView style={styles.layout3signupWrap}>
                <ViroFlexView style={{flex:1, backgroundColor: "#ff0000"}}>
                  <ViroText style={styles.layout3signupLinkText} text="Second Up"/>
                </ViroFlexView>
            </ViroFlexView>
          </ViroFlexView>
        </ViroFlexView>
      </ViroFlexView>
    );
  },

  _flexLayoutFour() {
    return (
      <ViroFlexView position={[0, 0, -4]} width={2} height={2} style={{flexDirection: 'column'}}>
        <ViroVideo style={{flex:.5}} source={require('./res/Climber.mp4')} />
        <ViroImage style={{flex: 1}} source={require('./res/seattle1.jpg')} />
      </ViroFlexView>
    );
  },

 });
var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  rowContainer: {
    flex: 1,
    flexDirection: 'row',
  },
  elementText: {
    fontSize: 30,
    color: '#ffffff',
    textAlign: 'center',
    flex: 1,
  },
  baseTextTwo: {
      fontFamily: 'Arial',
      fontSize: 20,
      color: '#ffffff',
      flex: 1,
      textAlignVertical: 'center',
      textAlign: 'center',
  },
  titleContainer: {
      flexDirection: 'column',
      padding: .2,
      color: '#ffffff',
  },
  prodDescriptionText: {
    fontFamily: 'sans-serif-light',
    fontSize: 20,
    color: '#ffffff',
    textAlignVertical: 'center',
    textAlign: 'left',
    flex: 1,
  },
  galleryContainer: {
    flexDirection: 'column',
    padding: .1,
    margin: .1,
    backgroundColor: "#00ff00"
  },
  horizontalFlex: {
    backgroundColor: "#ff0000",
    flex: .5,
    flexDirection: 'row',
    margin: .1,
  },
  centerText: {
    flex: .5,
    padding: .2,
    margin: .1,
    flexDirection: 'column',
  },
  layout3container: {
    flex: 1,
  },
  layout3markWrap: {
    flex: 1,
    paddingVertical: .10,
  },
  layout3mark: {
    flex: 1,
  },
  layout3wrapper: {
    paddingVertical: .10,
  },
  layout3inputWrap: {
    flexDirection: "row",
    marginVertical: .10,
    height: .40,
    backgroundColor: "#CCC"
  },
  layout3iconWrap: {
    paddingHorizontal: .7,
    alignItems: "center",
    justifyContent: "center",
  },
  layout3icon: {
    height: .5,
    width: .5,
  },
  layout3input: {
    flex: 1,
    paddingHorizontal: .10,
    backgroundColor: "#fff",
    fontSize: 20,
  },
  layout3button: {
    backgroundColor: "#FF3366",
    paddingVertical: .05,
    alignItems: "center",
    justifyContent: "center",
    marginTop: .05,
    flex: 2,
  },
  layout3buttonText: {
    color: "#FFF",
    fontSize: 18,
    textAlign: 'center',
  },
  layout3forgotPasswordText: {
    color: "#D8D8D8",
    textAlign: "right",
    paddingRight: .15,
    fontSize: 20,
  },
  layout3signupWrap: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
  },
  layout3accountText: {
    color: "#D8D8D8",
    fontSize: 18,
  },
  layout3signupLinkText: {
    color: "#FFF",
    marginLeft: .2,
    fontSize: 20,
  }
});

ViroMaterials.createMaterials({
  redColor: {
  fresnelExponent: .5,
   shininess: 2.0,
    diffuseColor: "#ff0000"
  },
  blue: {
      shininess: 2.0,
      lightingModel: "Lambert",
      diffuseColor: "#0000ff"
    },
  layout3background: {
    diffuseTexture: require('./res/grid_bg.jpg')
  },
  heart: {
      lightingModel: "Phong",
      diffuseTexture: require('./res/earth.png'),
    },
 });
 module.exports = ViroFlexViewLayoutTest;
<commit_msg>Fix FlexViewLayoutTest<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *//**
  * Sample React Native App
  * https://github.com/facebook/react-native
  */
 'use strict';

 import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   View
 } from 'react-native';

 import {
   ViroSceneNavigator,
   ViroScene,
   ViroBox,
   ViroMaterials,
   ViroNode,
   ViroOrbitCamera,
   ViroCamera,
   ViroAmbientLight,
   ViroOmniLight,
   ViroSpotLight,
   ViroDirectionalLight,
   ViroImage,
   ViroVideo,
   Viro360Image,
   Viro360Video,
   ViroFlexView,
   ViroUtils,
   ViroText,
   ViroAnimations,
   ViroAnimatedComponent,
   ViroQuad,
   ViroSkyBox,
   ViroSphere,
   Viro3DObject,
   ViroSpinner,
 } from 'react-viro';

var ReleaseMenu = require("./ReleaseMenu.js");

let polarToCartesian = ViroUtils.polarToCartesian;

var createReactClass = require('create-react-class');

 // **This test has not been done.  This is placeholder for scene and navigation arrows**

 var ViroFlexViewLayoutTest = createReactClass({

   getInitialState() {
     return {
        flexViewLayout:1,
     };
   },

   render: function() {
     return (
      <ViroScene>
        <ReleaseMenu sceneNavigator={this.props.sceneNavigator}/>
        {this._chooseFlexLayout()}
        <ViroText style={styles.baseTextTwo}  position={[0,-3, -3]} width={2} height={2}
                 text={"Change flexbox Layout"}
                 onClick={this._toggleFlexboxLayout}/>
      </ViroScene>

     );
   },

  _toggleFlexboxLayout() {
    var newflexboxLayout = this.state.flexViewLayout + 1;
    if (newflexboxLayout > 4){
        newflexboxLayout = 1;
    }
    console.log("New flexlayout: " + newflexboxLayout);
    this.setState({
                  flexViewLayout:newflexboxLayout
            });
  },
  _chooseFlexLayout() {
      if(this.state.flexViewLayout==1) {
          return this._flexLayoutFour();
      } else if(this.state.flexViewLayout==2) {
          return this._flexLayoutOne();
      } else if(this.state.flexViewLayout==3) {
          return this._flexLayoutThree();
      } else if(this.state.flexViewLayout==4) {
          return this._flexLayoutTwo();
      }
},
  _flexLayoutOne() {
    return (
      <ViroFlexView style={styles.titleContainer} position={[0, 0, -4]} rotation={[0, 0, 0]} height={2} width={4}>
        <ViroFlexView style={styles.rowContainer}>
          <ViroText style={styles.prodDescriptionText} text="Refresh Rate: 240CMR(Effective)" />
        </ViroFlexView>
        <ViroFlexView style={styles.rowContainer}>
          <ViroText style={styles.prodDescriptionText} text="Backlight: LED" />
        </ViroFlexView>
        <ViroFlexView style={styles.rowContainer}>
          <ViroText style={styles.prodDescriptionText} text="Dimensions(W x H x D): TV without stand: 44.9 x 24.5 x 2.4" />
        </ViroFlexView>
      </ViroFlexView>
    );
  },

  _flexLayoutTwo() {
    return (
      <ViroFlexView
        style={styles.galleryContainer} position={[0, 0, -4]}
        width={5} height={5}  rotation={[0, 0, 0]}>
        <ViroFlexView style={styles.horizontalFlex}>
          <ViroFlexView style={styles.centerText}>
            <ViroText style={styles.elementText} text="Real Estate"/>
            <ViroImage style={{flex:.8}} source={require('./res/sun_2302.jpg')} />
          </ViroFlexView>
          <ViroFlexView style={styles.centerText}>
            <ViroText style={styles.elementText} text="Adventure"/>
            <ViroImage style={{flex:.8}} source={require('./res/seattle1.jpg')} />
          </ViroFlexView>
        </ViroFlexView>
        <ViroFlexView style={styles.horizontalFlex} >
          <ViroFlexView style={styles.centerText}>
            <ViroText style={styles.elementText} text="Travel"/>
            <ViroImage style={{flex:.8}} source={require('./res/heart_d.jpg')} />
          </ViroFlexView>
          <ViroFlexView style={styles.centerText}>
            <ViroText style={styles.elementText} text="Sports"/>
            <ViroImage style={{flex:.8}} source={require('./res/grid_bg.jpg')} />
          </ViroFlexView>
        </ViroFlexView>
      </ViroFlexView>
    );
  },

  //Taken from: https://github.com/browniefed/react-native-screens/blob/master/screens/login/index.js
  _flexLayoutThree() {
    return (
      <ViroFlexView position={[0, 0, -4]} height={5} width={5}>
        <ViroFlexView style={{flex:1}} >
          <ViroFlexView style={styles.layout3markWrap} >
            <ViroImage style={styles.layout3mark} source={require('./res/card_main.png')} />
          </ViroFlexView>
          <ViroFlexView style={styles.layout3wrapper}>
            <ViroFlexView style={styles.layout3inputWrap}>
              <ViroFlexView style={styles.layout3iconWrap}>
                <ViroImage source={require('./res/grid_bg.jpg')} style={styles.layout3icon} />
              </ViroFlexView>
              <ViroText text="Username" style={styles.layout3input}  />
            </ViroFlexView>
            <ViroFlexView style={styles.layout3inputWrap}>
              <ViroFlexView style={styles.layout3iconWrap}>
                <ViroImage source={require('./res/grid_bg.jpg')} style={styles.layout3icon} />
              </ViroFlexView>
              <ViroText style={styles.layout3input} text="Password" />
            </ViroFlexView>
            <ViroFlexView style={{flex:.3}}>
                <ViroText style={styles.layout3forgotPasswordText} text="Forgot Password?" />
              </ViroFlexView>
              <ViroFlexView style={styles.layout3button}>
                <ViroText style={styles.layout3buttonText} text="First In" />
              </ViroFlexView>
          </ViroFlexView>
          <ViroFlexView style={styles.layout3container}>
            <ViroFlexView style={styles.layout3signupWrap}>
                <ViroFlexView style={{flex:1, backgroundColor: "#ff0000"}}>
                  <ViroText style={styles.layout3signupLinkText} text="Second Up"/>
                </ViroFlexView>
            </ViroFlexView>
          </ViroFlexView>
        </ViroFlexView>
      </ViroFlexView>
    );
  },

  _flexLayoutFour() {
    return (
      <ViroFlexView position={[0, 0, -4]} width={2} height={2} style={{flexDirection: 'column'}}>
        <ViroVideo style={{flex:.5}} source={require('./res/Climber.mp4')} />
        <ViroImage style={{flex: 1}} source={require('./res/seattle1.jpg')} />
      </ViroFlexView>
    );
  },

 });
var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  rowContainer: {
    flex: 1,
    flexDirection: 'row',
  },
  elementText: {
    fontSize: 30,
    color: '#ffffff',
    textAlign: 'center',
    flex: 1,
  },
  baseTextTwo: {
      fontFamily: 'Arial',
      fontSize: 20,
      color: '#ffffff',
      flex: 1,
      textAlignVertical: 'center',
      textAlign: 'center',
  },
  titleContainer: {
      flexDirection: 'column',
      padding: .2,
      color: '#ffffff',
  },
  prodDescriptionText: {
    fontFamily: 'sans-serif-light',
    fontSize: 20,
    color: '#ffffff',
    textAlignVertical: 'center',
    textAlign: 'left',
    flex: 1,
  },
  galleryContainer: {
    flexDirection: 'column',
    padding: .1,
    margin: .1,
    backgroundColor: "#00ff00"
  },
  horizontalFlex: {
    backgroundColor: "#ff0000",
    flex: .5,
    flexDirection: 'row',
    margin: .1,
  },
  centerText: {
    flex: .5,
    padding: .2,
    margin: .1,
    flexDirection: 'column',
  },
  layout3container: {
    flex: 1,
  },
  layout3markWrap: {
    flex: 1,
    paddingVertical: .10,
  },
  layout3mark: {
    flex: 1,
  },
  layout3wrapper: {
    paddingVertical: .10,
  },
  layout3inputWrap: {
    flexDirection: "row",
    marginVertical: .10,
    height: .40,
    backgroundColor: "#CCC"
  },
  layout3iconWrap: {
    paddingHorizontal: .7,
    alignItems: "center",
    justifyContent: "center",
  },
  layout3icon: {
    height: .5,
    width: .5,
  },
  layout3input: {
    flex: 1,
    paddingHorizontal: .10,
    backgroundColor: "#fff",
    fontSize: 20,
  },
  layout3button: {
    backgroundColor: "#FF3366",
    paddingVertical: .05,
    alignItems: "center",
    justifyContent: "center",
    marginTop: .05,
    flex: 2,
  },
  layout3buttonText: {
    color: "#FFF",
    fontSize: 18,
    textAlign: 'center',
  },
  layout3forgotPasswordText: {
    color: "#D8D8D8",
    textAlign: "right",
    paddingRight: .15,
    fontSize: 20,
  },
  layout3signupWrap: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
  },
  layout3accountText: {
    color: "#D8D8D8",
    fontSize: 18,
  },
  layout3signupLinkText: {
    color: "#FFF",
    marginLeft: .2,
    fontSize: 20,
  }
});

ViroMaterials.createMaterials({
  redColor: {
  fresnelExponent: .5,
   shininess: 2.0,
    diffuseColor: "#ff0000"
  },
  blue: {
      shininess: 2.0,
      lightingModel: "Lambert",
      diffuseColor: "#0000ff"
    },
  layout3background: {
    diffuseTexture: require('./res/grid_bg.jpg')
  },
  heart: {
      lightingModel: "Phong",
      diffuseTexture: require('./res/earth.png'),
    },
 });
 module.exports = ViroFlexViewLayoutTest;
<|endoftext|>


<commit_before>angular.module('teleinfo.home', [])

    .controller('HomeCtrl', function HomeController($scope, $http) {

        $scope.value = undefined;
        $scope.indexcompteur = undefined;

        $http.get('/rest/inst/p')
            .success(function (data) {
                $scope.value = data/1000;
            });
        $http.get('/rest/inst/index')
            .success(function (data) {
                $scope.indexcompteur = data;
            });

        $scope.upperLimit = 6;
        $scope.lowerLimit = 0;
        $scope.unit = "kW";
        $scope.precision = 2;
        $scope.ranges = [
            {min: 0, max: 2.5, color: '#8DCA2F'},
            {min: 2.5, max: 3.5, color: '#FDC702'},
            {min: 3.5, max: 4.5, color: '#FF7700'},
            {min: 4.5, max: 6.0, color: '#C50200' }
        ];
    })

    // Directive ngRadialGauge adaptée de @stherrienaspnet
    // https://github.com/stherrienaspnet/ngRadialGauge
    // TODO Virer la dépendance avec jQuery !
    .factory('d3Service', ['$document', '$window', '$q', '$rootScope',
        function($document, $window, $q, $rootScope) {
            var d = $q.defer(),
                d3service = {
                    d3: function() { return d.promise; }
                };
            function onScriptLoad() {
                // Load client in the browser
                $rootScope.$apply(function() { d.resolve($window.d3); });
            }
            var scriptTag = $document[0].createElement('script');
            scriptTag.type = 'text/javascript';
            scriptTag.async = true;
            scriptTag.src = '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.min.js';
            scriptTag.onreadystatechange = function () {
                if (this.readyState == 'complete') onScriptLoad();
            };
            scriptTag.onload = onScriptLoad;

            var s = $document[0].getElementsByTagName('body')[0];
            s.appendChild(scriptTag);

            return d3service;
        }])

    .directive('ngRadialGauge', ['$window', '$timeout', 'd3Service',
        function ($window, $timeout, d3Service) {
            return {
                restrict: 'A',
                scope: {
                    lowerLimit: '=',
                    upperLimit: '=',
                    ranges: '=',
                    value: '=',
                    valueUnit: '=',
                    precision: '=',
                    label: '@',
                    onClick: '&'
                },
                link: function (scope, ele, attrs) {
                    "use strict";
                    d3Service.d3().then(function (d3) {
                        var renderTimeout;
                        var width = parseInt(attrs.width) || 300;
                        var innerRadius = Math.round((width * 130) / 300);
                        var outterRadius = Math.round((width * 145) / 300);
                        var majorGraduations = parseInt(attrs.majorGraduations - 1) || 5;
                        var minorGraduations = parseInt(attrs.minorGraduations) || 10;
                        var majorGraduationLenght = Math.round((width * 16) / 300);
                        var minorGraduationLenght = Math.round((width * 10) / 300);
                        var majorGraduationMarginTop = Math.round((width * 7) / 300);
                        var majorGraduationColor = attrs.majorGraduationColor || "#B0B0B0";
                        var minorGraduationColor = attrs.minorGraduationColor || "#D0D0D0";
                        var majorGraduationTextColor = attrs.majorGraduationTextColor || "#6C6C6C";
                        var needleColor = attrs.needleColor || "#416094";
                        var valueVerticalOffset = Math.round((width * 30) / 300);
                        var unactiveColor = "#D7D7D7";
                        var majorGraduationTextSize = parseInt(attrs.majorGraduationTextSize);
                        var needleValueTextSize = parseInt(attrs.needleValueTextSize);
                        var userFontStyle = attrs.fontStyle;

                        var svg = d3.select(ele[0])
                            .append('svg')
                            .attr('width', width)
                            .attr('height', width * 0.75);
                        var renderMajorGraduations = function (majorGraduationsAngles) {
                            var centerX = width / 2;
                            var centerY = width / 2;
                            //Render Major Graduations
                            $.each(majorGraduationsAngles, function (index, value) {
                                var cos1Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght));
                                var sin1Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght));
                                var cos2Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                                var sin2Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                                var x1 = centerX + cos1Adj;
                                var y1 = centerY + sin1Adj * -1;
                                var x2 = centerX + cos2Adj;
                                var y2 = centerY + sin2Adj * -1;
                                svg.append("svg:line")
                                    .attr("x1", x1)
                                    .attr("y1", y1)
                                    .attr("x2", x2)
                                    .attr("y2", y2)
                                    .style("stroke", majorGraduationColor);

                                renderMinorGraduations(majorGraduationsAngles, index);
                            });
                        };
                        var renderMinorGraduations = function (majorGraduationsAngles, indexMajor) {
                            var minorGraduationsAngles = [];

                            if (indexMajor > 0) {
                                var minScale = majorGraduationsAngles[indexMajor - 1];
                                var maxScale = majorGraduationsAngles[indexMajor];
                                var scaleRange = maxScale - minScale;

                                for (var i = 1; i < minorGraduations; i++) {
                                    var scaleValue = minScale + i * scaleRange / minorGraduations;
                                    minorGraduationsAngles.push(scaleValue);
                                }

                                var centerX = width / 2;
                                var centerY = width / 2;
                                //Render Minor Graduations
                                $.each(minorGraduationsAngles, function (indexMinor, value) {
                                    var cos1Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - minorGraduationLenght));
                                    var sin1Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - minorGraduationLenght));
                                    var cos2Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                                    var sin2Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                                    var x1 = centerX + cos1Adj;
                                    var y1 = centerY + sin1Adj * -1;
                                    var x2 = centerX + cos2Adj;
                                    var y2 = centerY + sin2Adj * -1;
                                    svg.append("svg:line")
                                        .attr("x1", x1)
                                        .attr("y1", y1)
                                        .attr("x2", x2)
                                        .attr("y2", y2)
                                        .style("stroke", minorGraduationColor);
                                });
                            }
                        };
                        var getMajorGraduationValues = function (minLimit, maxLimit) {
                            var scaleRange = maxLimit - minLimit;
                            var majorGraduationValues = [];
                            for (var i = 0; i <= majorGraduations; i++) {
                                var scaleValue = minLimit + i * scaleRange / (majorGraduations);
                                majorGraduationValues.push(scaleValue.toFixed(scope.precision));
                            }

                            return majorGraduationValues;
                        };
                        var getMajorGraduationAngles = function () {
                            var scaleRange = 240;
                            var minScale = -120;
                            var graduationsAngles = [];
                            for (var i = 0; i <= majorGraduations; i++) {
                                var scaleValue = minScale + i * scaleRange / (majorGraduations);
                                graduationsAngles.push(scaleValue);
                            }

                            return graduationsAngles;
                        };
                        var renderMajorGraduationTexts = function (majorGraduationsAngles, majorGraduationValues) {
                            if (!scope.ranges) return;

                            var centerX = width / 2;
                            var centerY = width / 2;
                            var textVerticalPadding = 5;
                            var textHorizontalPadding = 5;

                            var lastGraduationValue = majorGraduationValues[majorGraduationValues.length - 1];
                            var textSize = isNaN(majorGraduationTextSize) ? (width * 12) / 300 : majorGraduationTextSize;
                            var fontStyle = textSize + "px Courier";

                            var dummyText = svg.append("text")
                                .attr("x", centerX)
                                .attr("y", centerY)
                                .attr("fill", "transparent")
                                .attr("text-anchor", "middle")
                                .style("font", fontStyle)
                                .text(lastGraduationValue + scope.valueUnit);

                            var textWidth = dummyText.node().getBBox().width;

                            for (var i = 0; i < majorGraduationsAngles.length; i++) {
                                var angle = majorGraduationsAngles[i];
                                var cos1Adj = Math.round(Math.cos((90 - angle) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght - textHorizontalPadding));
                                var sin1Adj = Math.round(Math.sin((90 - angle) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght - textVerticalPadding));

                                var sin1Factor = 1;
                                if (sin1Adj < 0) sin1Factor = 1.1;
                                if (sin1Adj > 0) sin1Factor = 0.9;
                                if (cos1Adj > 0) {
                                    if (angle > 0 && angle < 45) {
                                        cos1Adj -= textWidth / 2;
                                    } else {
                                        cos1Adj -= textWidth;
                                    }
                                }
                                if (cos1Adj < 0) {
                                    if (angle < 0 && angle > -45) {
                                        cos1Adj -= textWidth / 2;
                                    }
                                }
                                if (cos1Adj == 0) {
                                    cos1Adj -= angle == 0 ? textWidth / 4 : textWidth / 2;
                                }

                                var x1 = centerX + cos1Adj;
                                var y1 = centerY + sin1Adj * sin1Factor * -1;

                                svg.append("text")
                                    .attr("class", "mtt-majorGraduationText")
                                    .style("font", fontStyle)
                                    .attr("text-align", "center")
                                    .attr("x", x1)
                                    .attr("dy", y1)
                                    .attr("fill", majorGraduationTextColor)
                                    .text(majorGraduationValues[i] + scope.valueUnit);
                            }
                        };
                        var renderGraduationNeedle = function (minLimit, maxLimit) {
                            var centerX = width / 2;
                            var centerY = width / 2;
                            var centerColor;

                            if (typeof scope.value === 'undefined') {
                                centerColor = unactiveColor;
                            } else {
                                centerColor = needleColor;
                                var needleValue = ((scope.value - minLimit) * 240 / (maxLimit - minLimit)) - 30;
                                var thetaRad = needleValue * Math.PI / 180;

                                var needleLen = innerRadius - majorGraduationLenght - majorGraduationMarginTop;
                                var needleRadius = (width * 2.5) / 300;
                                var topX = centerX - needleLen * Math.cos(thetaRad);
                                var topY = centerY - needleLen * Math.sin(thetaRad);
                                var leftX = centerX - needleRadius * Math.cos(thetaRad - Math.PI / 2);
                                var leftY = centerY - needleRadius * Math.sin(thetaRad - Math.PI / 2);
                                var rightX = centerX - needleRadius * Math.cos(thetaRad + Math.PI / 2);
                                var rightY = centerY - needleRadius * Math.sin(thetaRad + Math.PI / 2);
                                var triangle = "M " + leftX + " " + leftY + " L " + topX + " " + topY + " L " + rightX + " " + rightY;
                                var textSize = isNaN(needleValueTextSize) ? (width * 12) / 300 : needleValueTextSize;
                                var fontStyle;
                                if (userFontStyle === undefined) {
                                    fontStyle = textSize + "px Courier";
                                } else {
                                    fontStyle = userFontStyle;
                                }
                                if (scope.value >= minLimit && scope.value <= maxLimit) {
                                    svg.append("svg:path")
                                        .attr("d", triangle)
                                        .style("stroke-width", 1)
                                        .style("stroke", needleColor)
                                        .style("fill", needleColor);
                                }

                                svg.append("text")
                                    .attr("x", centerX)
                                    .attr("y", centerY + valueVerticalOffset)
                                    .attr("class", "mtt-graduationValueText")
                                    .attr("fill", needleColor)
                                    .attr("text-anchor", "middle")
                                    .attr("font-weight", "bold")
                                    .style("font", fontStyle)
                                    .text('[ ' + scope.value.toFixed(scope.precision) + scope.valueUnit + ' ]');
                            }

                            var circleRadius = (width * 6) / 300;

                            svg.append("circle")
                                .attr("r", circleRadius)
                                .attr("cy", centerX)
                                .attr("cx", centerY)
                                .attr("fill", centerColor);
                        };
                        $window.onresize = function () {
                            scope.$apply();
                        };
                        scope.$watch(function () {
                            return angular.element($window)[0].innerWidth;
                        }, function () {
                            scope.render();
                        });
                        scope.$watch('ranges', function () {
                            scope.render();
                        }, true);
                        scope.$watch('value', function () {
                            scope.render();
                        }, true);
                        scope.render = function () {
                            svg.selectAll('*').remove();

                            if (renderTimeout) clearTimeout(renderTimeout);

                            renderTimeout = $timeout(function () {

                                var maxLimit = scope.upperLimit ? scope.upperLimit : 100;
                                var minLimit = scope.lowerLimit ? scope.lowerLimit : 0;
                                var d3DataSource = [];

                                if (typeof scope.ranges === 'undefined') {
                                    d3DataSource.push([minLimit, maxLimit, unactiveColor]);
                                } else {
                                    //Data Generation
                                    $.each(scope.ranges, function (index, value) {
                                        d3DataSource.push([value.min, value.max, value.color]);
                                    });
                                }

                                //Render Gauge Color Area
                                var translate = "translate(" + width / 2 + "," + width / 2 + ")";
                                var cScale = d3.scale.linear().domain([minLimit, maxLimit]).range([-120 * (Math.PI / 180), 120 * (Math.PI / 180)]);
                                var arc = d3.svg.arc()
                                    .innerRadius(innerRadius)
                                    .outerRadius(outterRadius)
                                    .startAngle(function (d) { return cScale(d[0]); })
                                    .endAngle(function (d) { return cScale(d[1]); });
                                svg.selectAll("path")
                                    .data(d3DataSource)
                                    .enter()
                                    .append("path")
                                    .attr("d", arc)
                                    .style("fill", function (d) { return d[2]; })
                                    .attr("transform", translate);

                                var majorGraduationsAngles = getMajorGraduationAngles();
                                var majorGraduationValues = getMajorGraduationValues(minLimit, maxLimit);
                                renderMajorGraduations(majorGraduationsAngles);
                                renderMajorGraduationTexts(majorGraduationsAngles, majorGraduationValues);
                                renderGraduationNeedle(minLimit, maxLimit);
                            }, 200);
                        };
                    });
                }
            };
        }]);
;

<commit_msg>refresh ttes les 2 sec<commit_after>angular.module('teleinfo.home', [])

    .controller('HomeCtrl', function HomeController($scope, $http) {

        $scope.value = undefined;
        $scope.indexcompteur = undefined;

        setInterval(function() {
            $http.get('/rest/inst/p')
                .success(function (data) {
                    $scope.value = data/1000;
                });
            $http.get('/rest/inst/index')
                .success(function (data) {
                    $scope.indexcompteur = data;
                });
        }, 2000)

        $scope.upperLimit = 6;
        $scope.lowerLimit = 0;
        $scope.unit = "kW";
        $scope.precision = 2;
        $scope.ranges = [
            {min: 0, max: 2.5, color: '#8DCA2F'},
            {min: 2.5, max: 3.5, color: '#FDC702'},
            {min: 3.5, max: 4.5, color: '#FF7700'},
            {min: 4.5, max: 6.0, color: '#C50200' }
        ];
    })

    // Directive ngRadialGauge adaptée de @stherrienaspnet
    // https://github.com/stherrienaspnet/ngRadialGauge
    // TODO Virer la dépendance avec jQuery !
    .factory('d3Service', ['$document', '$window', '$q', '$rootScope',
        function($document, $window, $q, $rootScope) {
            var d = $q.defer(),
                d3service = {
                    d3: function() { return d.promise; }
                };
            function onScriptLoad() {
                // Load client in the browser
                $rootScope.$apply(function() { d.resolve($window.d3); });
            }
            var scriptTag = $document[0].createElement('script');
            scriptTag.type = 'text/javascript';
            scriptTag.async = true;
            scriptTag.src = '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.1/d3.min.js';
            scriptTag.onreadystatechange = function () {
                if (this.readyState == 'complete') onScriptLoad();
            };
            scriptTag.onload = onScriptLoad;

            var s = $document[0].getElementsByTagName('body')[0];
            s.appendChild(scriptTag);

            return d3service;
        }])

    .directive('ngRadialGauge', ['$window', '$timeout', 'd3Service',
        function ($window, $timeout, d3Service) {
            return {
                restrict: 'A',
                scope: {
                    lowerLimit: '=',
                    upperLimit: '=',
                    ranges: '=',
                    value: '=',
                    valueUnit: '=',
                    precision: '=',
                    label: '@',
                    onClick: '&'
                },
                link: function (scope, ele, attrs) {
                    "use strict";
                    d3Service.d3().then(function (d3) {
                        var renderTimeout;
                        var width = parseInt(attrs.width) || 300;
                        var innerRadius = Math.round((width * 130) / 300);
                        var outterRadius = Math.round((width * 145) / 300);
                        var majorGraduations = parseInt(attrs.majorGraduations - 1) || 5;
                        var minorGraduations = parseInt(attrs.minorGraduations) || 10;
                        var majorGraduationLenght = Math.round((width * 16) / 300);
                        var minorGraduationLenght = Math.round((width * 10) / 300);
                        var majorGraduationMarginTop = Math.round((width * 7) / 300);
                        var majorGraduationColor = attrs.majorGraduationColor || "#B0B0B0";
                        var minorGraduationColor = attrs.minorGraduationColor || "#D0D0D0";
                        var majorGraduationTextColor = attrs.majorGraduationTextColor || "#6C6C6C";
                        var needleColor = attrs.needleColor || "#416094";
                        var valueVerticalOffset = Math.round((width * 30) / 300);
                        var unactiveColor = "#D7D7D7";
                        var majorGraduationTextSize = parseInt(attrs.majorGraduationTextSize);
                        var needleValueTextSize = parseInt(attrs.needleValueTextSize);
                        var userFontStyle = attrs.fontStyle;

                        var svg = d3.select(ele[0])
                            .append('svg')
                            .attr('width', width)
                            .attr('height', width * 0.75);
                        var renderMajorGraduations = function (majorGraduationsAngles) {
                            var centerX = width / 2;
                            var centerY = width / 2;
                            //Render Major Graduations
                            $.each(majorGraduationsAngles, function (index, value) {
                                var cos1Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght));
                                var sin1Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght));
                                var cos2Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                                var sin2Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                                var x1 = centerX + cos1Adj;
                                var y1 = centerY + sin1Adj * -1;
                                var x2 = centerX + cos2Adj;
                                var y2 = centerY + sin2Adj * -1;
                                svg.append("svg:line")
                                    .attr("x1", x1)
                                    .attr("y1", y1)
                                    .attr("x2", x2)
                                    .attr("y2", y2)
                                    .style("stroke", majorGraduationColor);

                                renderMinorGraduations(majorGraduationsAngles, index);
                            });
                        };
                        var renderMinorGraduations = function (majorGraduationsAngles, indexMajor) {
                            var minorGraduationsAngles = [];

                            if (indexMajor > 0) {
                                var minScale = majorGraduationsAngles[indexMajor - 1];
                                var maxScale = majorGraduationsAngles[indexMajor];
                                var scaleRange = maxScale - minScale;

                                for (var i = 1; i < minorGraduations; i++) {
                                    var scaleValue = minScale + i * scaleRange / minorGraduations;
                                    minorGraduationsAngles.push(scaleValue);
                                }

                                var centerX = width / 2;
                                var centerY = width / 2;
                                //Render Minor Graduations
                                $.each(minorGraduationsAngles, function (indexMinor, value) {
                                    var cos1Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - minorGraduationLenght));
                                    var sin1Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - minorGraduationLenght));
                                    var cos2Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                                    var sin2Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                                    var x1 = centerX + cos1Adj;
                                    var y1 = centerY + sin1Adj * -1;
                                    var x2 = centerX + cos2Adj;
                                    var y2 = centerY + sin2Adj * -1;
                                    svg.append("svg:line")
                                        .attr("x1", x1)
                                        .attr("y1", y1)
                                        .attr("x2", x2)
                                        .attr("y2", y2)
                                        .style("stroke", minorGraduationColor);
                                });
                            }
                        };
                        var getMajorGraduationValues = function (minLimit, maxLimit) {
                            var scaleRange = maxLimit - minLimit;
                            var majorGraduationValues = [];
                            for (var i = 0; i <= majorGraduations; i++) {
                                var scaleValue = minLimit + i * scaleRange / (majorGraduations);
                                majorGraduationValues.push(scaleValue.toFixed(scope.precision));
                            }

                            return majorGraduationValues;
                        };
                        var getMajorGraduationAngles = function () {
                            var scaleRange = 240;
                            var minScale = -120;
                            var graduationsAngles = [];
                            for (var i = 0; i <= majorGraduations; i++) {
                                var scaleValue = minScale + i * scaleRange / (majorGraduations);
                                graduationsAngles.push(scaleValue);
                            }

                            return graduationsAngles;
                        };
                        var renderMajorGraduationTexts = function (majorGraduationsAngles, majorGraduationValues) {
                            if (!scope.ranges) return;

                            var centerX = width / 2;
                            var centerY = width / 2;
                            var textVerticalPadding = 5;
                            var textHorizontalPadding = 5;

                            var lastGraduationValue = majorGraduationValues[majorGraduationValues.length - 1];
                            var textSize = isNaN(majorGraduationTextSize) ? (width * 12) / 300 : majorGraduationTextSize;
                            var fontStyle = textSize + "px Courier";

                            var dummyText = svg.append("text")
                                .attr("x", centerX)
                                .attr("y", centerY)
                                .attr("fill", "transparent")
                                .attr("text-anchor", "middle")
                                .style("font", fontStyle)
                                .text(lastGraduationValue + scope.valueUnit);

                            var textWidth = dummyText.node().getBBox().width;

                            for (var i = 0; i < majorGraduationsAngles.length; i++) {
                                var angle = majorGraduationsAngles[i];
                                var cos1Adj = Math.round(Math.cos((90 - angle) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght - textHorizontalPadding));
                                var sin1Adj = Math.round(Math.sin((90 - angle) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght - textVerticalPadding));

                                var sin1Factor = 1;
                                if (sin1Adj < 0) sin1Factor = 1.1;
                                if (sin1Adj > 0) sin1Factor = 0.9;
                                if (cos1Adj > 0) {
                                    if (angle > 0 && angle < 45) {
                                        cos1Adj -= textWidth / 2;
                                    } else {
                                        cos1Adj -= textWidth;
                                    }
                                }
                                if (cos1Adj < 0) {
                                    if (angle < 0 && angle > -45) {
                                        cos1Adj -= textWidth / 2;
                                    }
                                }
                                if (cos1Adj == 0) {
                                    cos1Adj -= angle == 0 ? textWidth / 4 : textWidth / 2;
                                }

                                var x1 = centerX + cos1Adj;
                                var y1 = centerY + sin1Adj * sin1Factor * -1;

                                svg.append("text")
                                    .attr("class", "mtt-majorGraduationText")
                                    .style("font", fontStyle)
                                    .attr("text-align", "center")
                                    .attr("x", x1)
                                    .attr("dy", y1)
                                    .attr("fill", majorGraduationTextColor)
                                    .text(majorGraduationValues[i] + scope.valueUnit);
                            }
                        };
                        var renderGraduationNeedle = function (minLimit, maxLimit) {
                            var centerX = width / 2;
                            var centerY = width / 2;
                            var centerColor;

                            if (typeof scope.value === 'undefined') {
                                centerColor = unactiveColor;
                            } else {
                                centerColor = needleColor;
                                var needleValue = ((scope.value - minLimit) * 240 / (maxLimit - minLimit)) - 30;
                                var thetaRad = needleValue * Math.PI / 180;

                                var needleLen = innerRadius - majorGraduationLenght - majorGraduationMarginTop;
                                var needleRadius = (width * 2.5) / 300;
                                var topX = centerX - needleLen * Math.cos(thetaRad);
                                var topY = centerY - needleLen * Math.sin(thetaRad);
                                var leftX = centerX - needleRadius * Math.cos(thetaRad - Math.PI / 2);
                                var leftY = centerY - needleRadius * Math.sin(thetaRad - Math.PI / 2);
                                var rightX = centerX - needleRadius * Math.cos(thetaRad + Math.PI / 2);
                                var rightY = centerY - needleRadius * Math.sin(thetaRad + Math.PI / 2);
                                var triangle = "M " + leftX + " " + leftY + " L " + topX + " " + topY + " L " + rightX + " " + rightY;
                                var textSize = isNaN(needleValueTextSize) ? (width * 12) / 300 : needleValueTextSize;
                                var fontStyle;
                                if (userFontStyle === undefined) {
                                    fontStyle = textSize + "px Courier";
                                } else {
                                    fontStyle = userFontStyle;
                                }
                                if (scope.value >= minLimit && scope.value <= maxLimit) {
                                    svg.append("svg:path")
                                        .attr("d", triangle)
                                        .style("stroke-width", 1)
                                        .style("stroke", needleColor)
                                        .style("fill", needleColor);
                                }

                                svg.append("text")
                                    .attr("x", centerX)
                                    .attr("y", centerY + valueVerticalOffset)
                                    .attr("class", "mtt-graduationValueText")
                                    .attr("fill", needleColor)
                                    .attr("text-anchor", "middle")
                                    .attr("font-weight", "bold")
                                    .style("font", fontStyle)
                                    .text('[ ' + scope.value.toFixed(scope.precision) + scope.valueUnit + ' ]');
                            }

                            var circleRadius = (width * 6) / 300;

                            svg.append("circle")
                                .attr("r", circleRadius)
                                .attr("cy", centerX)
                                .attr("cx", centerY)
                                .attr("fill", centerColor);
                        };
                        $window.onresize = function () {
                            scope.$apply();
                        };
                        scope.$watch(function () {
                            return angular.element($window)[0].innerWidth;
                        }, function () {
                            scope.render();
                        });
                        scope.$watch('ranges', function () {
                            scope.render();
                        }, true);
                        scope.$watch('value', function () {
                            scope.render();
                        }, true);
                        scope.render = function () {
                            svg.selectAll('*').remove();

                            if (renderTimeout) clearTimeout(renderTimeout);

                            renderTimeout = $timeout(function () {

                                var maxLimit = scope.upperLimit ? scope.upperLimit : 100;
                                var minLimit = scope.lowerLimit ? scope.lowerLimit : 0;
                                var d3DataSource = [];

                                if (typeof scope.ranges === 'undefined') {
                                    d3DataSource.push([minLimit, maxLimit, unactiveColor]);
                                } else {
                                    //Data Generation
                                    $.each(scope.ranges, function (index, value) {
                                        d3DataSource.push([value.min, value.max, value.color]);
                                    });
                                }

                                //Render Gauge Color Area
                                var translate = "translate(" + width / 2 + "," + width / 2 + ")";
                                var cScale = d3.scale.linear().domain([minLimit, maxLimit]).range([-120 * (Math.PI / 180), 120 * (Math.PI / 180)]);
                                var arc = d3.svg.arc()
                                    .innerRadius(innerRadius)
                                    .outerRadius(outterRadius)
                                    .startAngle(function (d) { return cScale(d[0]); })
                                    .endAngle(function (d) { return cScale(d[1]); });
                                svg.selectAll("path")
                                    .data(d3DataSource)
                                    .enter()
                                    .append("path")
                                    .attr("d", arc)
                                    .style("fill", function (d) { return d[2]; })
                                    .attr("transform", translate);

                                var majorGraduationsAngles = getMajorGraduationAngles();
                                var majorGraduationValues = getMajorGraduationValues(minLimit, maxLimit);
                                renderMajorGraduations(majorGraduationsAngles);
                                renderMajorGraduationTexts(majorGraduationsAngles, majorGraduationValues);
                                renderGraduationNeedle(minLimit, maxLimit);
                            }, 200);
                        };
                    });
                }
            };
        }]);
;

<|endoftext|>