<commit_before>import { app, BrowserWindow, shell } from 'electron';
import fs from 'fs-extra';
import path from 'path';

import windowStateKeeper from 'electron-window-state';

import { isDevMode, isWindows } from './environment';
import ipcApi from './electron/ipc-api';
import Tray from './lib/Tray';
import Settings from './electron/Settings';
import { appId } from './package.json'; // eslint-disable-line import/no-unresolved
import './electron/exception';

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
let willQuitApp = false;

// Ensure that the recipe directory exists
fs.ensureDir(path.join(app.getPath('userData'), 'recipes'));
fs.emptyDirSync(path.join(app.getPath('userData'), 'recipes', 'temp'));

// Set App ID for Windows
if (isWindows) {
  app.setAppUserModelId(appId);
}

// Force single window
if (process.platform !== 'darwin') {
  const isSecondInstance = app.makeSingleInstance(() => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.focus();
    }
  });

  if (isSecondInstance) {
    app.quit();
  }
}

// Initialize Settings
const settings = new Settings();

const createWindow = async () => {
  // Remember window size
  const mainWindowState = windowStateKeeper({
    defaultWidth: 800,
    defaultHeight: 600,
  });

  // Create the browser window.
  mainWindow = new BrowserWindow({
    x: mainWindowState.x,
    y: mainWindowState.y,
    width: mainWindowState.width,
    height: mainWindowState.height,
    minWidth: 800,
    minHeight: 600,
    titleBarStyle: 'hidden',
    backgroundColor: '#3498db',
    autoHideMenuBar: true,
  });

  // Initialize System Tray
  const trayIcon = new Tray();

  // Initialize ipcApi
  ipcApi({ mainWindow, settings, trayIcon });

  // Manage Window State
  mainWindowState.manage(mainWindow);

  // and load the index.html of the app.
  mainWindow.loadURL(`file://${__dirname}/index.html`);

  // Open the DevTools.
  if (isDevMode) {
    mainWindow.webContents.openDevTools();
  }

  // Emitted when the window is closed.
  mainWindow.on('close', (e) => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    if (!willQuitApp && (settings.get('runInBackground') === undefined || settings.get('runInBackground'))) {
      e.preventDefault();
      mainWindow.hide();

      if (process.platform === 'win32') {
        mainWindow.setSkipTaskbar(true);
      }
    } else {
      app.quit();
    }
  });

  // For Windows we need to store a flag to properly restore the window
  // if the window was maximized before minimizing it so system tray
  mainWindow.on('minimize', () => {
    app.wasMaximized = app.isMaximized;

    if (settings.get('minimizeToSystemTray')) {
      mainWindow.setSkipTaskbar(true);
      trayIcon.show();
    }
  });

  mainWindow.on('maximize', () => {
    app.isMaximized = true;
  });

  mainWindow.on('close', (e) => {
    if (settings.get('minimizeToSystemTray')) {
      e.preventDefault();
      mainWindow.minimize();
    }
  });

  mainWindow.on('unmaximize', () => {
    app.isMaximized = false;
  });

  mainWindow.on('restore', () => {
    mainWindow.setSkipTaskbar(false);

    if (app.wasMaximized) {
      mainWindow.maximize();
    }

    if (!settings.get('enableSystemTray')) {
      trayIcon.hide();
    }
  });

  mainWindow.on('show', () => {
    mainWindow.setSkipTaskbar(false);
  });

  app.mainWindow = mainWindow;
  app.isMaximized = mainWindow.isMaximized();

  mainWindow.webContents.on('new-window', (e, url) => {
    e.preventDefault();
    shell.openExternal(url);
  });
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (settings.get('runInBackground') === undefined
    || settings.get('runInBackground')) {
    app.quit();
  }
});

app.on('before-quit', () => {
  willQuitApp = true;
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  } else {
    mainWindow.show();
  }
});
<commit_msg>add debugging output for mainWindow<commit_after>import { app, BrowserWindow, shell } from 'electron';
import fs from 'fs-extra';
import path from 'path';

import windowStateKeeper from 'electron-window-state';

import { isDevMode, isWindows } from './environment';
import ipcApi from './electron/ipc-api';
import Tray from './lib/Tray';
import Settings from './electron/Settings';
import { appId } from './package.json'; // eslint-disable-line import/no-unresolved
import './electron/exception';

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
let willQuitApp = false;

// Ensure that the recipe directory exists
fs.ensureDir(path.join(app.getPath('userData'), 'recipes'));
fs.emptyDirSync(path.join(app.getPath('userData'), 'recipes', 'temp'));

// Set App ID for Windows
if (isWindows) {
  app.setAppUserModelId(appId);
}

// Force single window
// if (process.platform !== 'darwin') {
const isSecondInstance = app.makeSingleInstance(() => {
  console.log(mainWindow);
  console.log('isMinimized', mainWindow.isMinimized);
  if (mainWindow) {
    if (mainWindow.isMinimized()) mainWindow.restore();
    mainWindow.focus();
  }
});

if (isSecondInstance) {
  app.exit();
}

// }

// Initialize Settings
const settings = new Settings();

const createWindow = async () => {
  // Remember window size
  const mainWindowState = windowStateKeeper({
    defaultWidth: 800,
    defaultHeight: 600,
  });

  // Create the browser window.
  mainWindow = new BrowserWindow({
    x: mainWindowState.x,
    y: mainWindowState.y,
    width: mainWindowState.width,
    height: mainWindowState.height,
    minWidth: 800,
    minHeight: 600,
    titleBarStyle: 'hidden',
    backgroundColor: '#3498db',
    autoHideMenuBar: true,
  });

  // Initialize System Tray
  const trayIcon = new Tray();

  // Initialize ipcApi
  ipcApi({ mainWindow, settings, trayIcon });

  // Manage Window State
  mainWindowState.manage(mainWindow);

  // and load the index.html of the app.
  mainWindow.loadURL(`file://${__dirname}/index.html`);

  // Open the DevTools.
  if (isDevMode) {
    mainWindow.webContents.openDevTools();
  }

  // Emitted when the window is closed.
  mainWindow.on('close', (e) => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    if (!willQuitApp && (settings.get('runInBackground') === undefined || settings.get('runInBackground'))) {
      e.preventDefault();
      mainWindow.hide();

      if (process.platform === 'win32') {
        mainWindow.setSkipTaskbar(true);
      }
    } else {
      app.quit();
    }
  });

  // For Windows we need to store a flag to properly restore the window
  // if the window was maximized before minimizing it so system tray
  mainWindow.on('minimize', () => {
    app.wasMaximized = app.isMaximized;

    if (settings.get('minimizeToSystemTray')) {
      mainWindow.setSkipTaskbar(true);
      trayIcon.show();
    }
  });

  mainWindow.on('maximize', () => {
    app.isMaximized = true;
  });

  mainWindow.on('close', (e) => {
    if (settings.get('minimizeToSystemTray') && settings.get('runInBackground')) {
      e.preventDefault();
      mainWindow.minimize();
    }
  });

  mainWindow.on('unmaximize', () => {
    app.isMaximized = false;
  });

  mainWindow.on('restore', () => {
    mainWindow.setSkipTaskbar(false);

    if (app.wasMaximized) {
      mainWindow.maximize();
    }

    if (!settings.get('enableSystemTray')) {
      trayIcon.hide();
    }
  });

  mainWindow.on('show', () => {
    mainWindow.setSkipTaskbar(false);
  });

  app.mainWindow = mainWindow;
  app.isMaximized = mainWindow.isMaximized();

  mainWindow.webContents.on('new-window', (e, url) => {
    e.preventDefault();
    shell.openExternal(url);
  });
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (settings.get('runInBackground') === undefined
    || settings.get('runInBackground')) {
    app.quit();
  }
});

app.on('before-quit', () => {
  willQuitApp = true;
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  } else {
    mainWindow.show();
  }
});
<|endoftext|>


<commit_before>import Affix from './components/affix';
import BackTop from './components/backtop';
import Badge from './components/badge';
// import Breadcrumb from './components/breadcrumb';
// import Carousel from './components/carousel';
// import Cascader from './components/cascader';
import Checkbox from './components/checkbox';
import Circle from './components/circle';
import Datetime from './components/datetime';

import Dropdown from './plugins/dropdown';
import DropdownCustom from './components/dropdowncustom';
import DropdownMenu from './components/dropdownmenu';
import Form from './components/form';
import Menu from './components/menu';
import modal from './components/modal';
import Pagination from './components/pagination';
import Poptip from './components/poptip';
import Progress from './components/progress';
import Radio from './components/radio';
import Rate from './components/rate';
import Slider from './components/slider';
import Loading from './components/Loading';
import Steps from './components/steps';
import Search from './components/search';
import Select from './components/select';
import Switch from './components/switch';
import SwitchList from './components/switchlist';
import Table from './components/table';
import Tabs from './components/tabs';
import Tag from './components/tag';
import TagInput from './components/taginput';
import NumberInput from './components/numberinput';
import Tooltip from './components/tooltip';
import Tree from './components/tree';
import Uploader from './components/uploader';
import AutoComplete from './components/autocomplete';
import {
  Row,
  Col
} from './components/layout';
import Timeline from './components/timeline';
import { Button, ButtonGroup } from './components/button';
// import locale from './locale';

import style from './directives/style';
import tooltip from './directives/tooltip';
import autosize from './directives/autosize';
import $Modal from './plugins/modal';
import $Confirm from './plugins/confirm';
import $Message from './plugins/message';
import $Notice from './plugins/notice';
import $Loading from './plugins/loading';
import $LoadingBar from './plugins/loadingbar';

import filters from './filters';

import config from './utils/config';

const components = {
  Affix,
  // Alert,
  AutoComplete,
  BackTop,
  Badge,
  // Breadcrumb,
  // BreadcrumbItem: Breadcrumb.Item,
  Button,
  hButton: Button,
  ButtonGroup,
  // Card,
  // Carousel,
  // CarouselItem: Carousel.Item,
  // Cascader,
  Checkbox,
  // CheckboxGroup: Checkbox.Group,
  hCircle: Circle,
  // DatePicker,
  DropdownCustom,
  DropdownMenu,
  DatePicker: Datetime.DatePicker,
  DateRangePicker: Datetime.DateRangePicker,
  hForm: Form,
  Form,
  FormItem: Form.Item,
  FormItemList: Form.ItemList,
  // Collapse,
  // Icon,
  // InputNumber,
  // LoadingBar,
  Menu,
  // MenuGroup: Menu.Group,
  // MenuItem: Menu.Item,
  // Submenu: Menu.Sub,
  // Message,
  Modal: modal.Modal,
  ModalComponent: modal.ModalComponent,
  NumberInput,
  // Notice,
  // iOption: Option,
  // OptionGroup,
  Pagination,
  // Panel: Collapse.Panel,
  Poptip,
  Progress,
  Radio,
  // RadioGroup: Radio.Group,
  Rate,
  Row,
  hCol: Col,
  Col,
  Timeline,
  TimelineItem: Timeline.Item,
  hSelect: Select,
  Select,
  Search,
  Slider,
  Loading,
  // Step: Steps.Step,
  Steps,
  hSwitch: Switch,
  SwitchList,
  TagInput,
  Table,
  hTable: Table,
  Tabs,
  // TabPane: Tabs.Pane,
  Tag,
  // TimePicker,
  Tooltip,
  // Transfer,
  Tree,
  Uploader
};

const directives = {
  width: style.width,
  color: style.color,
  "bg-color": style.bgColor,
  height: style.height,
  padding: style.padding,
  margin: style.margin,
  font: style.font,
  autosize,
  tooltip
}

let prototypes = {
  $Message,
  $Confirm,
  $Loading,
  $LoadingBar
}

const install = function (Vue) {
  // locale.use(opts.locale);
  // locale.i18n(opts.i18n);

  if (install.installed) return;
  // if (opts) {

  // }

  Object.keys(components).forEach((key) => {
    Vue.component(key, components[key]);
  });

  Object.keys(filters).forEach((key) => {
    Vue.filter(key, filters[key]);
  });

  Object.keys(directives).forEach((key) => {
    Vue.directive(key, directives[key]);
  });

  Object.keys(prototypes).forEach((key) => {
    Vue.prototype[key] = prototypes[key];
  });

  this.$Modal = Vue.prototype.$Modal = $Modal(Vue);
  this.$Notice = Vue.prototype.$Notice = $Notice(Vue);
};

if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
}

const HeyUI = Object.assign(components, {
  install
}, prototypes, config, { Dropdown });

module.exports = HeyUI;
<commit_msg>fix: 删除无用的引用<commit_after>/*
 Copyright (C) Lan 2017
 Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
 */
import Affix from './components/affix';
import BackTop from './components/backtop';
import Badge from './components/badge';
import Checkbox from './components/checkbox';
import Circle from './components/circle';
import Datetime from './components/datetime';
import Dropdown from './plugins/dropdown';
import DropdownCustom from './components/dropdowncustom';
import DropdownMenu from './components/dropdownmenu';
import Form from './components/form';
import Menu from './components/menu';
import modal from './components/modal';
import Pagination from './components/pagination';
import Poptip from './components/poptip';
import Progress from './components/progress';
import Radio from './components/radio';
import Rate from './components/rate';
import Slider from './components/slider';
import Loading from './components/Loading';
import Steps from './components/steps';
import Search from './components/search';
import Select from './components/select';
import Switch from './components/switch';
import SwitchList from './components/switchlist';
import Table from './components/table';
import Tabs from './components/tabs';
import Tag from './components/tag';
import TagInput from './components/taginput';
import NumberInput from './components/numberinput';
import Tooltip from './components/tooltip';
import Tree from './components/tree';
import Uploader from './components/uploader';
import AutoComplete from './components/autocomplete';
import {
  Row,
  Col
} from './components/layout';
import Timeline from './components/timeline';
import { Button, ButtonGroup } from './components/button';
// import locale from './locale';

import style from './directives/style';
import tooltip from './directives/tooltip';
import autosize from './directives/autosize';
import $Modal from './plugins/modal';
import $Confirm from './plugins/confirm';
import $Message from './plugins/message';
import $Notice from './plugins/notice';
import $Loading from './plugins/loading';
import $LoadingBar from './plugins/loadingbar';

import filters from './filters';

import config from './utils/config';

const components = {
  Affix,
  AutoComplete,
  BackTop,
  Badge,
  Button,
  hButton: Button,
  ButtonGroup,
  Checkbox,
  hCircle: Circle,
  DropdownCustom,
  DropdownMenu,
  DatePicker: Datetime.DatePicker,
  DateRangePicker: Datetime.DateRangePicker,
  hForm: Form,
  Form,
  FormItem: Form.Item,
  FormItemList: Form.ItemList,
  Menu,
  Modal: modal.Modal,
  ModalComponent: modal.ModalComponent,
  NumberInput,
  Pagination,
  Poptip,
  Progress,
  Radio,
  Rate,
  Row,
  hCol: Col,
  Col,
  Timeline,
  TimelineItem: Timeline.Item,
  hSelect: Select,
  Select,
  Search,
  Slider,
  Loading,
  Steps,
  hSwitch: Switch,
  SwitchList,
  TagInput,
  Table,
  hTable: Table,
  Tabs,
  Tag,
  Tooltip,
  Tree,
  Uploader
};

const directives = {
  width: style.width,
  color: style.color,
  "bg-color": style.bgColor,
  height: style.height,
  padding: style.padding,
  margin: style.margin,
  font: style.font,
  autosize,
  tooltip
}

let prototypes = {
  $Message,
  $Confirm,
  $Loading,
  $LoadingBar
}

const install = function (Vue) {
  // locale.use(opts.locale);
  // locale.i18n(opts.i18n);

  if (install.installed) return;
  // if (opts) {

  // }

  Object.keys(components).forEach((key) => {
    Vue.component(key, components[key]);
  });

  Object.keys(filters).forEach((key) => {
    Vue.filter(key, filters[key]);
  });

  Object.keys(directives).forEach((key) => {
    Vue.directive(key, directives[key]);
  });

  Object.keys(prototypes).forEach((key) => {
    Vue.prototype[key] = prototypes[key];
  });

  this.$Modal = Vue.prototype.$Modal = $Modal(Vue);
  this.$Notice = Vue.prototype.$Notice = $Notice(Vue);
};

if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
}

const HeyUI = Object.assign(components, {
  install
}, prototypes, config, { Dropdown });

module.exports = HeyUI;
<|endoftext|>


<commit_before>var geojson, columndata;
var selectedCanton = null, selectedFeature = null;

// Swiss map projection
var crs = new L.Proj.CRS('EPSG:21781',
  '+title=CH1903 / LV03 +proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +x_0=600000 +y_0=200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs',
  {
    origin: [660000, 190000],
    extent: [420000, 900000, 30000, 350000],
    resolutions: [650.0, 500.0, 250.0, 100.0]
  }
);

// Main map object
var MAP_DEFAULT_CENTER = [46.8, 8.2];
var map = L.map('map')
		   .setView(MAP_DEFAULT_CENTER, 7.5);

//addGeoAdmin();

// Load data files
$.getJSON('data/Entrees_Sorties_Hospitalisations_Suisse_2011.json', function(data) {

	//console.log(data);
	columndata = data;
	precalcValues();

	// Load canton borders
	$.getJSON('data/swiss-cantons.geo.json',
		function(data) {

			geojson = L.geoJson(data, {
				style: style,
				onEachFeature: onEachFeature
			}).addTo(map);

			map.attributionControl.addAttribution(
				'Données © 2013 Office fédéral de la statistique');
		});

});

// control that shows state info on hover
var info = L.control();

info.onAdd = function (map) {
	this._div = L.DomUtil.create('div', 'info');
	this._infobox = $('.infobox.canton').hide();
	this._blankbox = $('.infobox.blank').show();
	this.update();
	return this._div;
};

info.update = function (props) {
	$('.infobox.canton div').css('border-left', '2em solid white');
	if (selectedCanton != null) {
		props = {
			abbr: columndata.Canton[selectedCanton],
			name: columndata.Nom[selectedCanton]
		}
	} else if (props === undefined) {
		$('.infobox.blank').show();
		this._infobox.hide();
		return;
	}

	// colourful box in legend
	$('.infobox.canton .percent-local').css('border-left',
		'2em solid ' + getColor(getValueForCanton(props.abbr)));

	// update legend
	updateValueForCanton(this._infobox, props.abbr);
	this._blankbox.hide();
	this._infobox.show();
	// update overlay
	/*
	this._div.innerHTML = (props ?
		'' + props.name + '
'
		+ (getValueForCanton(props.abbr) + '')
		: '...');
	*/
};

info.addTo(map);

function initGeoAdmin(map) {
	var geoadmin = L.tileLayer.wms("http://wms.geo.admin.ch/", {
	    layers: 'ch.swisstopo.pixelkarte-farbe-pk1000.noscale',
	    format: 'image/jpeg',
	    transparent: false,
	    crs: crs,
	    attribution: '© ' +
	          '' +
	          'Pixelmap 1:1000000 / geo.admin.ch'
	}).addTo(map);
}

function precalcValues() {
	columndata.Summary = {};
	for (var i = 0; i < columndata.Canton.length; i++) {
		var abbr = columndata.Canton[i];
		if (typeof columndata[abbr] == 'undefined') continue;
		var data = {
			ix: 		i,
			name: 		columndata.Nom[i],
			entrants:	columndata.Entrants[i],
			sortants:	columndata.Sortants[i],
			locals:		columndata[abbr][i]
		};
		data.p_local = data.locals / data.entrants;
		data.p_remote = (data.sortants-data.locals) / data.sortants;
		data.p_visitors = (data.entrants-data.locals) / data.entrants;
		// set
		columndata.Summary[abbr] = data;
	}
}

function getIxCanton(abbr) {
	return columndata.Summary[abbr].ix;
}

function getValueForCanton(abbr) {
	return columndata.Summary[abbr].entrants;
}

function updateValueForCanton(obj, abbr) {
	var data = columndata.Summary[abbr];

	$('.name', obj).html( data.name );
	$('.de-name', obj).html(
		(["VD","TI"].indexOf(abbr) ? 'du' : 'de') + data.name );
	$('.patients', obj).html( data.entrants );
	$('.hospitals', obj).html( data.sortants );
	$('.percent-local', obj).html( parseInt(1000 * data.p_local) / 10 );
	$('.percent-remote', obj).html( parseInt(1000 * data.p_remote) / 10 );
	$('.percent-visitors', obj).html( parseInt(1000 * data.p_visitors) / 10 );

	return true;
}

// get color depending on population density value
var DATA_GRADES =
	[1000, 5000, 25000, 50000, 100000];
function getColor(d) {
	return d > DATA_GRADES[4] ? '#940727' :
	       d > DATA_GRADES[3] ? '#a52d49' :
	       d > DATA_GRADES[2] ? '#c57889' :
	       d > DATA_GRADES[1] ? '#ebd1d8' :
	                  			'#ffffff';
}

function style(feature) {
	var baseColor =
		getColor(getValueForCanton(
			feature.properties.abbr ));
	return {
		weight: 2,
		opacity: 1,
		color: '#444',
		//dashArray: '3',
		fillOpacity: 0.7,
		fillColor: baseColor
	};
}

function highlightFeature(e) {
	if (selectedCanton != null) return;
	var layer = e.target;

	$.each(geojson.getLayers(), function() {
		if (this != layer)
			this.setStyle({ fillColor: '#000' });
	});

	layer.setStyle({
		weight: 3,
		color: '#fff',
		dashArray: '',
		fillOpacity: 0.7
	});

	if (!L.Browser.ie && !L.Browser.opera) {
		layer.bringToFront();
	}

	info.update(layer.feature.properties);
}

function resetHighlight(e) {
	if (selectedCanton != null) return;

	$.each(geojson.getLayers(), function() {
		geojson.resetStyle(this);
	});

	geojson.resetStyle(e.target);

	info.update();
}

function zoomToFeature(e) {
	var prevCanton = selectedCanton;
	selectedCanton = null;
	highlightFeature(e);
	var s = columndata.Canton
			.indexOf(e.target.feature.properties.abbr);
	if (s == prevCanton) {
		map.setView(MAP_DEFAULT_CENTER, 7.5);
	} else {
		selectedCanton = s;
		if (selectedFeature != null)
			geojson.resetStyle(selectedFeature);
		selectedFeature = e.target;
		map.fitBounds(e.target.getBounds());
	}
}

function onEachFeature(feature, layer) {
	layer.on({
		mouseover: highlightFeature,
		mouseout: resetHighlight,
		click: zoomToFeature
	});
}

var legend = L.control({position: 'bottomright'});

legend.onAdd = function (map) {

	var div = L.DomUtil.create('div', 'info legend'),
		grades = DATA_GRADES,
		labels = [],
		from, to;

	for (var i = 0; i < grades.length; i++) {
		from = grades[i];
		to = grades[i + 1];

		labels.push(
			' ' +
			from + (to ? '–' + to : '+'));
	}

	div.innerHTML = labels.join('
');
	return div;
};

legend.addTo(map);<commit_msg>Percentages<commit_after>var geojson, columndata;
var selectedCanton = null, selectedFeature = null;

// Swiss map projection
var crs = new L.Proj.CRS('EPSG:21781',
  '+title=CH1903 / LV03 +proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +x_0=600000 +y_0=200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs',
  {
    origin: [660000, 190000],
    extent: [420000, 900000, 30000, 350000],
    resolutions: [650.0, 500.0, 250.0, 100.0]
  }
);

// Main map object
var MAP_DEFAULT_CENTER = [46.8, 8.2];
var map = L.map('map')
		   .setView(MAP_DEFAULT_CENTER, 7.5);

//addGeoAdmin();

// Load data files
$.getJSON('data/Entrees_Sorties_Hospitalisations_Suisse_2011.json', function(data) {

	//console.log(data);
	columndata = data;
	precalcValues();

	// Load canton borders
	$.getJSON('data/swiss-cantons.geo.json',
		function(data) {

			geojson = L.geoJson(data, {
				style: style,
				onEachFeature: onEachFeature
			}).addTo(map);

			map.attributionControl.addAttribution(
				'Données © 2013 Office fédéral de la statistique');
		});

});

// control that shows state info on hover
var info = L.control();

info.onAdd = function (map) {
	this._div = L.DomUtil.create('div', 'info');
	this._infobox = $('.infobox.canton').hide();
	this._blankbox = $('.infobox.blank').show();
	this.update();
	return this._div;
};

info.update = function (props) {
	$('.infobox.canton div').css('border-left', '2em solid white');
	if (selectedCanton != null) {
		props = {
			abbr: columndata.Canton[selectedCanton],
			name: columndata.Nom[selectedCanton]
		}
	} else if (props === undefined) {
		$('.infobox.blank').show();
		this._infobox.hide();
		return;
	}

	// colourful box in legend
	$('.infobox.canton .percent-local').css('border-left',
		'2em solid ' + columndata.Summary[props.abbr].color_start );

	// update legend
	updateValueForCanton(this._infobox, props.abbr);
	this._blankbox.hide();
	this._infobox.show();
	// update overlay
	/*
	this._div.innerHTML = (props ?
		'' + props.name + '
'
		+ (getValueForCanton(props.abbr) + '')
		: '...');
	*/
};

info.addTo(map);

function initGeoAdmin(map) {
	var geoadmin = L.tileLayer.wms("http://wms.geo.admin.ch/", {
	    layers: 'ch.swisstopo.pixelkarte-farbe-pk1000.noscale',
	    format: 'image/jpeg',
	    transparent: false,
	    crs: crs,
	    attribution: '© ' +
	          '' +
	          'Pixelmap 1:1000000 / geo.admin.ch'
	}).addTo(map);
}

function precalcValues() {
	columndata.Summary = {};
	for (var i = 0; i < columndata.Canton.length; i++) {
		var abbr = columndata.Canton[i];
		if (typeof columndata[abbr] == 'undefined') continue;
		var data = {
			ix: 		i,
			name: 		columndata.Nom[i],
			entrants:	columndata.Entrants[i],
			sortants:	columndata.Sortants[i],
			locals:		columndata[abbr][i]
		};
		data.remote = data.sortants-data.locals;
		data.p_local = data.locals / data.entrants;
		data.p_remote = data.remote / data.sortants;
		data.p_visitors = (data.entrants-data.locals) / data.entrants;
		data.color_start = getColor(data.p_local * 100);
		// set
		columndata.Summary[abbr] = data;
	}
}

function getIxCanton(abbr) {
	return columndata.Summary[abbr].ix;
}

function getValueForCanton(abbr) {
	return columndata.Summary[abbr].p_local * 100;
}

function updateValueForCanton(obj, abbr) {
	var data = columndata.Summary[abbr];

	$('.name', obj).html( data.name );
	$('.de-name', obj).html(
		(["VD","TI"].indexOf(abbr) ? 'du' : 'de') + data.name );
	$('.patients', obj).html( data.entrants );
	$('.hospitals', obj).html( data.sortants );
	$('.percent-local', obj).html( parseInt(1000 * data.p_local) / 10 );
	$('.percent-remote', obj).html( parseInt(1000 * data.p_remote) / 10 );
	$('.percent-visitors', obj).html( parseInt(1000 * data.p_visitors) / 10 );

	return true;
}

function getColorCantonCanton(abbrFrom, abbrTo) {
	return getColor(100 *
			columndata[abbrFrom][getIxCanton(abbrTo)] /
			columndata.Summary[abbrFrom].remote
		);
}

// get color depending on population density value
var DATA_SCALES = [
		[35, 50, 75, 85, 90, 99],
		[0, 5, 10, 20, 30, 40]
	];
var DATA_GRADES = DATA_SCALES[0];

function getColor(d) {
	return d > DATA_GRADES[5] ? '#cc1030' :
		   d > DATA_GRADES[4] ? '#940727' :
	       d > DATA_GRADES[3] ? '#a52d49' :
	       d > DATA_GRADES[2] ? '#c57889' :
	       d > DATA_GRADES[1] ? '#ebd1d8' :
	                  			'#ffffff';
}

function style(feature) {
	var baseColor =
		getColor(getValueForCanton(
			feature.properties.abbr ));
	return {
		weight: 2,
		opacity: 1,
		color: '#444',
		//dashArray: '3',
		fillOpacity: 0.7,
		fillColor: baseColor
	};
}

function highlightFeature(e) {
	if (selectedCanton != null) return;
	var layer = e.target;

	switchScale(1);

	// others
	$.each(geojson.getLayers(), function() {
		if (layer == this) return;
		this.setStyle({
			fillColor: getColorCantonCanton(
				layer.feature.properties.abbr,
				this.feature.properties.abbr )
		});
	});

	// this
	layer.setStyle({ color: '#fff', fillColor: getColor(100) });

	if (!L.Browser.ie && !L.Browser.opera) {
		layer.bringToFront();
	}

	info.update(layer.feature.properties);
}

function resetHighlight(e) {
	if (selectedCanton != null) return;

	switchScale(0);

	$.each(geojson.getLayers(), function() {
		geojson.resetStyle(this);
	});

	geojson.resetStyle(e.target);

	info.update();
}

function zoomToFeature(e) {
	var prevCanton = selectedCanton;
	selectedCanton = null;
	highlightFeature(e);
	var s = columndata.Canton
			.indexOf(e.target.feature.properties.abbr);
	if (s == prevCanton) {
		map.setView(MAP_DEFAULT_CENTER, 7.5);
	} else {
		selectedCanton = s;
		if (selectedFeature != null)
			geojson.resetStyle(selectedFeature);
		selectedFeature = e.target;
		map.fitBounds(e.target.getBounds());
	}
}

function onEachFeature(feature, layer) {
	layer.on({
		mouseover: highlightFeature,
		mouseout: resetHighlight,
		click: zoomToFeature
	});
}

function switchScale(ds) {
	DATA_GRADES = DATA_SCALES[ds];
	$('.info.legend .grade').hide();
	$('.info.legend .scale-' + ds).show();
}

var legend = L.control({position: 'bottomright'});

legend.onAdd = function (map) {

	var div = L.DomUtil.create('div', 'info legend');
	var scales = "
%
";

	for (var ds = 0; ds < DATA_SCALES.length; ds++) {

		DATA_GRADES = DATA_SCALES[ds];
		var grades = DATA_GRADES,
			labels = [],
			from, to;

		for (var i = 0; i < grades.length; i++) {
			from = grades[i];
			to = grades[i + 1];

			labels.push(
				' ' +
				from + (to ? '–' + to : '+'));
		}

		scales += '
'
				+ labels.join('
') + '
';

	}

	div.innerHTML = scales;
	return div;
};

legend.addTo(map);
switchScale(0);<|endoftext|>


<commit_before>import {Decorators, Metadata} from 'aurelia-metadata';
import {ValueConverterResource} from './value-converter';

export {EventManager} from './event-manager';
export {ObserverLocator, ObjectObservationAdapter} from './observer-locator';
export {ValueConverterResource} from './value-converter';
export {calcSplices} from './array-change-records';
export * from './binding-modes';
export {Parser} from './parser';
export {BindingExpression} from './binding-expression';
export {ListenerExpression} from './listener-expression';
export {NameExpression} from './name-expression';
export {CallExpression} from './call-expression';
export {DirtyChecker} from './dirty-checking';
export {getChangeRecords} from './map-change-records';
export {ComputedObservationAdapter, declarePropertyDependencies} from './computed-observation';

//ES7 Decorators
export function valueConverter(name){
  return function(target){
    Metadata.on(target).add(new ValueConverterResource(name));
    return target;
  }
}

Decorators.configure.parameterizedDecorator('valueConverter', valueConverter);

export function computedFrom(...rest){
  return function(target, key, descriptor){
    if (descriptor.set){
      throw new Error(`The computed property "${key}" cannot have a setter function.`);
    }
    descriptor.get.dependencies = rest;
    return descriptor;
  }
}
<commit_msg>fix(index): fix export ComputedPropertyObserver<commit_after>import {Decorators, Metadata} from 'aurelia-metadata';
import {ValueConverterResource} from './value-converter';

export {EventManager} from './event-manager';
export {ObserverLocator, ObjectObservationAdapter} from './observer-locator';
export {ValueConverterResource} from './value-converter';
export {calcSplices} from './array-change-records';
export * from './binding-modes';
export {Parser} from './parser';
export {BindingExpression} from './binding-expression';
export {ListenerExpression} from './listener-expression';
export {NameExpression} from './name-expression';
export {CallExpression} from './call-expression';
export {DirtyChecker} from './dirty-checking';
export {getChangeRecords} from './map-change-records';
export {ComputedPropertyObserver, declarePropertyDependencies} from './computed-observation';

//ES7 Decorators
export function valueConverter(name){
  return function(target){
    Metadata.on(target).add(new ValueConverterResource(name));
    return target;
  }
}

Decorators.configure.parameterizedDecorator('valueConverter', valueConverter);

export function computedFrom(...rest){
  return function(target, key, descriptor){
    if (descriptor.set){
      throw new Error(`The computed property "${key}" cannot have a setter function.`);
    }
    descriptor.get.dependencies = rest;
    return descriptor;
  }
}
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch';
import { merge } from 'lodash';
import defaultConfig from './config/defaultConfig';

function restMiddlewareCreator(customConfig) {
  const finalConfig = merge(defaultConfig, customConfig);
  const { suffix, fetchOptions } = finalConfig;

  return ({ dispatch }) => next => (action) => {
    if (!action || !action.$payload) {
      return next(action);
    }

    const [REQUEST, SUCCESS, FAILURE] = suffix;
    const { type, $payload } = action;
    const { url, options } = $payload;
    const opts = merge({}, fetchOptions, options);

    // Request start
    dispatch({ type: `${type}_${REQUEST}` });

    // Catch the response from service
    return fetch(url, opts)
      .then(response => response.json())
      .then((data) => {
        // Request success, dispatch the response data
        dispatch({ type: `${type}_${SUCCESS}`, data });
      })
      .catch((err) => {
        // Request failure, dispatch the error
        dispatch({ type: `${type}_${FAILURE}`, err });
      });
  };
}

export default restMiddlewareCreator;
<commit_msg>Transition all params action / Пробросил все входящие параметры дальше<commit_after>import fetch from 'isomorphic-fetch';
import { merge } from 'lodash';
import defaultConfig from './config/defaultConfig';

function restMiddlewareCreator(customConfig) {
  const finalConfig = merge(defaultConfig, customConfig);
  const { suffix, fetchOptions } = finalConfig;

  return ({ dispatch }) => next => (action) => {
    if (!action || !action.$payload) {
      return next(action);
    }

    const [REQUEST, SUCCESS, FAILURE] = suffix;
    const { type, $payload } = action;
    const { url, options } = $payload;
    const opts = merge({}, fetchOptions, options);

    // Request start
    dispatch( Object.assign({}, action, { type: `${type}_${REQUEST}` }) );

    // Catch the response from service
    return fetch(url, opts)
      .then(response => response.json())
      .then((data) => {
        // Request success, dispatch the response data
        dispatch( Object.assign({}, action, { type: `${type}_${SUCCESS}`, data }) );
      })
      .catch((err) => {
        // Request failure, dispatch the error
        dispatch( Object.assign({}, action, { type: `${type}_${FAILURE}`, err }) );
      });
  };
}

export default restMiddlewareCreator;
<|endoftext|>


<commit_before>/**
 *
 * Pretty-Logger
 *
 * a simple logging library to make it easier for developers to log.  With this
 * library we want to achieve the following:
 *
 * 1.  pretty (read: human readable) console logs
 * 2.  informative console logs
 * 3.  control when, where and how console logs appear
 *
 * There are several libraries that already do this, however, unless there is
 * a must have feature that would be too difficult to implement ourselves, it
 * is very easy to roll out our own which give us 100% control over what and
 * how we log.
 *
 * This logging library supports latest browsers.  It will be very easy to make
 * it node compatible, but we are focusing this as
 * a front-end tool for the time being
 *
 * the log levels are as follows:
 *
 * info  : interesting to support stuff - read like prose
 * debug : interesting to developers - read in a way that is helpful
 * warn  : tell us a potential mistake we have made and how to resolve
 * error : tell us about a mistake that has happened and how to resolve
 *
 * @todo reduce the info, debug, warn and error function to a factory
 * @todo the VERSION should probably come from a package.json file.  We can acquire
 *       the version from the package.json by using a line like this:
 *       const VERSION = require('../package.json').version;
 */

import {VERSION, COLORS, LEVEL, ICON, BROWSER} from './constants';

/**
 *
 * HELPERS
 *
 */

/**
 * getter used to access a levels human readable name
 * @param {array} level - LEVEL.INFO
*/
function getLevelName(level) {
  const name = level[0];
  const capitalizedName = name.toUpperCase();

  return capitalizedName;
}

/**
 * getter used to access a levels numeric value
 * @param {array} level - LEVEL.INFO
*/
function getLevelValue(level) {
  const value = level[1];

  return value;
}

/**
 * getter used to access a levels color value
 * @param {array} level - LEVEL.INFO
*/
function getLevelColor(level) {
  const color = level[2];

  return color;
}

/**
 * check whether or not the environment is node
 * @return {boolean}
*/
function isNode() {
  return typeof module !== 'undefined' && typeof module.exports !== 'undefined';
}

/**
 * sets an alternative logging format for browser which have inconsistent
 * support for the console API
 * @return {boolean}
 */
function isSafeMode() {
  return BROWSER.IS_FIREFOX || BROWSER.IS_EXPLORER;
}

/**
 * check whether or not the environment is the browser
 * @return {boolean}
*/
function isBrowser() {
  return typeof window !== 'undefined';
}

// Logging system default level - which levels to show in console
export const DEFAULT_LEVEL = getLevelValue(LEVEL.INFO);

/**
 * adds color and font-weight to a console log message
 * @param  {string} msg - the string you want to format
 * @param  {string} levelColor - a hexcode e.g. #D87392
 * @return {string}
*/
function formatMsg(msg, levelName) {
  const lvl = LEVEL[levelName];
  const icon = ICON[levelName];
  let message;
  let styles;
  let otherStyles = '';

  /**
   * we are blocked by the browsers and the css properties they have whitelisted.
   * In this scenario we have to handle different browsers unqiely.
   */
  switch (true) {
    case BROWSER.IS_SAFARI:
      message = `%c%c ${msg}`;

      styles = [
        `background-image: url( ${icon} )`,
        'background-repeat: no-repeat',
        'background-size: 15px 15px',
        'padding-left: 15.2px',
      ].join(';');
      otherStyles = [
        `color: ${getLevelColor(lvl)}`,
        'font-weight: bold',
        'display: block',
        'padding-left: 15.2px',
        'padding-top: .4px',
      ].join(';');
      break;

    case BROWSER.IS_CHROME:
      message = `%c ${msg}`;

      styles = [
        `background-image: url( ${icon} )`,
        'background-repeat: no-repeat',
        'background-size: 13px 13px',
        `color: ${getLevelColor(lvl)}`,
        'font-weight: bold',
        'display: block',
        'margin-left: 5px',
        'padding-left: 18px',
      ].join(';');
      break;

    case BROWSER.IS_FIREFOX:
      message = `%c ${msg}`;

      styles = [
        `color: ${getLevelColor(lvl)}`,
        'font-weight: bold',
        'display: block',
        'margin-left: -6px', // line up subject and data logged
      ].join(';');
      break;
    default:
      console.error('pretty-logs could not identify the browser');
      break;
  }

  const styledMessage = [message, styles, otherStyles];

  return styledMessage;
}

/**
 *
 * Logging Suite
 *
 */

/**
 * format and process the log msg:
 *
 *     API - Thu Jan 05 2017 16:22:08 GMT-0500 (EST)
 *
 * @param {string} levelName - 'INFO', 'DEBUG', 'WARN', 'ERROR'
 * @param {string} category - log category e.g. API, REQUEST etc
 * @param {string} msg - helpful human readable message to log
 * @param {object} data - additional data
 * @example log('INFO', 'API', 'This is an API request', {...});
*/
function log(levelName, category, msg, data) {
  // setup
  const timestamp = new Date();
  const lvlColor = getLevelColor(LEVEL[levelName]);
  const groupMsg = `${category} - ${timestamp}`;
  const formattedGroupMsg = formatMsg(groupMsg, levelName);

  // turn the msg into an object for cleaner reading and machine friendliness
  const logMsg = {category, msg, data};
  const logMsgAsJson = JSON.stringify(logMsg);

  // log to the console
  if (isBrowser() && isSafeMode()) {
    console.log(...formattedGroupMsg);
    console.log(logMsg);
    console.log(''); // clear separation of one log to another
  } else if (isBrowser()) {
    console.groupCollapsed(...formattedGroupMsg);
    console.log(logMsg);
    console.groupEnd();
  }
}

/**
 * This is a helper method to reduce boilerplate.  The idea is that we use this
 * to generate logging functions which are functions that log a specific level.
 * for example, if you create log = makeLogger('LOG') you can then call it like
 * this:
 *
 * @example
 *  const logInfo = makeLogger('INFO');
 *  logInfo('API', 'This is an API request', {...});
 *
 * this is going to be an internal tool, the enduser will only be responsible
 * for creating some additional log levels if needed and then we will handle
 * the generation of these methods on our end.  I believe this is a strong idea
 * as it make this library very much data driven.
*/

function makeLogger(logName) {
  return function(category, message, data) {
    const levelValue = getLevelValue(LEVEL[logName]);
    const isActiveLogLevel = DEFAULT_LEVEL <= levelValue;

    if (isActiveLogLevel) {
      log(logName, category, message, data);
    }
  };
}

export const logInfo = makeLogger('INFO');
export const logDebug = makeLogger('DEBUG');
export const logWarn = makeLogger('WARN');
export const logError = makeLogger('ERROR');

/**
 *
 * Exports
 *
 */

const logger = {
  VERSION,
};

export default logger;
<commit_msg>Issue #5 formatting order (#19)<commit_after>/**
 *
 * Pretty-Logger
 *
 * a simple logging library to make it easier for developers to log.  With this
 * library we want to achieve the following:
 *
 * 1.  pretty (read: human readable) console logs
 * 2.  informative console logs
 * 3.  control when, where and how console logs appear
 *
 * There are several libraries that already do this, however, unless there is
 * a must have feature that would be too difficult to implement ourselves, it
 * is very easy to roll out our own which give us 100% control over what and
 * how we log.
 *
 * This logging library supports latest browsers.  It will be very easy to make
 * it node compatible, but we are focusing this as
 * a front-end tool for the time being
 *
 * the log levels are as follows:
 *
 * info  : interesting to support stuff - read like prose
 * debug : interesting to developers - read in a way that is helpful
 * warn  : tell us a potential mistake we have made and how to resolve
 * error : tell us about a mistake that has happened and how to resolve
 *
 * @todo reduce the info, debug, warn and error function to a factory
 * @todo the VERSION should probably come from a package.json file.  We can acquire
 *       the version from the package.json by using a line like this:
 *       const VERSION = require('../package.json').version;
 */

import {VERSION, COLORS, LEVEL, ICON, BROWSER} from './constants';

/**
 *
 * HELPERS
 *
 */

/**
 * getter used to access a levels human readable name
 * @param {array} level - LEVEL.INFO
*/
function getLevelName(level) {
  const name = level[0];
  const capitalizedName = name.toUpperCase();

  return capitalizedName;
}

/**
 * getter used to access a levels numeric value
 * @param {array} level - LEVEL.INFO
*/
function getLevelValue(level) {
  const value = level[1];

  return value;
}

/**
 * getter used to access a levels color value
 * @param {array} level - LEVEL.INFO
*/
function getLevelColor(level) {
  const color = level[2];

  return color;
}

/**
 * check whether or not the environment is node
 * @return {boolean}
*/
function isNode() {
  return typeof module !== 'undefined' && typeof module.exports !== 'undefined';
}

/**
 * sets an alternative logging format for browser which have inconsistent
 * support for the console API
 * @return {boolean}
 */
function isSafeMode() {
  return BROWSER.IS_FIREFOX || BROWSER.IS_EXPLORER;
}

/**
 * check whether or not the environment is the browser
 * @return {boolean}
*/
function isBrowser() {
  return typeof window !== 'undefined';
}

// Logging system default level - which levels to show in console
export const DEFAULT_LEVEL = getLevelValue(LEVEL.INFO);

/**
 * adds color and font-weight to a console log message
 * @param  {string} msg - the string you want to format
 * @param  {string} levelColor - a hexcode e.g. #D87392
 * @return {string}
*/
function formatMsg(msg, levelName) {
  const lvl = LEVEL[levelName];
  const icon = ICON[levelName];
  let message;
  let styles;
  let otherStyles = '';

  /**
   * we are blocked by the browsers and the css properties they have whitelisted.
   * In this scenario we have to handle different browsers unqiely.
   */
  switch (true) {
    case BROWSER.IS_SAFARI:
      message = `%c%c ${msg}`;

      styles = [
        `background-image: url( ${icon} )`,
        'background-repeat: no-repeat',
        'background-size: 15px 15px',
        'padding-left: 15.2px',
      ].join(';');
      otherStyles = [
        `color: ${getLevelColor(lvl)}`,
        'font-weight: bold',
        'display: block',
        'padding-left: 15.2px',
        'padding-top: .4px',
      ].join(';');
      break;

    case BROWSER.IS_CHROME:
      message = `%c ${msg}`;

      styles = [
        `background-image: url( ${icon} )`,
        'background-repeat: no-repeat',
        'background-size: 13px 13px',
        `color: ${getLevelColor(lvl)}`,
        'font-weight: bold',
        'display: block',
        'margin-left: 5px',
        'padding-left: 18px',
      ].join(';');
      break;

    case BROWSER.IS_FIREFOX:
      message = `%c ${msg}`;

      styles = [
        `color: ${getLevelColor(lvl)}`,
        'font-weight: bold',
        'display: block',
        'margin-left: -6px', // line up subject and data logged
      ].join(';');
      break;
    default:
      console.error('pretty-logs could not identify the browser');
      break;
  }

  const styledMessage = [message, styles, otherStyles];

  return styledMessage;
}

/**
 *
 * Logging Suite
 *
 */

/**
 * format and process the log msg:
 *
 *     API - Thu Jan 05 2017 16:22:08 GMT-0500 (EST)
 *
 * @param {string} levelName - 'INFO', 'DEBUG', 'WARN', 'ERROR'
 * @param {string} category - log category e.g. API, REQUEST etc
 * @param {string} msg - helpful human readable message to log
 * @param {object} data - additional data
 * @example log('INFO', 'API', 'This is an API request', {...});
*/
function log(levelName, category, msg, data) {
  // setup
  const timestamp = new Date();
  const date = timestamp.toLocaleDateString();
  const time = timestamp.toLocaleTimeString();
  const dateTime = `${date}, ${time}`;

  const lvlColor = getLevelColor(LEVEL[levelName]);
  const groupMsg = `${dateTime} - ${msg}`;
  const formattedGroupMsg = formatMsg(groupMsg, levelName);

  // turn the msg into an object for cleaner reading and machine friendliness
  const logMsg = {category, msg, data};
  const logMsgAsJson = JSON.stringify(logMsg);

  // log to the console
  if (isBrowser() && isSafeMode()) {
    console.log(...formattedGroupMsg);
    console.log(logMsg);
    console.log(''); // clear separation of one log to another
  } else if (isBrowser()) {
    console.groupCollapsed(...formattedGroupMsg);
    console.log(logMsg);
    console.groupEnd();
  }
}

/**
 * This is a helper method to reduce boilerplate.  The idea is that we use this
 * to generate logging functions which are functions that log a specific level.
 * for example, if you create log = makeLogger('LOG') you can then call it like
 * this:
 *
 * @example
 *  const logInfo = makeLogger('INFO');
 *  logInfo('API', 'This is an API request', {...});
 *
 * this is going to be an internal tool, the enduser will only be responsible
 * for creating some additional log levels if needed and then we will handle
 * the generation of these methods on our end.  I believe this is a strong idea
 * as it make this library very much data driven.
*/

function makeLogger(logName) {
  return function(category, message, data) {
    const levelValue = getLevelValue(LEVEL[logName]);
    const isActiveLogLevel = DEFAULT_LEVEL <= levelValue;

    if (isActiveLogLevel) {
      log(logName, category, message, data);
    }
  };
}

export const logInfo = makeLogger('INFO');
export const logDebug = makeLogger('DEBUG');
export const logWarn = makeLogger('WARN');
export const logError = makeLogger('ERROR');

/**
 *
 * Exports
 *
 */

const logger = {
  VERSION,
};

export default logger;
<|endoftext|>


<commit_before>import chain from './chain';
import {clone, noop} from './utils';

function vq(el, props, opts = null) {
  if (!el || !props) throw new Error('Must have two or three args');

  if (!opts) {
    if (!('p' in props && 'o' in props)) {
      throw new Error('2nd arg must have `p` and `o` property when only two args is given');
    }

    opts = props.o;
    props = props.p;
  }

  // use `props` as progress callback if it is a function
  if (typeof props === 'function') {
    opts.progress = props;
    props = {
      tween: [1, 0]
    };
  }

  // Avoid changing original props and opts
  // vq may mutate these values internally
  props = clone(props);
  opts = clone(opts);

  return chain(el, props, opts);
}

vq.sequence = function sequence(seq) {
  return function(done) {
    // Do not use ES default parameters because the babel eliminates actual arguments.
    // Then we cannot detect whether the callback is set or not.
    if (typeof done !== 'function') done = noop;

    sequenceImpl(seq, done);
  };
};

vq.parallel = function parallel(fns) {
  let waiting = fns.length;

  return function(done) {
    // Do not use ES default parameters because the babel eliminates actual arguments.
    // Then we cannot detect whether the callback is set or not.
    if (typeof done !== 'function') done = noop;

    const listener = function listener() {
      --waiting;
      if (waiting === 0) done();
    };

    for (const fn of fns) {
      unify(fn)(listener);
    }
  };
};

function sequenceImpl(seq, done) {
  if (seq.length === 0) return done();

  const head = unify(seq[0]);
  const tail = seq.slice(1);

  return head(() => sequenceImpl(tail, done));
}

function unify(fn) {
  return function(done) {
    if (typeof fn !== 'function') return done();

    if (fn.length > 0) {
      // Ensure there is a callback function as 1st argument
      return fn(done);
    }

    const res = fn();

    // Wait until the function is terminated if the returned value is thenable
    if (res && typeof res.then === 'function') {
      return res.then(done);
    }

    return done();
  };
}

module.exports = vq;
<commit_msg>Stop using for-of for IE<commit_after>import chain from './chain';
import {clone, noop} from './utils';

function vq(el, props, opts = null) {
  if (!el || !props) throw new Error('Must have two or three args');

  if (!opts) {
    if (!('p' in props && 'o' in props)) {
      throw new Error('2nd arg must have `p` and `o` property when only two args is given');
    }

    opts = props.o;
    props = props.p;
  }

  // use `props` as progress callback if it is a function
  if (typeof props === 'function') {
    opts.progress = props;
    props = {
      tween: [1, 0]
    };
  }

  // Avoid changing original props and opts
  // vq may mutate these values internally
  props = clone(props);
  opts = clone(opts);

  return chain(el, props, opts);
}

vq.sequence = function sequence(seq) {
  return function(done) {
    // Do not use ES default parameters because the babel eliminates actual arguments.
    // Then we cannot detect whether the callback is set or not.
    if (typeof done !== 'function') done = noop;

    sequenceImpl(seq, done);
  };
};

vq.parallel = function parallel(fns) {
  let waiting = fns.length;

  return function(done) {
    // Do not use ES default parameters because the babel eliminates actual arguments.
    // Then we cannot detect whether the callback is set or not.
    if (typeof done !== 'function') done = noop;

    const listener = function listener() {
      --waiting;
      if (waiting === 0) done();
    };

    for (let i = 0, len = fns.length; i < len; i++) {
      unify(fns[i])(listener);
    }
  };
};

function sequenceImpl(seq, done) {
  if (seq.length === 0) return done();

  const head = unify(seq[0]);
  const tail = seq.slice(1);

  return head(() => sequenceImpl(tail, done));
}

function unify(fn) {
  return function(done) {
    if (typeof fn !== 'function') return done();

    if (fn.length > 0) {
      // Ensure there is a callback function as 1st argument
      return fn(done);
    }

    const res = fn();

    // Wait until the function is terminated if the returned value is thenable
    if (res && typeof res.then === 'function') {
      return res.then(done);
    }

    return done();
  };
}

module.exports = vq;
<|endoftext|>


<commit_before>/* global c */

import { boxGeom_create } from './boxGeom';
import { bufferGeom_create, bufferGeom_fromGeom } from './bufferGeom';
import { camera_create, camera_lookAt, camera_updateProjectionMatrix } from './camera';
import { cylinderGeom_create } from './cylinderGeom';
import { directionalLight_create } from './directionalLight';
import { mat4_getInverse, mat4_multiplyMatrices } from './mat4';
import { material_create } from './material';
import { mesh_create } from './mesh';
import { object3d_create, object3d_add, object3d_updateMatrixWorld } from './object3d';
import { quat_setFromEuler } from './quat';
import {
  createShaderProgram,
  createFloat32Buffer,
  setFloat32Attribute,
  setFloatUniform,
  setMat4Uniform,
  setVec3Uniform,
  getAttributeLocations,
  getUniformLocations,
} from './shader';
import {
  vec3_create,
  vec3_multiplyScalar,
  vec3_setFromMatrixPosition,
  vec3_set,
  vec3_add,
  vec3_sub,
  vec3_transformDirection,
  vec3_applyQuaternion,
} from './vec3';
import { align } from './boxAlign';
import { colors, defaultColors } from './boxColors';
import { scale } from './boxTransform';
import { worm_create } from './worm';
import { controls_create } from './controls';
import { pointerLock_create } from './pointerLock';
import { compose } from './utils';
import playAudio from './audio';

import vs from './shaders/phong_vert.glsl';
import fs from './shaders/phong_frag.glsl';

var boxMaterial = material_create();
vec3_set(boxMaterial.color, 1, 0.4, 0.8);
vec3_set(boxMaterial.specular, 1, 1, 1);

var box = boxGeom_create(1, 1, 1);
align('px_py')(box);
var mesh = mesh_create(box, boxMaterial);
quat_setFromEuler(mesh.quaternion, vec3_create(0, 0, -Math.PI / 6));

var box2 = boxGeom_create(1, 4, 1);
compose(
  align('py'),
  scale({ py: 0 }),
  align('px'),
  defaultColors([1, 1, 1]),
  colors({ py: [0.5, 0, 1] })
)(box2);
var mesh2 = mesh_create(box2, boxMaterial);
mesh2.position.x = 2;

var group = object3d_create();
var boxCount = 144;
group.position.x = -Math.sqrt(boxCount) / 2;
group.position.z = -Math.sqrt(boxCount) / 2;
for (var i = 0; i < boxCount; i++) {
  var box3 = boxGeom_create(0.75, 0.2, 0.75);
  compose(
    defaultColors([1, 1, 1]),
    colors({ ny: [0.5, 0, 0.7] })
  )(box3);
  var mesh3 = mesh_create(box3, boxMaterial);
  mesh3.position.x = Math.floor(i / Math.sqrt(boxCount));
  mesh3.position.z = i % Math.sqrt(boxCount);
  object3d_add(group, mesh3);
}

var cylinder = cylinderGeom_create(1, 1, 4, 8, 1);
var mesh4 = mesh_create(cylinder, boxMaterial);

var worm = worm_create(8, 0.5, 0.5, 1, 0.2);

var camera = camera_create(60, window.innerWidth / window.innerHeight);
vec3_set(camera.position, 4, 2, 8);
camera_lookAt(camera, vec3_create());
pointerLock_create(controls_create(camera), c);

var fogColor = vec3_create(0, 0, 0);
var fogNear = 0.1;
var fogFar = 20;

var ambientLightColor = vec3_create(0.5, 0.5, 0.9);

var light = directionalLight_create(vec3_create(1, 0.5, 0.5));
var directionalLights = [light];

var scene = object3d_create();
object3d_add(scene, mesh);
object3d_add(scene, mesh2);
object3d_add(scene, group);
object3d_add(scene, mesh4);
object3d_add(scene, worm);
object3d_add(scene, camera);
object3d_add(scene, light);

c.width = window.innerWidth;
c.height = window.innerHeight;

var gl = c.getContext('webgl');
gl.clearColor(0, 0, 0, 0);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
gl.getExtension('OES_standard_derivatives');

var program = createShaderProgram(gl, vs, fs);

var attributes = getAttributeLocations(gl, program);
var uniforms = getUniformLocations(gl, program);

gl.useProgram(program);

function setFloat32AttributeBuffer(name, location, bufferGeom, size) {
  var buffer = (
    bufferGeom.buffers[name] ||
    (bufferGeom.buffers[name] = createFloat32Buffer(gl, bufferGeom.attrs[name]))
  );

  setFloat32Attribute(gl, location, buffer, size);
}

function renderObject(object) {
  if (object.geometry && object.material) {
    var geometry = object.geometry;
    var material = object.material;

    setVec3Uniform(gl, uniforms.fogColor, fogColor);
    setFloatUniform(gl, uniforms.fogNear, fogNear);
    setFloatUniform(gl, uniforms.fogFar, fogFar);

    setVec3Uniform(gl, uniforms.diffuse, material.color);
    setVec3Uniform(gl, uniforms.specular, material.specular);
    setFloatUniform(gl, uniforms.shininess, material.shininess);
    setVec3Uniform(gl, uniforms.emissive, material.emissive);

    mat4_multiplyMatrices(object.modelViewMatrix, camera.matrixWorldInverse, object.matrixWorld);

    setMat4Uniform(gl, uniforms.modelViewMatrix, object.modelViewMatrix);
    setMat4Uniform(gl, uniforms.projectionMatrix, camera.projectionMatrix);

    if (!geometry._bufferGeom) {
      geometry._bufferGeom = bufferGeom_fromGeom(bufferGeom_create(), geometry);
    }

    setFloat32AttributeBuffer('position', attributes.position, geometry._bufferGeom, 3);
    setFloat32AttributeBuffer('color', attributes.color, geometry._bufferGeom, 3);

    gl.drawArrays(gl.TRIANGLES, 0, geometry._bufferGeom.attrs.position.length / 3);
  }

  object.children.map(renderObject);
}

var direction = vec3_create();

var pt;

function render(t) {
  t = (t || 0) * 1e-3;
  if (!pt) {
    pt = t;
  }

  var dt = t - pt;
  pt = t;

  vec3_applyQuaternion(vec3_set(direction, 0, 0, -dt * 2), camera.quaternion);
  vec3_add(camera.position, direction);

  mesh.position.x = Math.cos(t);
  quat_setFromEuler(mesh.quaternion, vec3_create(0, 0, t + 1));
  light.position.x = Math.cos(t) * 3;
  light.position.z = Math.sin(t) * 3;
  object3d_updateMatrixWorld(scene);
  mat4_getInverse(camera.matrixWorldInverse, camera.matrixWorld);

  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  setVec3Uniform(gl, uniforms.ambientLightColor, ambientLightColor);

  directionalLights.map(function(light, index) {
    var _vec3 = vec3_create();

    var direction = vec3_setFromMatrixPosition(vec3_create(), light.matrixWorld);
    vec3_setFromMatrixPosition(_vec3, light.target.matrixWorld);
    vec3_transformDirection(vec3_sub(direction, _vec3), camera.matrixWorldInverse);

    var color = vec3_multiplyScalar(Object.assign(vec3_create(), light.color), light.intensity);

    setVec3Uniform(gl, uniforms['directionalLights[' + index + '].direction'], direction);
    setVec3Uniform(gl, uniforms['directionalLights[' + index + '].color'], color);
  });

  scene.children.map(renderObject);

  requestAnimationFrame(render);
}

render();
playAudio();

function setSize(width, height) {
  c.width = width;
  c.height = height;
  gl.viewport(0, 0, width, height);
}

window.addEventListener('resize', function() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera_updateProjectionMatrix(camera);

  setSize(window.innerWidth, window.innerHeight);
});
<commit_msg>Extract scene update function<commit_after>/* global c */

import { boxGeom_create } from './boxGeom';
import { bufferGeom_create, bufferGeom_fromGeom } from './bufferGeom';
import { camera_create, camera_lookAt, camera_updateProjectionMatrix } from './camera';
import { cylinderGeom_create } from './cylinderGeom';
import { directionalLight_create } from './directionalLight';
import { mat4_getInverse, mat4_multiplyMatrices } from './mat4';
import { material_create } from './material';
import { mesh_create } from './mesh';
import { object3d_create, object3d_add, object3d_updateMatrixWorld } from './object3d';
import { quat_setFromEuler } from './quat';
import {
  createShaderProgram,
  createFloat32Buffer,
  setFloat32Attribute,
  setFloatUniform,
  setMat4Uniform,
  setVec3Uniform,
  getAttributeLocations,
  getUniformLocations,
} from './shader';
import {
  vec3_create,
  vec3_multiplyScalar,
  vec3_setFromMatrixPosition,
  vec3_set,
  vec3_add,
  vec3_sub,
  vec3_transformDirection,
  vec3_applyQuaternion,
} from './vec3';
import { align } from './boxAlign';
import { colors, defaultColors } from './boxColors';
import { scale } from './boxTransform';
import { worm_create } from './worm';
import { controls_create } from './controls';
import { pointerLock_create } from './pointerLock';
import { compose } from './utils';
import playAudio from './audio';

import vs from './shaders/phong_vert.glsl';
import fs from './shaders/phong_frag.glsl';

var boxMaterial = material_create();
vec3_set(boxMaterial.color, 1, 0.4, 0.8);
vec3_set(boxMaterial.specular, 1, 1, 1);

var box = boxGeom_create(1, 1, 1);
align('px_py')(box);
var mesh = mesh_create(box, boxMaterial);
quat_setFromEuler(mesh.quaternion, vec3_create(0, 0, -Math.PI / 6));

var box2 = boxGeom_create(1, 4, 1);
compose(
  align('py'),
  scale({ py: 0 }),
  align('px'),
  defaultColors([1, 1, 1]),
  colors({ py: [0.5, 0, 1] })
)(box2);
var mesh2 = mesh_create(box2, boxMaterial);
mesh2.position.x = 2;

var group = object3d_create();
var boxCount = 144;
group.position.x = -Math.sqrt(boxCount) / 2;
group.position.z = -Math.sqrt(boxCount) / 2;
for (var i = 0; i < boxCount; i++) {
  var box3 = boxGeom_create(0.75, 0.2, 0.75);
  compose(
    defaultColors([1, 1, 1]),
    colors({ ny: [0.5, 0, 0.7] })
  )(box3);
  var mesh3 = mesh_create(box3, boxMaterial);
  mesh3.position.x = Math.floor(i / Math.sqrt(boxCount));
  mesh3.position.z = i % Math.sqrt(boxCount);
  object3d_add(group, mesh3);
}

var cylinder = cylinderGeom_create(1, 1, 4, 8, 1);
var mesh4 = mesh_create(cylinder, boxMaterial);

var worm = worm_create(8, 0.5, 0.5, 1, 0.2);

var camera = camera_create(60, window.innerWidth / window.innerHeight);
vec3_set(camera.position, 4, 2, 8);
camera_lookAt(camera, vec3_create());
pointerLock_create(controls_create(camera), c);

var fogColor = vec3_create(0, 0, 0);
var fogNear = 0.1;
var fogFar = 20;

var ambientLightColor = vec3_create(0.5, 0.5, 0.9);

var light = directionalLight_create(vec3_create(1, 0.5, 0.5));
var directionalLights = [light];

var scene = object3d_create();
object3d_add(scene, mesh);
object3d_add(scene, mesh2);
object3d_add(scene, group);
object3d_add(scene, mesh4);
object3d_add(scene, worm);
object3d_add(scene, camera);
object3d_add(scene, light);

c.width = window.innerWidth;
c.height = window.innerHeight;

var gl = c.getContext('webgl');
gl.clearColor(0, 0, 0, 0);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
gl.getExtension('OES_standard_derivatives');

var program = createShaderProgram(gl, vs, fs);

var attributes = getAttributeLocations(gl, program);
var uniforms = getUniformLocations(gl, program);

gl.useProgram(program);

var pt;
var cameraDirection = vec3_create();

function updateObject(object, dt) {
  if (object.update) {
    object.update(dt);
  }

  object.children.map(function(child) {
    updateObject(child, dt);
  });
}

function update(t) {
  t = (t || 0) * 1e-3;
  if (!pt) {
    pt = t;
  }

  var dt = t - pt;
  pt = t;

  vec3_applyQuaternion(vec3_set(cameraDirection, 0, 0, -dt * 2), camera.quaternion);
  vec3_add(camera.position, cameraDirection);

  mesh.position.x = Math.cos(t);
  quat_setFromEuler(mesh.quaternion, vec3_create(0, 0, t + 1));
  light.position.x = Math.cos(t) * 3;
  light.position.z = Math.sin(t) * 3;

  scene.children.map(function(object) {
    updateObject(object, dt);
  });
}

function setFloat32AttributeBuffer(name, location, bufferGeom, size) {
  var buffer = (
    bufferGeom.buffers[name] ||
    (bufferGeom.buffers[name] = createFloat32Buffer(gl, bufferGeom.attrs[name]))
  );

  setFloat32Attribute(gl, location, buffer, size);
}

function renderObject(object) {
  if (object.geometry && object.material) {
    var geometry = object.geometry;
    var material = object.material;

    setVec3Uniform(gl, uniforms.fogColor, fogColor);
    setFloatUniform(gl, uniforms.fogNear, fogNear);
    setFloatUniform(gl, uniforms.fogFar, fogFar);

    setVec3Uniform(gl, uniforms.diffuse, material.color);
    setVec3Uniform(gl, uniforms.specular, material.specular);
    setFloatUniform(gl, uniforms.shininess, material.shininess);
    setVec3Uniform(gl, uniforms.emissive, material.emissive);

    mat4_multiplyMatrices(object.modelViewMatrix, camera.matrixWorldInverse, object.matrixWorld);

    setMat4Uniform(gl, uniforms.modelViewMatrix, object.modelViewMatrix);
    setMat4Uniform(gl, uniforms.projectionMatrix, camera.projectionMatrix);

    if (!geometry._bufferGeom) {
      geometry._bufferGeom = bufferGeom_fromGeom(bufferGeom_create(), geometry);
    }

    setFloat32AttributeBuffer('position', attributes.position, geometry._bufferGeom, 3);
    setFloat32AttributeBuffer('color', attributes.color, geometry._bufferGeom, 3);

    gl.drawArrays(gl.TRIANGLES, 0, geometry._bufferGeom.attrs.position.length / 3);
  }

  object.children.map(renderObject);
}

function render(t) {
  update(t);

  object3d_updateMatrixWorld(scene);
  mat4_getInverse(camera.matrixWorldInverse, camera.matrixWorld);

  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  setVec3Uniform(gl, uniforms.ambientLightColor, ambientLightColor);

  directionalLights.map(function(light, index) {
    var _vec3 = vec3_create();

    var direction = vec3_setFromMatrixPosition(vec3_create(), light.matrixWorld);
    vec3_setFromMatrixPosition(_vec3, light.target.matrixWorld);
    vec3_transformDirection(vec3_sub(direction, _vec3), camera.matrixWorldInverse);

    var color = vec3_multiplyScalar(Object.assign(vec3_create(), light.color), light.intensity);

    setVec3Uniform(gl, uniforms['directionalLights[' + index + '].direction'], direction);
    setVec3Uniform(gl, uniforms['directionalLights[' + index + '].color'], color);
  });

  scene.children.map(renderObject);

  requestAnimationFrame(render);
}

render();
playAudio();

function setSize(width, height) {
  c.width = width;
  c.height = height;
  gl.viewport(0, 0, width, height);
}

window.addEventListener('resize', function() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera_updateProjectionMatrix(camera);

  setSize(window.innerWidth, window.innerHeight);
});
<|endoftext|>


<commit_before>var has = require("has"),
    isNull = require("is_null"),
    isFunction = require("is_function"),
    inherits = require("inherits"),
    EventEmitter = require("event_emitter"),
    createPool = require("create_pool"),
    uuid = require("uuid");

var ClassPrototype;

module.exports = Class;

function Class() {

    EventEmitter.call(this, -1);

    this.__id = null;
}
EventEmitter.extend(Class);
createPool(Class);
ClassPrototype = Class.prototype;

Class.extend = function(Child, className) {
    if (has(Class.__classes, className)) {
        throw new Error("extend(Child, className) class named " + className + " already defined");
    } else {
        Class.__classes[className] = Child;

        inherits(Child, this);
        createPool(Child);
        Child.className = Child.prototype.className = className;

        if (isFunction(this.onExtend)) {
            this.onExtend.apply(this, arguments);
        }

        return Child;
    }
};

Class.inherit = Class.extend;

Class.__classes = {};

Class.hasClass = function(className) {
    return has(Class.__classes, className);
};

Class.getClass = function(className) {
    if (Class.hasClass(className)) {
        return Class.__classes[className];
    } else {
        throw new Error("getClass(className) class named " + className + " is not defined");
    }
};

Class.newClass = function(className) {
    return new(Class.getClass(className))();
};

Class.fromJSON = function(json) {
    return (Class.newClass(json.className)).fromJSON(json);
};

Class.className = ClassPrototype.className = "Class";

Class.create = function() {
    var instance = new this();
    return instance.construct.apply(instance, arguments);
};

ClassPrototype.construct = function() {

    this.__id = uuid();

    return this;
};

ClassPrototype.destructor = function() {

    this.__id = null;

    return this;
};

ClassPrototype.generateNewId = function() {

    this.__id = uuid();

    return this;
};

ClassPrototype.toJSON = function(json) {
    json = json || {};

    json.className = this.className;

    return json;
};

ClassPrototype.fromJSON = function( /* json */ ) {

    if (isNull(this.__id)) {
        this.generateNewId();
    }

    return this;
};
<commit_msg>update<commit_after>var has = require("has"),
    isNull = require("is_null"),
    isFunction = require("is_function"),
    inherits = require("inherits"),
    EventEmitter = require("event_emitter"),
    createPool = require("create_pool"),
    uuid = require("uuid");

var ClassPrototype;

module.exports = Class;

function Class() {

    EventEmitter.call(this, -1);

    this.__id = null;
}
EventEmitter.extend(Class);
createPool(Class);
ClassPrototype = Class.prototype;

Class.extend = function(Child, className) {
    if (has(Class.__classes, className)) {
        throw new Error("extend(Child, className) class named " + className + " already defined");
    } else {
        Class.__classes[className] = Child;

        inherits(Child, this);
        createPool(Child);
        Child.className = Child.prototype.className = className;

        if (isFunction(this.onExtend)) {
            this.onExtend.apply(this, arguments);
        }

        return Child;
    }
};

Class.inherit = Class.extend;

Class.__classes = {};

Class.hasClass = function(className) {
    return has(Class.__classes, className);
};

Class.getClass = function(className) {
    if (Class.hasClass(className)) {
        return Class.__classes[className];
    } else {
        throw new Error("getClass(className) class named " + className + " is not defined");
    }
};

Class.newClass = function(className) {
    return new(Class.getClass(className))();
};

Class.fromJSON = function(json) {
    return (Class.newClass(json.className)).fromJSON(json);
};

Class.className = ClassPrototype.className = "Class";

Class.create = function() {
    var instance = new this();
    return instance.construct.apply(instance, arguments);
};

ClassPrototype.construct = function() {

    this.__id = uuid();

    return this;
};

ClassPrototype.destructor = function() {

    this.__id = null;

    return this;
};

ClassPrototype.generateNewId = function() {

    this.__id = uuid();

    return this;
};

ClassPrototype.toJSON = function(json) {
    json = json || {};

    json.__id = this.__id;
    json.className = this.className;

    return json;
};

ClassPrototype.fromJSON = function( /* json */ ) {

    if (isNull(this.__id)) {
        this.generateNewId();
    }

    return this;
};
<|endoftext|>


<commit_before>import {$debug, getExportNameForType, PLUGIN_NAME} from './util';
import convertToPropTypes from './convertToPropTypes';
import makePropTypesAst from './makePropTypesAst';

// maps between type alias name to prop types
let internalTypes = {};

// maps between type alias to import alias
let importedTypes = {};
let suppress = false;
const SUPPRESS_STRING = 'no babel-plugin-flow-react-proptypes';

const convertNodeToPropTypes = node => convertToPropTypes(
    node,
    importedTypes,
    internalTypes
);

const getPropsForTypeAnnotation = typeAnnotation => {
  const typeAnnotationReference = typeAnnotation.id && typeAnnotation.id.name;

  let props = null;
  if (typeAnnotationReference) {
    props = internalTypes[typeAnnotationReference] || importedTypes[typeAnnotationReference];
    if (!props) {
      $debug(`Did not find type annotation for reference ${typeAnnotationReference}`);
    }
  }
  else if (typeAnnotation.properties || typeAnnotation.type || 'GenericTypeAnnotation') {
    props = convertNodeToPropTypes(typeAnnotation);
  }
  else {
    throw new Error(`Expected prop types, but found none. This is a bug in ${PLUGIN_NAME}`);
  }

  return props;
};

const getFunctionalComponentTypeProps = path => {
  // Check if this looks like a stateless react component with PropType reference:
  const firstParam = path.node.params[0];
  const typeAnnotation = firstParam
    && firstParam.typeAnnotation
    && firstParam.typeAnnotation.typeAnnotation;

  if (!typeAnnotation) {
    $debug('Found stateless component without type definition');
    return;
  }

  return getPropsForTypeAnnotation(typeAnnotation);
};

export default function flowReactPropTypes(babel) {
  const t = babel.types;

  const isFunctionalReactComponent = path => {
    if ((path.type === 'ArrowFunctionExpression' || path.type === 'FunctionExpression') && !path.parent.id) {
      // Could be functions inside a React component
      return false;
    }
    if (t.isJSXElement(path.node.body)) {
      return true;
    }
    if (t.isCallExpression(path.node.body)) {
      const callee = path.node.body.callee;
      if (callee && callee.object && ['createElement', 'React'].indexOf(callee.object.name) >= 0) {
        return true;
      }
    }
    if (t.isBlockStatement(path.node.body)) {
      const bodyParts = path.node.body.body;
      if (!bodyParts) {
        return false;
      }

      for (let i = 0; i < bodyParts.length; i++) {
        const b = bodyParts[i];
        if (t.isExpressionStatement(b)) {
          if (t.isJSXElement(b.expression)) {
            return true;
          }
          const callee = b.expression.callee;
          if (callee && callee.object && ['createElement', 'React'].indexOf(callee.object.name) >= 0) {
            return true;
          }
        }
        if (t.isReturnStatement(b) && t.isJSXElement(b.argument)) {
          return true;
        }
      }
    }
    return false;
  };

  const annotate = (path, props) => {
    let name;
    let targetPath;

    if (path.type === 'ArrowFunctionExpression' || path.type === 'FunctionExpression') {
      name = path.parent.id.name;
      const basePath = path.parentPath.parentPath;
      targetPath = t.isExportDeclaration(basePath.parent) ? basePath.parentPath : basePath;
    }
    else {
      name = path.node.id.name;
      targetPath = path.parent.type === 'Program' ? path : path.parentPath;
    }

    if (!props) {
      throw new Error(`Did not find type annotation for ${name}`);
    }

    if (!props.properties) {
      // Bail out if we don't have any properties. This will be the case if
      // we have an imported PropType, like:
      // import type { T } from '../types';
      // const C = (props: T) =>
{props.name}
;
      return;
    }

    const propTypesAST = makePropTypesAst(props);
    const attachPropTypesAST = t.expressionStatement(
      t.assignmentExpression(
        '=',
        t.memberExpression(t.identifier(name), t.identifier('propTypes')),
        propTypesAST
      )
    );
    targetPath.insertAfter(attachPropTypesAST);
  };

  const functionVisitor = path => {
    if (!isFunctionalReactComponent(path)) {
      return;
    }
    const props = getFunctionalComponentTypeProps(path);
    if (props) {
      annotate(path, props);
    }
  };

  return {
    visitor: {
      Program(path) {
        internalTypes = {};
        importedTypes = {};
        suppress = false;
        let directives = path.node.directives;
        if(directives && directives.length)  {
          let directive = directives[0];
          if (directive.value && directive.value.value == SUPPRESS_STRING) {
            suppress = true;
          }
        }
      },
      TypeAlias(path) {
        if (suppress) return;
        $debug('TypeAlias found');
        const {right} = path.node;

        const typeAliasName = path.node.id.name;
        if (!typeAliasName) {
          throw new Error('Did not find name for type alias');
        }

        const propTypes = convertNodeToPropTypes(right);
        internalTypes[typeAliasName] = propTypes;
      },
      ClassDeclaration(path) {
        if (suppress) return;
        const {superClass} = path.node;

        // check if we're extending React.Compoennt
        const extendsReactComponent = superClass && superClass.type === 'MemberExpression'
        && superClass.object.name === 'React'
        && superClass.property.name === 'Component';
        const extendsComponent = superClass && superClass.type === 'Identifier' && superClass.name === 'Component';
        if (!extendsReactComponent && !extendsComponent) {
          $debug('Found a class that isn\'t a react component', superClass);
          return;
        }

        // And have type as property annotations or Component<void, Props, void>
        path.node.body.body.forEach(bodyNode => {
          if (bodyNode && bodyNode.key.name === 'props' && bodyNode.typeAnnotation) {
            const props = getPropsForTypeAnnotation(bodyNode.typeAnnotation.typeAnnotation);
            return annotate(path, props);
          }
        });

        // super type parameter
        const secondSuperParam = path.node.superTypeParameters && path.node.superTypeParameters.params[1];
        if (secondSuperParam && secondSuperParam.type === 'GenericTypeAnnotation') {
          const typeAliasName = secondSuperParam.id.name;
          const props = internalTypes[typeAliasName];
          return annotate(path, props);
        }
      },

      FunctionExpression(path) {
        if (suppress) return;
        return functionVisitor(path);
      },

      FunctionDeclaration(path) {
        if (suppress) return;
        return functionVisitor(path);
      },

      ArrowFunctionExpression(path) {
        if (suppress) return;
        return functionVisitor(path);
      },

      // See issue:
      ExportNamedDeclaration(path) {
        if (suppress) return;
        const {node} = path;

        if (!node.declaration || node.declaration.type !== 'TypeAlias') {
          return;
        }
        if (!node.declaration.right.properties) {
          return;
        }

        const name = node.declaration.id.name;
        const propTypes = convertNodeToPropTypes(node.declaration.right);
        internalTypes[name] = propTypes;

        let propTypesAst = makePropTypesAst(propTypes);

        if (propTypesAst.type === 'ObjectExpression') {
          propTypesAst = t.callExpression(
            t.memberExpression(
              t.memberExpression(
                t.callExpression(
                  t.identifier('require'),
                  [t.stringLiteral('react')]
                ),
                t.identifier('PropTypes')
              ),
              t.identifier('shape'),
            ),
            [propTypesAst],
          );
        }

        const exportAst = t.expressionStatement(t.callExpression(
          t.memberExpression(t.identifier('Object'), t.identifier('defineProperty')),
          [
            t.memberExpression(t.identifier('module'), t.identifier('exports')),
            t.stringLiteral(getExportNameForType(name)),
            propTypesAst,
          ]
        ));
        path.insertAfter(exportAst);
      },
      ImportDeclaration(path) {
        if (suppress) return;
        const {node} = path;
        if (node.importKind === 'type') {
          node.specifiers.forEach((specifier) => {
            const typeName = specifier.type === 'ImportDefaultSpecifier'
              ? specifier.local.name
              : specifier.imported.name;

            importedTypes[typeName] = getExportNameForType(typeName);
            const variableDeclarationAst = t.variableDeclaration(
              'var',
              [
                t.variableDeclarator(
                  // TODO: use local import name?
                  t.identifier(getExportNameForType(typeName)),
                  t.logicalExpression(
                    '||',
                    t.memberExpression(
                      t.callExpression(
                        t.identifier('require'),
                        [t.stringLiteral(node.source.value)]
                      ),
                      t.identifier(getExportNameForType(typeName))
                    ),
                    t.memberExpression(
                      t.memberExpression(
                        t.callExpression(
                          t.identifier('require'),
                          [
                            t.stringLiteral('react'),
                          ]
                        ),
                        t.identifier('PropTypes')
                      ),
                      t.identifier('any')
                    )
                  ),
                )
              ]
            );
            path.insertAfter(variableDeclarationAst);
          });
        }
      }
    }
  };
};
<commit_msg>fixes lint errors<commit_after>import {$debug, getExportNameForType, PLUGIN_NAME} from './util';
import convertToPropTypes from './convertToPropTypes';
import makePropTypesAst from './makePropTypesAst';

// maps between type alias name to prop types
let internalTypes = {};

// maps between type alias to import alias
let importedTypes = {};
let suppress = false;
const SUPPRESS_STRING = 'no babel-plugin-flow-react-proptypes';

const convertNodeToPropTypes = node => convertToPropTypes(
    node,
    importedTypes,
    internalTypes
);

const getPropsForTypeAnnotation = typeAnnotation => {
  const typeAnnotationReference = typeAnnotation.id && typeAnnotation.id.name;

  let props = null;
  if (typeAnnotationReference) {
    props = internalTypes[typeAnnotationReference] || importedTypes[typeAnnotationReference];
    if (!props) {
      $debug(`Did not find type annotation for reference ${typeAnnotationReference}`);
    }
  }
  else if (typeAnnotation.properties || typeAnnotation.type || 'GenericTypeAnnotation') {
    props = convertNodeToPropTypes(typeAnnotation);
  }
  else {
    throw new Error(`Expected prop types, but found none. This is a bug in ${PLUGIN_NAME}`);
  }

  return props;
};

const getFunctionalComponentTypeProps = path => {
  // Check if this looks like a stateless react component with PropType reference:
  const firstParam = path.node.params[0];
  const typeAnnotation = firstParam
    && firstParam.typeAnnotation
    && firstParam.typeAnnotation.typeAnnotation;

  if (!typeAnnotation) {
    $debug('Found stateless component without type definition');
    return;
  }

  return getPropsForTypeAnnotation(typeAnnotation);
};

export default function flowReactPropTypes(babel) {
  const t = babel.types;

  const isFunctionalReactComponent = path => {
    if ((path.type === 'ArrowFunctionExpression' || path.type === 'FunctionExpression') && !path.parent.id) {
      // Could be functions inside a React component
      return false;
    }
    if (t.isJSXElement(path.node.body)) {
      return true;
    }
    if (t.isCallExpression(path.node.body)) {
      const callee = path.node.body.callee;
      if (callee && callee.object && ['createElement', 'React'].indexOf(callee.object.name) >= 0) {
        return true;
      }
    }
    if (t.isBlockStatement(path.node.body)) {
      const bodyParts = path.node.body.body;
      if (!bodyParts) {
        return false;
      }

      for (let i = 0; i < bodyParts.length; i++) {
        const b = bodyParts[i];
        if (t.isExpressionStatement(b)) {
          if (t.isJSXElement(b.expression)) {
            return true;
          }
          const callee = b.expression.callee;
          if (callee && callee.object && ['createElement', 'React'].indexOf(callee.object.name) >= 0) {
            return true;
          }
        }
        if (t.isReturnStatement(b) && t.isJSXElement(b.argument)) {
          return true;
        }
      }
    }
    return false;
  };

  const annotate = (path, props) => {
    let name;
    let targetPath;

    if (path.type === 'ArrowFunctionExpression' || path.type === 'FunctionExpression') {
      name = path.parent.id.name;
      const basePath = path.parentPath.parentPath;
      targetPath = t.isExportDeclaration(basePath.parent) ? basePath.parentPath : basePath;
    }
    else {
      name = path.node.id.name;
      targetPath = path.parent.type === 'Program' ? path : path.parentPath;
    }

    if (!props) {
      throw new Error(`Did not find type annotation for ${name}`);
    }

    if (!props.properties) {
      // Bail out if we don't have any properties. This will be the case if
      // we have an imported PropType, like:
      // import type { T } from '../types';
      // const C = (props: T) =>
{props.name}
;
      return;
    }

    const propTypesAST = makePropTypesAst(props);
    const attachPropTypesAST = t.expressionStatement(
      t.assignmentExpression(
        '=',
        t.memberExpression(t.identifier(name), t.identifier('propTypes')),
        propTypesAST
      )
    );
    targetPath.insertAfter(attachPropTypesAST);
  };

  const functionVisitor = path => {
    if (!isFunctionalReactComponent(path)) {
      return;
    }
    const props = getFunctionalComponentTypeProps(path);
    if (props) {
      annotate(path, props);
    }
  };

  return {
    visitor: {
      Program(path) {
        internalTypes = {};
        importedTypes = {};
        suppress = false;
        const directives = path.node.directives;
        if(directives && directives.length)  {
          const directive = directives[0];
          if (directive.value && directive.value.value == SUPPRESS_STRING) {
            suppress = true;
          }
        }
      },
      TypeAlias(path) {
        if (suppress) return;
        $debug('TypeAlias found');
        const {right} = path.node;

        const typeAliasName = path.node.id.name;
        if (!typeAliasName) {
          throw new Error('Did not find name for type alias');
        }

        const propTypes = convertNodeToPropTypes(right);
        internalTypes[typeAliasName] = propTypes;
      },
      ClassDeclaration(path) {
        if (suppress) return;
        const {superClass} = path.node;

        // check if we're extending React.Compoennt
        const extendsReactComponent = superClass && superClass.type === 'MemberExpression'
        && superClass.object.name === 'React'
        && superClass.property.name === 'Component';
        const extendsComponent = superClass && superClass.type === 'Identifier' && superClass.name === 'Component';
        if (!extendsReactComponent && !extendsComponent) {
          $debug('Found a class that isn\'t a react component', superClass);
          return;
        }

        // And have type as property annotations or Component<void, Props, void>
        path.node.body.body.forEach(bodyNode => {
          if (bodyNode && bodyNode.key.name === 'props' && bodyNode.typeAnnotation) {
            const props = getPropsForTypeAnnotation(bodyNode.typeAnnotation.typeAnnotation);
            return annotate(path, props);
          }
        });

        // super type parameter
        const secondSuperParam = path.node.superTypeParameters && path.node.superTypeParameters.params[1];
        if (secondSuperParam && secondSuperParam.type === 'GenericTypeAnnotation') {
          const typeAliasName = secondSuperParam.id.name;
          const props = internalTypes[typeAliasName];
          return annotate(path, props);
        }
      },

      FunctionExpression(path) {
        if (suppress) return;
        return functionVisitor(path);
      },

      FunctionDeclaration(path) {
        if (suppress) return;
        return functionVisitor(path);
      },

      ArrowFunctionExpression(path) {
        if (suppress) return;
        return functionVisitor(path);
      },

      // See issue:
      ExportNamedDeclaration(path) {
        if (suppress) return;
        const {node} = path;

        if (!node.declaration || node.declaration.type !== 'TypeAlias') {
          return;
        }
        if (!node.declaration.right.properties) {
          return;
        }

        const name = node.declaration.id.name;
        const propTypes = convertNodeToPropTypes(node.declaration.right);
        internalTypes[name] = propTypes;

        let propTypesAst = makePropTypesAst(propTypes);

        if (propTypesAst.type === 'ObjectExpression') {
          propTypesAst = t.callExpression(
            t.memberExpression(
              t.memberExpression(
                t.callExpression(
                  t.identifier('require'),
                  [t.stringLiteral('react')]
                ),
                t.identifier('PropTypes')
              ),
              t.identifier('shape'),
            ),
            [propTypesAst],
          );
        }

        const exportAst = t.expressionStatement(t.callExpression(
          t.memberExpression(t.identifier('Object'), t.identifier('defineProperty')),
          [
            t.memberExpression(t.identifier('module'), t.identifier('exports')),
            t.stringLiteral(getExportNameForType(name)),
            propTypesAst,
          ]
        ));
        path.insertAfter(exportAst);
      },
      ImportDeclaration(path) {
        if (suppress) return;
        const {node} = path;
        if (node.importKind === 'type') {
          node.specifiers.forEach((specifier) => {
            const typeName = specifier.type === 'ImportDefaultSpecifier'
              ? specifier.local.name
              : specifier.imported.name;

            importedTypes[typeName] = getExportNameForType(typeName);
            const variableDeclarationAst = t.variableDeclaration(
              'var',
              [
                t.variableDeclarator(
                  // TODO: use local import name?
                  t.identifier(getExportNameForType(typeName)),
                  t.logicalExpression(
                    '||',
                    t.memberExpression(
                      t.callExpression(
                        t.identifier('require'),
                        [t.stringLiteral(node.source.value)]
                      ),
                      t.identifier(getExportNameForType(typeName))
                    ),
                    t.memberExpression(
                      t.memberExpression(
                        t.callExpression(
                          t.identifier('require'),
                          [
                            t.stringLiteral('react'),
                          ]
                        ),
                        t.identifier('PropTypes')
                      ),
                      t.identifier('any')
                    )
                  ),
                )
              ]
            );
            path.insertAfter(variableDeclarationAst);
          });
        }
      }
    }
  };
};
<|endoftext|>