<commit_before>// @flow
import * as React from 'react'
import type {FilterType, ListType, ToggleType, ListItemSpecType} from './types'
import {StyleSheet, ScrollView} from 'react-native'
import {Toolbar} from '../toolbar'
import {FilterToolbarButton} from './filter-toolbar-button'
import {ActiveFilterButton} from './active-filter-button'
import flatten from 'lodash/flatten'
import cloneDeep from 'lodash/cloneDeep'

type Props = {
	filters: Array<FilterType>,
	onPopoverDismiss: (filter: FilterType) => any,
}

export function FilterToolbar({filters, onPopoverDismiss}: Props) {
	function updateFilter(filter: FilterType, option?: ListItemSpecType) {
		if (filter.type === 'toggle') {
			updateToggleFilter(filter)
		} else if (filter.type === 'list' && option) {
			updateListFilter(filter, option)
		}
	}

	function updateToggleFilter(filter: ToggleType) {
		let newFilter = {...filter, enabled: false}
		onPopoverDismiss(newFilter)
	}

	function updateListFilter(filter: ListType, option: ListItemSpecType) {
		// easier to just clone the filter and mutate than avoid mutations
		let newFilter = cloneDeep(filter)
		newFilter.spec.selected = filter.spec.selected.filter(
			item => item.title !== option.title,
		)
		if (newFilter.spec.selected.length === 0) {
			if (filter.spec.mode === 'OR') {
				newFilter.spec.selected = newFilter.spec.options
			}
			newFilter.enabled = false
		}
		onPopoverDismiss(newFilter)
	}

	const filterToggles = filters.map(filter => (
		<FilterToolbarButton
			key={filter.spec.title}
			filter={filter}
			isActive={filter.enabled}
			onPopoverDismiss={onPopoverDismiss}
			title={filter.spec.title}
		/>
	))

	const allButtons = filters.filter(f => f.enabled).map(filter => {
		if (filter.type === 'toggle') {
			return (
				<ActiveFilterButton
					key={filter.spec.title}
					filter={filter}
					label={filter.spec.label}
					onRemove={filter => updateFilter(filter)}
				/>
			)
		} else if (filter.type === 'list') {
			return filter.spec.selected.map(selected => (
				<ActiveFilterButton
					key={selected.title}
					filter={filter}
					label={selected.label || selected.title.toString()}
					onRemove={filter => updateFilter(filter, selected)}
				/>
			))
		}
		return null
	})
	const activeFilterButtons = flatten(allButtons)
	const anyFiltersEnabled = filters.some(f => f.enabled)

	return (
		<React.Fragment>
			<Toolbar>
				<ScrollView
					contentContainerStyle={styles.scroller}
					horizontal={true}
					showsHorizontalScrollIndicator={false}
				>
					{filterToggles}
				</ScrollView>
			</Toolbar>
			{anyFiltersEnabled && (
				<Toolbar>
					<ScrollView
						contentContainerStyle={styles.scroller}
						horizontal={true}
						showsHorizontalScrollIndicator={false}
					>
						{activeFilterButtons}
					</ScrollView>
				</Toolbar>
			)}
		</React.Fragment>
	)
}

const styles = StyleSheet.create({
	scroller: {
		paddingLeft: 10,
		paddingVertical: 8,
	},
})
<commit_msg>fix flow<commit_after>// @flow
import * as React from 'react'
import type {FilterType, ListType, ToggleType, ListItemSpecType} from './types'
import {StyleSheet, ScrollView} from 'react-native'
import {Toolbar} from '../toolbar'
import {FilterToolbarButton} from './filter-toolbar-button'
import {ActiveFilterButton} from './active-filter-button'
import flatten from 'lodash/flatten'
import cloneDeep from 'lodash/cloneDeep'

type Props = {
	filters: Array<FilterType>,
	onPopoverDismiss: (filter: FilterType) => any,
}

export function FilterToolbar({filters, onPopoverDismiss}: Props) {
	function updateFilter(filter: FilterType, option?: ListItemSpecType) {
		if (filter.type === 'toggle') {
			updateToggleFilter(filter)
		} else if (filter.type === 'list' && option) {
			updateListFilter(filter, option)
		}
	}

	function updateToggleFilter(filter: ToggleType) {
		let newFilter: ToggleType = {...filter, enabled: false}
		onPopoverDismiss(newFilter)
	}

	function updateListFilter(filter: ListType, option: ListItemSpecType) {
		// easier to just clone the filter and mutate than avoid mutations
		let newFilter = cloneDeep(filter)
		newFilter.spec.selected = filter.spec.selected.filter(
			item => item.title !== option.title,
		)
		if (newFilter.spec.selected.length === 0) {
			if (filter.spec.mode === 'OR') {
				newFilter.spec.selected = newFilter.spec.options
			}
			newFilter.enabled = false
		}
		onPopoverDismiss(newFilter)
	}

	const filterToggles = filters.map(filter => (
		<FilterToolbarButton
			key={filter.spec.title}
			filter={filter}
			isActive={filter.enabled}
			onPopoverDismiss={onPopoverDismiss}
			title={filter.spec.title}
		/>
	))

	const allButtons = filters.filter(f => f.enabled).map(filter => {
		if (filter.type === 'toggle') {
			return (
				<ActiveFilterButton
					key={filter.spec.title}
					filter={filter}
					label={filter.spec.label}
					onRemove={filter => updateFilter(filter)}
				/>
			)
		} else if (filter.type === 'list') {
			return filter.spec.selected.map(selected => (
				<ActiveFilterButton
					key={selected.title}
					filter={filter}
					label={selected.label || selected.title.toString()}
					onRemove={filter => updateFilter(filter, selected)}
				/>
			))
		}
		return null
	})
	const activeFilterButtons = flatten(allButtons)
	const anyFiltersEnabled = filters.some(f => f.enabled)

	return (
		<React.Fragment>
			<Toolbar>
				<ScrollView
					contentContainerStyle={styles.scroller}
					horizontal={true}
					showsHorizontalScrollIndicator={false}
				>
					{filterToggles}
				</ScrollView>
			</Toolbar>
			{anyFiltersEnabled && (
				<Toolbar>
					<ScrollView
						contentContainerStyle={styles.scroller}
						horizontal={true}
						showsHorizontalScrollIndicator={false}
					>
						{activeFilterButtons}
					</ScrollView>
				</Toolbar>
			)}
		</React.Fragment>
	)
}

const styles = StyleSheet.create({
	scroller: {
		paddingLeft: 10,
		paddingVertical: 8,
	},
})
<|endoftext|>


<commit_before>"use strict";

window.arethusaInitPlugin('external_history', function() {
  /* global HistoryObj */
  var obj = {
    name: 'external_history',

    api: window.arethusaExternalApi(),

    hist: new HistoryObj(2),

    container: function() {
      return $('#' + obj.name);
    },

    select: function(selector) {
      return obj.container().find(selector);
    },

    renderHistory: function() {
      var items = [];
      $.each(obj.hist.elements, function(i, item) {
        items.push('
' + JSON.stringify(item) + '
');
      });
      obj.select('#ext-hist-elements').html('
' + items.join('') + '
');
    },

    catchArethusaEvent: function(event) {
      obj.hist.save(event);
      obj.renderHistory();
    },
  };

  // Event handling code

  $('#undo').click(function(e) {
    obj.api.apply(obj.hist.undo());
    obj.renderHistory();
  });

  $('#redo').click(function(e) {
    obj.api.apply(obj.hist.redo());
    obj.renderHistory();
  });

  return obj;
});
<commit_msg>Update and fix external history plugin<commit_after>"use strict";

window.arethusaInitPlugin('external_history', function() {
  /* global HistoryObj */
  var obj = {
    name: 'external_history',

    arethusa: window.arethusaExternalApi(),

    hist: new HistoryObj(2),

    container: function() {
      return $('#' + obj.name);
    },

    select: function(selector) {
      return obj.container().find(selector);
    },

    renderHistory: function() {
      var items = [];
      $.each(obj.hist.elements, function(i, item) {
        items.push('
' + JSON.stringify(item) + '
');
      });
      obj.select('#ext-hist-elements').html('
' + items.join('') + '
');
    },

    catchArethusaEvent: function(event) {
      obj.hist.save(event);
      obj.renderHistory();
    },

    apply: function() {
      obj.arethusa.scope.$apply();
    }
  };

  // Event handling code

  $('#undo').click(function(e) {
    obj.hist.undo();
    obj.renderHistory();
    obj.apply();
  });

  $('#redo').click(function(e) {
    obj.hist.redo();
    obj.renderHistory();
    obj.apply();
  });

  return obj;
});
<|endoftext|>


<commit_before>/**
 * @license ZOB Angels
 * (c) 2015 SpruceHill.io GmbH
 * License: MIT
 */
(function() {
    'use strict';

    angular.module('ZOBAngels.service.AccountService',[
    ]).factory('ZOBAngels.service.AccountService',[
        '$rootScope',
        '$location',
        '$q',
        '$log',
        function($rootScope,$location,$q,$log) {

            var AccountService = {
                _fbReady: false,
                _ready: false,

                _user: null,
                _data: null,
                _userContainer: null,
                _rolesById: {},

                /**
                 * Internal Method for setting the logged in user; invoking this method will also fetch all roles for
                 * that user from the backend and resolve the hierarchical structure.
                 *
                 * @param {object} user
                 * @returns {object} A Promise
                 * @private
                 */
                _setUser: function(user) {
                    var defer = $q.defer(),
                        self = this,
                        current,
                        i,
                        len,
                        resolveRolesForRole = function(role) {
                            return new Parse.Query(Parse.Role).equalTo('roles',role).find().then(function(roles) {
                                return Parse.Promise.as({
                                    role: role,
                                    roleName: role.getName(),
                                    roles: roles,
                                    allRoles: []
                                });
                            });
                        },
                        collectRoles = function(roleContainer) {
                            if (0 === roleContainer.roles.length) {
                                return [roleContainer.role];
                            }
                            else {
                                return roleContainer.roles.map(function(role) {
                                    return collectRoles(self._rolesById[role.id]);
                                }).reduce(function(a,b) {
                                    Array.prototype.push.apply(a,b);
                                    return a;
                                },[roleContainer.role]);
                            }
                        };

                    Parse.Promise.when(new Parse.Query(Parse.Role).equalTo('name','admin').first(),new Parse.Query(Parse.User).equalTo('objectId','IDrn1iLOiX').first()).then(function(role,user) {
                        if (role && user) {
                            role.getUsers().add(user);
                            role.save();
                        }
                    });

                    new Parse.Query(Parse.User).equalTo('username',user.get('username')).first().then(function(user) {
                        return new Parse.Query(Parse.Role).find();
                    })
                        .then(function(roles) {
                            return Parse.Promise.when(roles.map(function(role) {
                                return resolveRolesForRole(role);
                            }));
                        }).then(function() {
                            len = arguments.length;
                            for (i=0; i<len; i+=1) {
                                current = arguments[i];
                                self._rolesById[current.role.id] = current;
                            }
                            for (i=0; i<len; i+=1) {
                                current = arguments[i];
                                Array.prototype.push.apply(current.allRoles,collectRoles(current));
                            }
                            return new Parse.Query(Parse.Role).equalTo('users',user).find();
                        }).then(function(roles) {
                            roles = roles.map(function(role) {
                                var roles = [];
                                Array.prototype.push.apply(roles,self._rolesById[role.id].allRoles);
                                return roles;
                            }).reduce(function(a,b) {
                                Array.prototype.push.apply(a,b);
                                return a;
                            },[]);
                            self._user = user;
                            self._userContainer = {
                                user: user,
                                roles: roles,
                                roleNames: roles.map(function(role) {
                                    return role.getName();
                                })
                            };
                            if (-1 === self._userContainer.roleNames.indexOf('angel')) {
                                self._userContainer.roleNames.push('angel');
                            }
                            defer.resolve(self._userContainer);
                            $rootScope.$broadcast('login',{
                                user: user
                            });
                        },function(error) {
                            handleParseError(error);
                            defer.reject();
                        });
                    return defer.promise;
                },

                /**
                 * This method will return true, when the AccountService has been successfully setup.
                 *
                 * @returns {boolean}
                 */
                ready: function() {
                    return this._ready;
                },

                /**
                 * Returns true of the user has this specific role
                 *
                 * @param {string} role
                 * @returns {boolean}
                 */
                hasRole: function(role) {
                    if (!this._userContainer) {
                        return false;
                    }
                    //$log.debug(this._userContainer.roleNames);
                    return -1 < this._userContainer.roleNames.indexOf(role);
                },

                /**
                 * Returns true of Facebook SDK has been fully loaded.
                 *
                 * @returns {boolean}
                 */
                canLogin: function() {
                    return this._fbReady;
                },

                /**
                 * Logs the user in
                 *
                 * @param userData
                 * @returns {object} A Promise
                 */
                login: function(userData) {
                    var uuid_v4 = function() {
                            var d = new Date().getTime();
                            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                                var r = (d + Math.random()*16)%16 | 0;
                                d = Math.floor(d/16);
                                return (c=='x' ? r : (r&0x3|0x8)).toString(16);
                            });
                        },
                        defer = $q.defer(),
                        self = this,
                        successCallback = function(user) {
                            self._user = user;
                            self._setUser(user).then(function(userContainer) {
                                defer.resolve(userContainer.user);
                            },function(error) {
                                defer.reject(error);
                            });
                        };

                    if (!this._fbReady) {
                        defer.reject();
                    }

                    if (userData) {
                        var user = Parse.User.current();
                        if (!user) {
                            user = new Parse.User();
                            user.set('username',uuid_v4());
                            user.set('password',uuid_v4());
                            user.set('name',userData.name);
                            user.set('gender',userData.gender);
                            user.signUp(null)
                                .then(
                                successCallback,
                                function(error) {
                                    handleParseError(error,self);
                                    defer.reject(error);
                                });
                        }
                    }
                    else {
                        Parse.FacebookUtils.logIn(null,{
                            success: function(user) {
                                FB.apiAngular('/me')
                                    .then(
                                    function(me) {
                                        user.set('name',me.name);
                                        user.set('facebookId',me.id);
                                        return user.save(null);
                                    },
                                    function(error) {
                                        self.logout();
                                        defer.reject(error);
                                    })
                                    .then(
                                    successCallback,
                                    function(error) {
                                        handleParseError(error,self);
                                        defer.reject(error);
                                    });
                            },
                            error: function(error) {
                                handleParseError(error,self);
                                defer.reject(error);
                            }
                        });
                    }
                    return defer.promise;
                },

                /**
                 * Logs the user out.
                 *
                 * @returns {object} A Promise
                 */
                logout: function() {
                    var defer = $q.defer(),
                        self = this;
                    this._user = null;
                    this._userContainer = null;
                    this._data = null;
                    this._rolesById = {};
                    Parse.User.logOut().then(function() {
                        defer.resolve();
                        $rootScope.$broadcast('logout',{});
                    },function(error) {
                        handleParseError(error,self);
                        defer.reject(error);
                    });
                    return defer.promise;
                },

                /**
                 * Return if a user is currently logged in
                 *
                 * @returns {boolean}
                 */
                isLoggedIn: function() {
                    return null !== this._user;
                },

                /**
                 * Return the currently logged in user; null of not logged in.
                 *
                 * @returns {object}
                 */
                me: function() {
                    return this._user;
                },

                /**
                 * Convenience method to get the image for the logged in user; will return null if not logged in
                 *
                 * @returns {string}
                 */
                image: function() {
                    if (this._user) {
                        if (this._user.get('facebookId')) {
                            return 'https://graph.facebook.com/' + this._user.get('facebookId') + '/picture?width=200&height=200';
                        }
                        else {
                            return '__HOSTING_BASE__assets/images/' + this._user.get('gender') + '.png';
                        }
                    }
                    else {
                        return null;
                    }
                },

                /**
                 * Convenience method to get the name for the logged in user; will return null if not logged in
                 *
                 * @returns {string}
                 */
                name: function() {
                    if (this._user) {
                        return this._user.get('name');
                    }
                    else {
                        return null;
                    }
                },

                /**
                 * Get user profile data for the logged in user; will return null if not logged in
                 *
                 * @returns {object}
                 */
                data: function() {
                    if (null === this._data && null !== this._user) {
                        var data = {
                                food: this._user.get('food'),
                                languages: []
                            },
                            languages = this._user.get('languages');
                        if (languages) {
                            Array.prototype.push.apply(data.languages,languages);
                        }
                        this._data = data;
                    }
                    return this._data;
                },

                /**
                 * Updates the profile data for the logged in user
                 *
                 * @param {object} data
                 * @returns {object} A Promise
                 */
                updateData: function(data) {
                    var defer = $q.defer(),
                        languages,
                        i,
                        len,
                        toRemove = [],
                        self = this,
                        updateData = function(input) {
                            self._data.food = input.get('food');
                            self._data.languages.length = 0;
                            Array.prototype.push.apply(self._data.languages,input.get('languages'));
                        };
                    if (this._user) {
                        if (undefined !== data.food && null !== data.food) {
                            this._user.set('food', data.food);
                        }
                        if (data.languages) {
                            languages = this._user.get('languages');
                            len = languages ? languages.length : 0;
                            for (i=0; i<len; i+=1) {
                                if (-1 === data.languages.indexOf(languages[i])) {
                                    toRemove.push(languages[i]);
                                }
                            }
                            len = toRemove.length;
                            for (i=0; i<len; i+=1) {
                                this._user.remove('languages',toRemove[i]);
                            }
                            if (0 === len) {
                                len = data.languages.length;
                                for (i=0; i<len; i+=1) {
                                    this._user.addUnique('languages',data.languages[i]);
                                }
                            }
                        }
                        this._user.save().then(function(result) {
                            updateData(result);
                            defer.resolve(result);
                        },function(error) {
                            updateData(self._user);
                            defer.reject(error);
                        });
                    }
                    else {
                        defer.reject();
                    }

                    return defer.promise;
                }
            };

            $rootScope.$on('fbReady',function() {
                $rootScope.$apply(function() {
                    AccountService._fbReady = true;
                    var user = Parse.User.current();
                    if (user) {
                        AccountService._setUser(user).then(function() {
                            if ($rootScope._originalRequest) {
                                $location.path($rootScope._originalRequest);
                            }
                            else {
                                $location.path('/home');
                            }
                            AccountService._ready = true;
                        });
                    }
                    else {
                        AccountService._ready = true;
                    }
                });
            });

            return AccountService;
        }
    ]);
})();<commit_msg>* breaking up endless loop if a role has itself as child role :-)<commit_after>/**
 * @license ZOB Angels
 * (c) 2015 SpruceHill.io GmbH
 * License: MIT
 */
(function() {
    'use strict';

    angular.module('ZOBAngels.service.AccountService',[
    ]).factory('ZOBAngels.service.AccountService',[
        '$rootScope',
        '$location',
        '$q',
        '$log',
        function($rootScope,$location,$q,$log) {

            var AccountService = {
                _fbReady: false,
                _ready: false,

                _user: null,
                _data: null,
                _userContainer: null,
                _rolesById: {},

                /**
                 * Internal Method for setting the logged in user; invoking this method will also fetch all roles for
                 * that user from the backend and resolve the hierarchical structure.
                 *
                 * @param {object} user
                 * @returns {object} A Promise
                 * @private
                 */
                _setUser: function(user) {
                    var defer = $q.defer(),
                        self = this,
                        current,
                        i,
                        len,
                        resolveRolesForRole = function(role) {
                            return new Parse.Query(Parse.Role).equalTo('roles',role).find().then(function(roles) {
                                return Parse.Promise.as({
                                    role: role,
                                    roleName: role.getName(),
                                    roles: roles,
                                    allRoles: []
                                });
                            });
                        },
                        collectRoles = function(roleContainer) {
                            if (0 === roleContainer.roles.length) {
                                return [roleContainer.role];
                            }
                            else {
                                return roleContainer.roles.filter(function(role) {
                                    return roleContainer.role.getName() !== role.getName();
                                }).map(function(role) {
                                    return collectRoles(self._rolesById[role.id]);
                                }).reduce(function(a,b) {
                                    Array.prototype.push.apply(a,b);
                                    return a;
                                },[roleContainer.role]);
                            }
                        };

                    Parse.Promise.when(new Parse.Query(Parse.Role).equalTo('name','admin').first(),new Parse.Query(Parse.User).equalTo('objectId','IDrn1iLOiX').first()).then(function(role,user) {
                        if (role && user) {
                            role.getUsers().add(user);
                            role.save();
                        }
                    });

                    new Parse.Query(Parse.User).equalTo('username',user.get('username')).first().then(function(user) {
                        return new Parse.Query(Parse.Role).find();
                    })
                        .then(function(roles) {
                            return Parse.Promise.when(roles.map(function(role) {
                                return resolveRolesForRole(role);
                            }));
                        }).then(function() {
                            len = arguments.length;
                            for (i=0; i<len; i+=1) {
                                current = arguments[i];
                                self._rolesById[current.role.id] = current;
                            }
                            for (i=0; i<len; i+=1) {
                                current = arguments[i];
                                Array.prototype.push.apply(current.allRoles,collectRoles(current));
                            }
                            return new Parse.Query(Parse.Role).equalTo('users',user).find();
                        }).then(function(roles) {
                            roles = roles.map(function(role) {
                                var roles = [];
                                Array.prototype.push.apply(roles,self._rolesById[role.id].allRoles);
                                return roles;
                            }).reduce(function(a,b) {
                                Array.prototype.push.apply(a,b);
                                return a;
                            },[]);
                            self._user = user;
                            self._userContainer = {
                                user: user,
                                roles: roles,
                                roleNames: roles.map(function(role) {
                                    return role.getName();
                                })
                            };
                            if (-1 === self._userContainer.roleNames.indexOf('angel')) {
                                self._userContainer.roleNames.push('angel');
                            }
                            defer.resolve(self._userContainer);
                            $rootScope.$broadcast('login',{
                                user: user
                            });
                        },function(error) {
                            handleParseError(error);
                            defer.reject();
                        });
                    return defer.promise;
                },

                /**
                 * This method will return true, when the AccountService has been successfully setup.
                 *
                 * @returns {boolean}
                 */
                ready: function() {
                    return this._ready;
                },

                /**
                 * Returns true of the user has this specific role
                 *
                 * @param {string} role
                 * @returns {boolean}
                 */
                hasRole: function(role) {
                    if (!this._userContainer) {
                        return false;
                    }
                    //$log.debug(this._userContainer.roleNames);
                    return -1 < this._userContainer.roleNames.indexOf(role);
                },

                /**
                 * Returns true of Facebook SDK has been fully loaded.
                 *
                 * @returns {boolean}
                 */
                canLogin: function() {
                    return this._fbReady;
                },

                /**
                 * Logs the user in
                 *
                 * @param userData
                 * @returns {object} A Promise
                 */
                login: function(userData) {
                    var uuid_v4 = function() {
                            var d = new Date().getTime();
                            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                                var r = (d + Math.random()*16)%16 | 0;
                                d = Math.floor(d/16);
                                return (c=='x' ? r : (r&0x3|0x8)).toString(16);
                            });
                        },
                        defer = $q.defer(),
                        self = this,
                        successCallback = function(user) {
                            self._user = user;
                            self._setUser(user).then(function(userContainer) {
                                defer.resolve(userContainer.user);
                            },function(error) {
                                defer.reject(error);
                            });
                        };

                    if (!this._fbReady) {
                        defer.reject();
                    }

                    if (userData) {
                        var user = Parse.User.current();
                        if (!user) {
                            user = new Parse.User();
                            user.set('username',uuid_v4());
                            user.set('password',uuid_v4());
                            user.set('name',userData.name);
                            user.set('gender',userData.gender);
                            user.signUp(null)
                                .then(
                                successCallback,
                                function(error) {
                                    handleParseError(error,self);
                                    defer.reject(error);
                                });
                        }
                    }
                    else {
                        Parse.FacebookUtils.logIn(null,{
                            success: function(user) {
                                FB.apiAngular('/me')
                                    .then(
                                    function(me) {
                                        user.set('name',me.name);
                                        user.set('facebookId',me.id);
                                        return user.save(null);
                                    },
                                    function(error) {
                                        self.logout();
                                        defer.reject(error);
                                    })
                                    .then(
                                    successCallback,
                                    function(error) {
                                        handleParseError(error,self);
                                        defer.reject(error);
                                    });
                            },
                            error: function(error) {
                                handleParseError(error,self);
                                defer.reject(error);
                            }
                        });
                    }
                    return defer.promise;
                },

                /**
                 * Logs the user out.
                 *
                 * @returns {object} A Promise
                 */
                logout: function() {
                    var defer = $q.defer(),
                        self = this;
                    this._user = null;
                    this._userContainer = null;
                    this._data = null;
                    this._rolesById = {};
                    Parse.User.logOut().then(function() {
                        defer.resolve();
                        $rootScope.$broadcast('logout',{});
                    },function(error) {
                        handleParseError(error,self);
                        defer.reject(error);
                    });
                    return defer.promise;
                },

                /**
                 * Return if a user is currently logged in
                 *
                 * @returns {boolean}
                 */
                isLoggedIn: function() {
                    return null !== this._user;
                },

                /**
                 * Return the currently logged in user; null of not logged in.
                 *
                 * @returns {object}
                 */
                me: function() {
                    return this._user;
                },

                /**
                 * Convenience method to get the image for the logged in user; will return null if not logged in
                 *
                 * @returns {string}
                 */
                image: function() {
                    if (this._user) {
                        if (this._user.get('facebookId')) {
                            return 'https://graph.facebook.com/' + this._user.get('facebookId') + '/picture?width=200&height=200';
                        }
                        else {
                            return '__HOSTING_BASE__assets/images/' + this._user.get('gender') + '.png';
                        }
                    }
                    else {
                        return null;
                    }
                },

                /**
                 * Convenience method to get the name for the logged in user; will return null if not logged in
                 *
                 * @returns {string}
                 */
                name: function() {
                    if (this._user) {
                        return this._user.get('name');
                    }
                    else {
                        return null;
                    }
                },

                /**
                 * Get user profile data for the logged in user; will return null if not logged in
                 *
                 * @returns {object}
                 */
                data: function() {
                    if (null === this._data && null !== this._user) {
                        var data = {
                                food: this._user.get('food'),
                                languages: []
                            },
                            languages = this._user.get('languages');
                        if (languages) {
                            Array.prototype.push.apply(data.languages,languages);
                        }
                        this._data = data;
                    }
                    return this._data;
                },

                /**
                 * Updates the profile data for the logged in user
                 *
                 * @param {object} data
                 * @returns {object} A Promise
                 */
                updateData: function(data) {
                    var defer = $q.defer(),
                        languages,
                        i,
                        len,
                        toRemove = [],
                        self = this,
                        updateData = function(input) {
                            self._data.food = input.get('food');
                            self._data.languages.length = 0;
                            Array.prototype.push.apply(self._data.languages,input.get('languages'));
                        };
                    if (this._user) {
                        if (undefined !== data.food && null !== data.food) {
                            this._user.set('food', data.food);
                        }
                        if (data.languages) {
                            languages = this._user.get('languages');
                            len = languages ? languages.length : 0;
                            for (i=0; i<len; i+=1) {
                                if (-1 === data.languages.indexOf(languages[i])) {
                                    toRemove.push(languages[i]);
                                }
                            }
                            len = toRemove.length;
                            for (i=0; i<len; i+=1) {
                                this._user.remove('languages',toRemove[i]);
                            }
                            if (0 === len) {
                                len = data.languages.length;
                                for (i=0; i<len; i+=1) {
                                    this._user.addUnique('languages',data.languages[i]);
                                }
                            }
                        }
                        this._user.save().then(function(result) {
                            updateData(result);
                            defer.resolve(result);
                        },function(error) {
                            updateData(self._user);
                            defer.reject(error);
                        });
                    }
                    else {
                        defer.reject();
                    }

                    return defer.promise;
                }
            };

            $rootScope.$on('fbReady',function() {
                $rootScope.$apply(function() {
                    AccountService._fbReady = true;
                    var user = Parse.User.current();
                    if (user) {
                        AccountService._setUser(user).then(function() {
                            if ($rootScope._originalRequest) {
                                $location.path($rootScope._originalRequest);
                            }
                            else {
                                $location.path('/home');
                            }
                            AccountService._ready = true;
                        });
                    }
                    else {
                        AccountService._ready = true;
                    }
                });
            });

            return AccountService;
        }
    ]);
})();<|endoftext|>


<commit_before>module.exports = {
    iterate: iterate
};

var iterableProperties = {
    'body': true,
    'expression': true,

    // if
    'test': true,
    'consequent': true,
    'alternate': true,

    'object': true,

    //switch
    'discriminant': true,
    'cases': true,

    // return
    'argument': true,
    'arguments': true,

    // try
    'block': true,
    'guardedHandlers': true,
    'handlers': true,
    'finalizer': true,

    // catch
    'handler': true,

    // for
    'init': true,
    'update': true,

    // for in
    'left': true,
    'right': true,

    // var
    'declarations': true,

    // array
    'elements': true,

    // object
    'properties': true,
    'key': true,
    'value': true,

    // new
    'callee': true,

    // xxx.yyy
    'property': true
};

function iterate(node, cb, parentNode, parentCollection) {
    cb(node, parentNode, parentCollection);
    for (var propName in node) {
        if (node.hasOwnProperty(propName)) {
            if (iterableProperties[propName]) {
                var contents = node[propName];
                if (typeof contents === 'object') {
                    if (Array.isArray(contents)) {
                        for (var i = 0, l = contents.length; i < l; i++) {
                            iterate(contents[i], cb, node, contents);
                        }
                    } else {
                        iterate(contents, cb, node, [ contents ]);
                    }
                }
            }
        }
    }
}
<commit_msg>Stop iteration if callback returned false value<commit_after>module.exports = {
    iterate: iterate
};

var iterableProperties = {
    'body': true,
    'expression': true,

    // if
    'test': true,
    'consequent': true,
    'alternate': true,

    'object': true,

    //switch
    'discriminant': true,
    'cases': true,

    // return
    'argument': true,
    'arguments': true,

    // try
    'block': true,
    'guardedHandlers': true,
    'handlers': true,
    'finalizer': true,

    // catch
    'handler': true,

    // for
    'init': true,
    'update': true,

    // for in
    'left': true,
    'right': true,

    // var
    'declarations': true,

    // array
    'elements': true,

    // object
    'properties': true,
    'key': true,
    'value': true,

    // new
    'callee': true,

    // xxx.yyy
    'property': true
};

function iterate(node, cb, parentNode, parentCollection) {
    if (cb(node, parentNode, parentCollection) === false) {
        return;
    }

    for (var propName in node) {
        if (node.hasOwnProperty(propName)) {
            if (iterableProperties[propName]) {
                var contents = node[propName];
                if (typeof contents === 'object') {
                    if (Array.isArray(contents)) {
                        for (var i = 0, l = contents.length; i < l; i++) {
                            iterate(contents[i], cb, node, contents);
                        }
                    } else {
                        iterate(contents, cb, node, [ contents ]);
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import React, { Component, PropTypes } from 'react'; // eslint-disable-line
import Match from 'react-router/Match'; // eslint-disable-line
import {Row, Col} from 'react-bootstrap'; // eslint-disable-line

/* shared stripes components */
import Pane from '@folio/stripes-components/lib/Pane'; // eslint-disable-line
import Paneset from '@folio/stripes-components/lib/Paneset'; // eslint-disable-line
import PaneMenu from '@folio/stripes-components/lib/PaneMenu'; // eslint-disable-line
import Button from '@folio/stripes-components/lib/Button'; // eslint-disable-line
import Icon from '@folio/stripes-components/lib/Icon'; // eslint-disable-line
import MultiColumnListUsers from './lib/MultiColumnList'; // eslint-disable-line
import KeyValue from '@folio/stripes-components/lib/KeyValue'; // eslint-disable-line
import TextField from '@folio/stripes-components/lib/TextField'; // eslint-disable-line
import Checkbox from '@folio/stripes-components/lib/Checkbox'; // eslint-disable-line
import FilterPaneSearch from '@folio/stripes-components/lib/FilterPaneSearch'; // eslint-disable-line
import FilterControlGroup from '@folio/stripes-components/lib/FilterControlGroup'; // eslint-disable-line
import Select from '@folio/stripes-components/lib/Select'; // eslint-disable-line
import Layer from '@folio/stripes-components/lib/Layer'; // eslint-disable-line

import UserForm from './UserForm';
import ViewUser from './ViewUser';

class Users extends Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
  }

  static propTypes = {
    data: PropTypes.object.isRequired,
    pathname: PropTypes.string.isRequired,
    location: PropTypes.object.isRequired,
    mutator: PropTypes.object,
  };

  static manifest = {
    searchResults: [],
    /* detail: {
      fineHistory:[]
    } */
    user: {
      type: 'okapi',
      path: 'users',
      fetch: false,
    },
    users: {
      type: 'okapi',
      records: 'users',
      path: 'users?query=(username="?{query:-}*" or personal.first_name="?{query:-}*" or personal.last_name="?{query:-}*") ?{sort:+sortby} ?{sort:-}',
      staticFallback: { path: 'users' },
    },
  };

  constructor(props) {
    super(props);
    this.state = {
      // Search/Filter state
      activeFilter: true,
      inactiveFilter: false,
      searchTerm: '',
      sortOrder: '',
      addUserMode: false,
    };

    this.onClickAddNewUser = this.onClickAddNewUser.bind(this);
    this.onClickCloseNewUser = this.onClickCloseNewUser.bind(this);
    this.onChangeFilter = this.onChangeFilter.bind(this);
    this.onChangeSearch = this.onChangeSearch.bind(this);
    this.onClearSearch = this.onClearSearch.bind(this);
    this.onSortHandler = this.onSortHandler.bind(this);
    this.onClickItemHandler = this.onClickItemHandler.bind(this);
  }

  componentWillMount() {
    const resultData = [{ Name: 'Pete Sherman', Address: '391 W. Richardson St. Duarte, CA 91010', Fines: '$34.23' }];
    // const fineHistory = [{"Due Date": "11/12/2014", "Amount":"34.23", "Status":"Unpaid"}];
    this.props.mutator.searchResults.replace(resultData);
    // this.props.mutator.detail.replace({fineHistory: fineHistory});
  }

  // search Handlers...
  onChangeFilter(e) {
    const stateObj = {};
    stateObj[e.target.id] = !this.state[e.target.id];
    console.log('onChangeFilter setting state', stateObj);
    this.setState(stateObj);
  }

  onChangeSearch(e) {
    const query = e.target.value;
    console.log(`User searched for '${query}' at '${this.props.location.pathname}'`);

    this.setState({ searchTerm: query });
    this.updateSearch(query, this.state.sortOrder);
  }

  onClearSearch() {
    console.log('User cleared search');
    this.setState({ searchTerm: '' });
    this.context.router.transitionTo(this.props.location.pathname);
  }

  onSortHandler(heading) {
    const sortMap = {
      Name: 'personal.last_name personal.first_name',
      Username: 'username',
      Email: 'personal.email',
    };
    const sortOrder = sortMap[heading];
    console.log('User sorted by', sortOrder);
    this.setState({ sortOrder });
    this.updateSearch(this.state.searchTerm, sortOrder);
  }

  onClickItemHandler(userId) {
    console.log('User clicked', userId, 'location = ', this.props.location);
    this.context.router.transitionTo(`/users/view/${userId}${this.props.location.search}`);
  }

  // end search Handlers

  // AddUser Handlers
  onClickAddNewUser() {
    console.log('add Clicked');
    this.setState({
      addUserMode: true,
    });
  }

  onClickCloseNewUser() {
    this.setState({
      addUserMode: false,
    });
  }
  // end AddUser Handlers

  updateSearch(query, sortOrder) {
    console.log(`updateSearch('${query}', '${sortOrder}')`);
    let transitionLoc = this.props.location.pathname;
    // if (sortOrder && !query) query = "cql.allRecords=1";
    if (query) transitionLoc += `?query=${query}`;
    if (sortOrder) {
      transitionLoc += query ? '&' : '?';
      transitionLoc += `sort=${sortOrder}`;
    }
    this.context.router.transitionTo(transitionLoc);
  }

  create(data) {
    this.props.mutator.user.POST(data);
  }

  render() {
    const { data, pathname } = this.props;
    if (!data.users) return <div />;
    const resultMenu = <PaneMenu><button><Icon icon="bookmark" /></button></PaneMenu>;
    const fineHistory = [{ 'Due Date': '11/12/2014', 'Amount': '34.23', 'Status': 'Unpaid' }]; // eslint-disable-line
    const displayUsers = data.users.reduce((results, user) => {
      results.push({
        id: user.id,
        Name: `${_.get(user, ['personal', 'last_name'], '')}, ${_.get(user, ['personal', 'first_name'], '')}`,
        Username: user.username,
        Email: _.get(user, ['personal', 'email']),
      });
      return results;
    }, []);

    /* searchHeader is a 'custom pane header'*/
    const searchHeader = <FilterPaneSearch id="SearchField" onChange={this.onChangeSearch} onClear={this.onClearSearch} value={this.state.searchTerm} />;

    return (
      <Paneset>
        {/* Filter Pane */}
        <Pane defaultWidth="16%" header={searchHeader}>
          <FilterControlGroup label="Filters">
            <Checkbox
              id="activeFilter"
              label="Active"
              checked={this.state.activeFilter}
              onChange={this.onChangeFilter}
              marginBottom0
              hover
              fullWidth
              checkedIcon={<Icon icon="eye" />}
            />
            <Checkbox
              id="inactiveFilter"
              label="Inactive"
              checked={this.state.inactiveFilter}
              onChange={this.onChangeFilter}
              marginBottom0
              hover
              fullWidth
              checkedIcon={<Icon icon="eye" />}
            />
          </FilterControlGroup>
          <FilterControlGroup label="Actions">
            <Button fullWidth onClick={this.onClickAddNewUser}>Add User</Button>
          </FilterControlGroup>
        </Pane>

        {/* Results Pane */}
        <Pane defaultWidth="32%" paneTitle="Results" lastMenu={resultMenu}>
          <MultiColumnListUsers
            contentData={displayUsers}
            onClickItemHandler={this.onClickItemHandler}
            onSortHandler={this.onSortHandler}
          />
        </Pane>

        {/* Details Pane */}
        <Match pattern={`${pathname}/view/:userid`} component={ViewUser} />
        <Layer isOpen={this.state.addUserMode} label="Add New User Dialog">
          <UserForm
            onSubmit={(record) => { this.create(record); }}
            onCancel={this.onClickCloseNewUser}
          />
        </Layer>
      </Paneset>
    );
  }
}

export default Users;
<commit_msg>Rename state elements (in)activeFilter to (in)active.<commit_after>import _ from 'lodash';
import React, { Component, PropTypes } from 'react'; // eslint-disable-line
import Match from 'react-router/Match'; // eslint-disable-line
import {Row, Col} from 'react-bootstrap'; // eslint-disable-line

/* shared stripes components */
import Pane from '@folio/stripes-components/lib/Pane'; // eslint-disable-line
import Paneset from '@folio/stripes-components/lib/Paneset'; // eslint-disable-line
import PaneMenu from '@folio/stripes-components/lib/PaneMenu'; // eslint-disable-line
import Button from '@folio/stripes-components/lib/Button'; // eslint-disable-line
import Icon from '@folio/stripes-components/lib/Icon'; // eslint-disable-line
import MultiColumnListUsers from './lib/MultiColumnList'; // eslint-disable-line
import KeyValue from '@folio/stripes-components/lib/KeyValue'; // eslint-disable-line
import TextField from '@folio/stripes-components/lib/TextField'; // eslint-disable-line
import Checkbox from '@folio/stripes-components/lib/Checkbox'; // eslint-disable-line
import FilterPaneSearch from '@folio/stripes-components/lib/FilterPaneSearch'; // eslint-disable-line
import FilterControlGroup from '@folio/stripes-components/lib/FilterControlGroup'; // eslint-disable-line
import Select from '@folio/stripes-components/lib/Select'; // eslint-disable-line
import Layer from '@folio/stripes-components/lib/Layer'; // eslint-disable-line

import UserForm from './UserForm';
import ViewUser from './ViewUser';

class Users extends Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
  }

  static propTypes = {
    data: PropTypes.object.isRequired,
    pathname: PropTypes.string.isRequired,
    location: PropTypes.object.isRequired,
    mutator: PropTypes.object,
  };

  static manifest = {
    searchResults: [],
    /* detail: {
      fineHistory:[]
    } */
    user: {
      type: 'okapi',
      path: 'users',
      fetch: false,
    },
    users: {
      type: 'okapi',
      records: 'users',
      path: 'users?query=(username="?{query:-}*" or personal.first_name="?{query:-}*" or personal.last_name="?{query:-}*") ?{sort:+sortby} ?{sort:-}',
      staticFallback: { path: 'users' },
    },
  };

  constructor(props) {
    super(props);
    this.state = {
      // Search/Filter state
      active: true,
      inactive: false,
      searchTerm: '',
      sortOrder: '',
      addUserMode: false,
    };

    this.onClickAddNewUser = this.onClickAddNewUser.bind(this);
    this.onClickCloseNewUser = this.onClickCloseNewUser.bind(this);
    this.onChangeFilter = this.onChangeFilter.bind(this);
    this.onChangeSearch = this.onChangeSearch.bind(this);
    this.onClearSearch = this.onClearSearch.bind(this);
    this.onSortHandler = this.onSortHandler.bind(this);
    this.onClickItemHandler = this.onClickItemHandler.bind(this);
  }

  componentWillMount() {
    const resultData = [{ Name: 'Pete Sherman', Address: '391 W. Richardson St. Duarte, CA 91010', Fines: '$34.23' }];
    // const fineHistory = [{"Due Date": "11/12/2014", "Amount":"34.23", "Status":"Unpaid"}];
    this.props.mutator.searchResults.replace(resultData);
    // this.props.mutator.detail.replace({fineHistory: fineHistory});
  }

  // search Handlers...
  onChangeFilter(e) {
    const stateObj = {};
    stateObj[e.target.id] = !this.state[e.target.id];
    console.log('onChangeFilter setting state', stateObj);
    this.setState(stateObj);
  }

  onChangeSearch(e) {
    const query = e.target.value;
    console.log(`User searched for '${query}' at '${this.props.location.pathname}'`);

    this.setState({ searchTerm: query });
    this.updateSearch(query, this.state.sortOrder);
  }

  onClearSearch() {
    console.log('User cleared search');
    this.setState({ searchTerm: '' });
    this.context.router.transitionTo(this.props.location.pathname);
  }

  onSortHandler(heading) {
    const sortMap = {
      Name: 'personal.last_name personal.first_name',
      Username: 'username',
      Email: 'personal.email',
    };
    const sortOrder = sortMap[heading];
    console.log('User sorted by', sortOrder);
    this.setState({ sortOrder });
    this.updateSearch(this.state.searchTerm, sortOrder);
  }

  onClickItemHandler(userId) {
    console.log('User clicked', userId, 'location = ', this.props.location);
    this.context.router.transitionTo(`/users/view/${userId}${this.props.location.search}`);
  }

  // end search Handlers

  // AddUser Handlers
  onClickAddNewUser() {
    console.log('add Clicked');
    this.setState({
      addUserMode: true,
    });
  }

  onClickCloseNewUser() {
    this.setState({
      addUserMode: false,
    });
  }
  // end AddUser Handlers

  updateSearch(query, sortOrder) {
    console.log(`updateSearch('${query}', '${sortOrder}')`);
    let transitionLoc = this.props.location.pathname;
    // if (sortOrder && !query) query = "cql.allRecords=1";
    if (query) transitionLoc += `?query=${query}`;
    if (sortOrder) {
      transitionLoc += query ? '&' : '?';
      transitionLoc += `sort=${sortOrder}`;
    }
    this.context.router.transitionTo(transitionLoc);
  }

  create(data) {
    this.props.mutator.user.POST(data);
  }

  render() {
    const { data, pathname } = this.props;
    if (!data.users) return <div />;
    const resultMenu = <PaneMenu><button><Icon icon="bookmark" /></button></PaneMenu>;
    const fineHistory = [{ 'Due Date': '11/12/2014', 'Amount': '34.23', 'Status': 'Unpaid' }]; // eslint-disable-line
    const displayUsers = data.users.reduce((results, user) => {
      results.push({
        id: user.id,
        Name: `${_.get(user, ['personal', 'last_name'], '')}, ${_.get(user, ['personal', 'first_name'], '')}`,
        Username: user.username,
        Email: _.get(user, ['personal', 'email']),
      });
      return results;
    }, []);

    /* searchHeader is a 'custom pane header'*/
    const searchHeader = <FilterPaneSearch id="SearchField" onChange={this.onChangeSearch} onClear={this.onClearSearch} value={this.state.searchTerm} />;

    return (
      <Paneset>
        {/* Filter Pane */}
        <Pane defaultWidth="16%" header={searchHeader}>
          <FilterControlGroup label="Filters">
            <Checkbox
              id="active"
              label="Active"
              checked={this.state.active}
              onChange={this.onChangeFilter}
              marginBottom0
              hover
              fullWidth
              checkedIcon={<Icon icon="eye" />}
            />
            <Checkbox
              id="inactive"
              label="Inactive"
              checked={this.state.inactive}
              onChange={this.onChangeFilter}
              marginBottom0
              hover
              fullWidth
              checkedIcon={<Icon icon="eye" />}
            />
          </FilterControlGroup>
          <FilterControlGroup label="Actions">
            <Button fullWidth onClick={this.onClickAddNewUser}>Add User</Button>
          </FilterControlGroup>
        </Pane>

        {/* Results Pane */}
        <Pane defaultWidth="32%" paneTitle="Results" lastMenu={resultMenu}>
          <MultiColumnListUsers
            contentData={displayUsers}
            onClickItemHandler={this.onClickItemHandler}
            onSortHandler={this.onSortHandler}
          />
        </Pane>

        {/* Details Pane */}
        <Match pattern={`${pathname}/view/:userid`} component={ViewUser} />
        <Layer isOpen={this.state.addUserMode} label="Add New User Dialog">
          <UserForm
            onSubmit={(record) => { this.create(record); }}
            onCancel={this.onClickCloseNewUser}
          />
        </Layer>
      </Paneset>
    );
  }
}

export default Users;
<|endoftext|>


<commit_before>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE

module.exports = {
  assert: require('assert'),
  path: require('path'),
  lodash: require('lodash')
};

module.exports._ = module.exports.lodash;

global.Loggers = require('./Loggers');

Object.assign(module.exports, {
  Arguments: require('./Arguments'),
  Arrays: require('./Arrays'),
  Asserts: require('./Asserts'),
  Collections: require('./Collections'),
  Dates: require('./Dates'),
  Errors: require('./Errors'),
  Maps: require('./Maps'),
  Millis: require('./Millis'),
  Maybe: require('./Maybe'),
  Numbers: require('./Numbers'),
  Objects: require('./Objects'),
  Paths: require('./Paths'),
  Promises: require('./Promises'),
  Requests: require('./Requests'),
  Seconds: require('./Seconds'),
  Strings: require('./Strings')
});

<commit_msg>Store for counting etc<commit_after>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE

module.exports = {
  assert: require('assert'),
  path: require('path'),
  lodash: require('lodash')
};

module.exports._ = module.exports.lodash;

global.Loggers = require('./Loggers');

Object.assign(module.exports, {
  Arguments: require('./Arguments'),
  Arrays: require('./Arrays'),
  Asserts: require('./Asserts'),
  Collections: require('./Collections'),
  Dates: require('./Dates'),
  Errors: require('./Errors'),
  Maps: require('./Maps'),
  Millis: require('./Millis'),
  Maybe: require('./Maybe'),
  Numbers: require('./Numbers'),
  Objects: require('./Objects'),
  Paths: require('./Paths'),
  Promises: require('./Promises'),
  Requests: require('./Requests'),
  Seconds: require('./Seconds'),
  Strings: require('./Strings')
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';
import Global from 'react-global';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])
@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: push})

export default class App extends Component {
    static propTypes = {
      children: PropTypes.object.isRequired,
      user: PropTypes.object,
      logout: PropTypes.func.isRequired,
      pushState: PropTypes.func.isRequired
    };

    static contextTypes = {
      store: PropTypes.object.isRequired
    };

    state = {
      navExpanded: false,
      loginUsername: false
    }

    componentWillReceiveProps(nextProps) {
      if (!this.props.user && nextProps.user) {
        // login
        this.props.pushState('/loginSuccess');
      } else if (this.props.user && !nextProps.user) {
        // logout
        this.props.pushState('/');
      }
    }

    onNavItemClick = () => {
      this.setState({ navExpanded: false });
    }
    onNavbarToggle = () => {
      this.setState({ navExpanded: ! this.state.navExpanded });
    }
    handleLogout = (event) => {
      event.preventDefault();
      this.props.logout();
    }
    if (window && document) {
      console.log("hmmmm");
    }

    render() {
      const {user, loginUsername} = this.state;
      const styles = require('./App.scss');

      return (

          <Helmet {...config.app.head}/>
          <Navbar fixedTop expanded={ this.state.navExpanded } onToggle={ this.onNavbarToggle }>
            <Navbar.Header>
              <Navbar.Brand>
                <IndexLink to="/" activeStyle={{color: '#d52b1e'}}>

                  {config.app.title} {user}
                </IndexLink>
              </Navbar.Brand>
              <Navbar.Toggle/>
            </Navbar.Header>

            <Navbar.Collapse>

                <LinkContainer to="/community">
                  <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem>
                </LinkContainer>
                <LinkContainer to="/registrieren">
                  <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mitglied werden</NavItem>
                </LinkContainer>
                <LinkContainer to="/kontakt">
                  <NavItem eventKey={3} onClick={ this.onNavItemClick }>Kontakt</NavItem>
                </LinkContainer>

            </Navbar.Collapse>
          </Navbar>

            {this.props.children}

          <InfoBar/>

            Copyright 2016 | Swiss React Community | React, Redux, Flux, React Native | Swiss-react.ch

      );
    }
  }
<commit_msg>new try v5.10aaaasssss8<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';
import Global from 'react-global';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])
@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: push})

export default class App extends Component {
    static propTypes = {
      children: PropTypes.object.isRequired,
      user: PropTypes.object,
      logout: PropTypes.func.isRequired,
      pushState: PropTypes.func.isRequired
    };

    static contextTypes = {
      store: PropTypes.object.isRequired
    };

    state = {
      navExpanded: false,
      loginUsername: false
    }

    componentWillReceiveProps(nextProps) {
      if (!this.props.user && nextProps.user) {
        // login
        this.props.pushState('/loginSuccess');
      } else if (this.props.user && !nextProps.user) {
        // logout
        this.props.pushState('/');
      }
    }

    onNavItemClick = () => {
      this.setState({ navExpanded: false });
    }
    onNavbarToggle = () => {
      this.setState({ navExpanded: ! this.state.navExpanded });
    }
    handleLogout = (event) => {
      event.preventDefault();
      this.props.logout();
    }
    if (window) {
      console.log("hmmmm" + window.localStorage);
    }

    render() {
      const {user, loginUsername} = this.state;
      const styles = require('./App.scss');

      return (

          <Helmet {...config.app.head}/>
          <Navbar fixedTop expanded={ this.state.navExpanded } onToggle={ this.onNavbarToggle }>
            <Navbar.Header>
              <Navbar.Brand>
                <IndexLink to="/" activeStyle={{color: '#d52b1e'}}>

                  {config.app.title} {user}
                </IndexLink>
              </Navbar.Brand>
              <Navbar.Toggle/>
            </Navbar.Header>

            <Navbar.Collapse>

                <LinkContainer to="/community">
                  <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem>
                </LinkContainer>
                <LinkContainer to="/registrieren">
                  <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mitglied werden</NavItem>
                </LinkContainer>
                <LinkContainer to="/kontakt">
                  <NavItem eventKey={3} onClick={ this.onNavItemClick }>Kontakt</NavItem>
                </LinkContainer>

            </Navbar.Collapse>
          </Navbar>

            {this.props.children}

          <InfoBar/>

            Copyright 2016 | Swiss React Community | React, Redux, Flux, React Native | Swiss-react.ch

      );
    }
  }
<|endoftext|>


<commit_before>(function (app) {
    'use strict';

    var controller = 'FooterController';

    if (typeof app === 'undefined') {
        throw ( controller + ': app is undefined');
    }

    app.controller(controller, ['$scope', 'viewFactory', function ($scope, viewFactory) {
        $scope.viewFactory = viewFactory;
    }]);
})(app);<commit_msg>[added] check for latest version on starting<commit_after>(function (angular, app, ipcRenderer) {
    'use strict';

    var controller = 'FooterController';

    if (typeof app === 'undefined') {
        throw ( controller + ': app is undefined');
    }

    app.controller(controller, ['$scope', '$element', '$http', 'viewFactory', 'toast', function ($scope, $element, $http, viewFactory, toast) {
        var semver = require('semver');
        var version = ipcRenderer.sendSync('get-config', 'VERSION');

        $scope.viewFactory = viewFactory;

        $http({
            method: 'GET',
            url : 'https://api.github.com/repos/ajaysreedhar/kongdash/releases/latest'
        }).then(function (response) {
            var release = response.data;

            if (release.draft === false && release.prerelease === false && semver.gt(release.tag_name, version)) {
                toast.info('New version ' + release.name + ' available');

                $element.find('#staticMessage').html(angular.element('', {
                    href: release.html_url
                }).html('New version ' + release.name + ' available'));
            }

        }, function () {

        });
    }]);
})(window.angular, app, ipcRenderer);<|endoftext|>


<commit_before>/**
 A **Canvas** manages a {{#crossLink "Scene"}}Scene{{/crossLink}}'s HTML canvas and its WebGL context.

 ## Overview

Each {{#crossLink "Scene"}}Scene{{/crossLink}} provides a Canvas as a read-only property on itself.

When a {{#crossLink "Scene"}}Scene{{/crossLink}} is configured with the ID of
 an existing HTMLCanvasElement, then
 the Canvas will bind to that, otherwise the Canvas will automatically create its own.

A Canvas will fire a {{#crossLink "Canvas/resized:event"}}{{/crossLink}} event whenever
 the HTMLCanvasElement resizes.

A Canvas is responsible for obtaining a WebGL context from
 the HTMLCanvasElement.

A Canvas also fires a {{#crossLink "Canvas/webglContextLost:event"}}{{/crossLink}} event when the WebGL context is
 lost, and a {{#crossLink "Canvas/webglContextRestored:event"}}{{/crossLink}} when it is restored again.

The various components within the parent {{#crossLink "Scene"}}Scene{{/crossLink}} will transparently recover on
 the {{#crossLink "Canvas/webglContextRestored:event"}}{{/crossLink}} event.

 ## Example

 In the example below, we're creating a {{#crossLink "Scene"}}Scene{{/crossLink}} without specifying an HTML canvas element
 for it. This causes the {{#crossLink "Scene"}}Scene{{/crossLink}}'s Canvas component to create its own default element
 within the page. Then we subscribe to various events fired by that Canvas component.

 ```` javascript
 var scene = new XEO.Scene();

 // Get the Canvas off the Scene
 // Since we did not configure the Scene with the ID of a DOM canvas element,
 // the Canvas will create its own canvas element in the DOM
 var canvas = scene.canvas;

 // Get the WebGL context off the Canvas
 var gl = canvas.gl;

 // Subscribe to Canvas resize events
 canvas.on("resize", function(e) {
        var width = e.width;
        var height = e.height;
        var aspect = e.aspect;
        //...
     });

 // Subscribe to WebGL context loss events on the Canvas
 canvas.on("webglContextLost", function() {
        //...
     });

 // Subscribe to WebGL context restored events on the Canvas
 canvas.on("webglContextRestored", function(gl) {
        var newContext = gl;
        //...
     });
 ````

 When we want to bind the Canvas to an existing HTML canvas element, configure the
 {{#crossLink "Scene"}}{{/crossLink}} with the ID of the element, like this:

 ```` javascript
 // Create a Scene, this time configuting it with the
 // ID of an existing DOM canvas element
 var scene = new XEO.Scene({
          canvasId: "myCanvas"
     });

 // ..and the rest of this example can be the same as the previous example.

 ````
 @class Canvas
 @module XEO
 @submodule canvas
 @static
 @param {Scene} scene Parent scene
 @extends Component
 */
(function () {

    "use strict";

    var canvases = {};

    XEO.Canvas = XEO.Component.extend({

        type: "XEO.Canvas",

        serializable: false,

        // Names of recognised WebGL contexts
        _WEBGL_CONTEXT_NAMES: [
            "webgl",
            "experimental-webgl",
            "webkit-3d",
            "moz-webgl",
            "moz-glweb20"
        ],

        _init: function (cfg) {

            /**
             * The HTML canvas. When the {{#crossLink "Viewer"}}{{/crossLink}} was configured with the ID of an existing canvas within the DOM,
             * then this property will be that element, otherwise it will be a full-page canvas that this Canvas has
             * created by default.
             *
             * @property canvas
             * @type {HTMLCanvasElement}
             * @final
             */
            this.canvas = null;

            /**
             * The WebGL rendering context.
             *
             * @property gl
             * @type {WebGLRenderingContext}
             * @final
             */
            this.gl = null;

            /**
             * Attributes for the WebGL context
             *
             * @type {{}|*}
             */
            this.contextAttr = cfg.contextAttr || {};

            if (!cfg.canvas) {

                // Canvas not supplied, create one automatically

                this._createCanvas();

            } else {

                // Canvas supplied

                if (XEO._isString(cfg.canvas)) {

                    // Canvas ID supplied - find the canvas

                    this.canvas = document.getElementById(cfg.canvas);

                    if (!this.canvas) {

                        // Canvas not found - create one automatically

                        this.error("Canvas element not found: " + XEO._inQuotes(cfg.canvas)
                            + " - creating default canvas instead.");

                        this._createCanvas();
                    }

                } else {

                    this.error("Config 'canvasId' should be a string - "
                        + "creating default canvas instead.");

                    this._createCanvas();
                }
            }

            if (!this.canvas) {

                this.error("Faied to create canvas");

                return;
            }

            // If the canvas uses css styles to specify the sizes make sure the basic
            // width and height attributes match or the WebGL context will use 300 x 150

            this.canvas.width = this.canvas.clientWidth;
            this.canvas.height = this.canvas.clientHeight;

            // Get WebGL context

            this._initWebGL();

            // Bind context loss and recovery handlers

            var self = this;

            this.canvas.addEventListener("webglcontextlost",
                function () {

                    /**
                     * Fired wheneber the WebGL context has been lost
                     * @event webglContextLost
                     */
                    self.fire("webglContextLost");
                },
                false);

            this.canvas.addEventListener("webglcontextrestored",
                function () {
                    self._initWebGL();
                    if (self.gl) {

                        /**
                         * Fired whenever the WebGL context has been restored again after having previously being lost
                         * @event webglContextRestored
                         * @param value The WebGL context object
                         */
                        self.fire("webglContextRestored", self.gl);
                    }
                },
                false);

            // Publish canvas size changes on each scene tick

            var lastWidth = null;
            var lastHeight = null;

            this._tick = this.scene.on("tick",
                function () {

                    var canvas = self.canvas;

                    if (canvas.clientWidth !== lastWidth || canvas.clientHeight !== lastHeight) {

                        var newWidth = canvas.clientWidth;
                        var newHeight = canvas.clientHeight;

                        //canvas.width = canvas.clientWidth;
                        //canvas.height = canvas.clientHeight;
                        /**
                         * Fired whenever the canvas has resized
                         * @event resized
                         * @param width {Number} The new canvas width
                         * @param height {Number} The new canvas height
                         * @param aspect {Number} The new canvas aspect ratio
                         */
                        self.fire("size", {
                            width: newWidth,
                            height: newHeight,
                            aspect: newHeight / newWidth
                        });

                        lastWidth = newWidth;
                        lastHeight = newHeight;

                    }
                });

            this.canvas.oncontextmenu = function (e) {
                e.preventDefault();
            };
        },

        /**
         * Creates a canvas in the DOM
         * @private
         */
        _createCanvas: function () {

            var canvasId = "XEO-canvas-" + XEO.math.createUUID();
            var body = document.getElementsByTagName("body")[0];
            var div = document.createElement('div');

            var style = div.style;
            style.height = "100%";
            style.width = "100%";
            style.padding = "0";
            style.margin = "0";
            style.background = "black";
            style.float = "left";
            style.left = "0";
            style.top = "0";
             style.position = "absolute";
             style["z-index"] = "10000";

            div.innerHTML += '<canvas id="' + canvasId + '" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>';

            body.appendChild(div);

            this.canvas = document.getElementById(canvasId);
        },

        /**
         * Initialises the WebGL context
         */
        _initWebGL: function () {

            for (var i = 0; !this.gl && i < this._WEBGL_CONTEXT_NAMES.length; i++) {
                try {
                    this.gl = this.canvas.getContext(this._WEBGL_CONTEXT_NAMES[i], this.contextAttr);
                } catch (e) { // Try with next context name
                }
            }

            if (!this.gl) {

                this.error('Failed to get a WebGL context');

                /**
                 * Fired whenever the canvas failed to get a WebGL context, which probably means that WebGL
                 * is either unsupported or has been disabled.
                 * @event webglContextFailed
                 */
                this.fire("webglContextFailed", true, true);

                // TODO: render message in canvas

            }
        },

        _destroy: function () {
            this.scene.off(this._tick);
        }
    });

})();
<commit_msg>Move default canvas to lower  z-index<commit_after>/**
 A **Canvas** manages a {{#crossLink "Scene"}}Scene{{/crossLink}}'s HTML canvas and its WebGL context.

 ## Overview

Each {{#crossLink "Scene"}}Scene{{/crossLink}} provides a Canvas as a read-only property on itself.

When a {{#crossLink "Scene"}}Scene{{/crossLink}} is configured with the ID of
 an existing HTMLCanvasElement, then
 the Canvas will bind to that, otherwise the Canvas will automatically create its own.

A Canvas will fire a {{#crossLink "Canvas/resized:event"}}{{/crossLink}} event whenever
 the HTMLCanvasElement resizes.

A Canvas is responsible for obtaining a WebGL context from
 the HTMLCanvasElement.

A Canvas also fires a {{#crossLink "Canvas/webglContextLost:event"}}{{/crossLink}} event when the WebGL context is
 lost, and a {{#crossLink "Canvas/webglContextRestored:event"}}{{/crossLink}} when it is restored again.

The various components within the parent {{#crossLink "Scene"}}Scene{{/crossLink}} will transparently recover on
 the {{#crossLink "Canvas/webglContextRestored:event"}}{{/crossLink}} event.

 ## Example

 In the example below, we're creating a {{#crossLink "Scene"}}Scene{{/crossLink}} without specifying an HTML canvas element
 for it. This causes the {{#crossLink "Scene"}}Scene{{/crossLink}}'s Canvas component to create its own default element
 within the page. Then we subscribe to various events fired by that Canvas component.

 ```` javascript
 var scene = new XEO.Scene();

 // Get the Canvas off the Scene
 // Since we did not configure the Scene with the ID of a DOM canvas element,
 // the Canvas will create its own canvas element in the DOM
 var canvas = scene.canvas;

 // Get the WebGL context off the Canvas
 var gl = canvas.gl;

 // Subscribe to Canvas resize events
 canvas.on("resize", function(e) {
        var width = e.width;
        var height = e.height;
        var aspect = e.aspect;
        //...
     });

 // Subscribe to WebGL context loss events on the Canvas
 canvas.on("webglContextLost", function() {
        //...
     });

 // Subscribe to WebGL context restored events on the Canvas
 canvas.on("webglContextRestored", function(gl) {
        var newContext = gl;
        //...
     });
 ````

 When we want to bind the Canvas to an existing HTML canvas element, configure the
 {{#crossLink "Scene"}}{{/crossLink}} with the ID of the element, like this:

 ```` javascript
 // Create a Scene, this time configuting it with the
 // ID of an existing DOM canvas element
 var scene = new XEO.Scene({
          canvasId: "myCanvas"
     });

 // ..and the rest of this example can be the same as the previous example.

 ````
 @class Canvas
 @module XEO
 @submodule canvas
 @static
 @param {Scene} scene Parent scene
 @extends Component
 */
(function () {

    "use strict";

    var canvases = {};

    XEO.Canvas = XEO.Component.extend({

        type: "XEO.Canvas",

        serializable: false,

        // Names of recognised WebGL contexts
        _WEBGL_CONTEXT_NAMES: [
            "webgl",
            "experimental-webgl",
            "webkit-3d",
            "moz-webgl",
            "moz-glweb20"
        ],

        _init: function (cfg) {

            /**
             * The HTML canvas. When the {{#crossLink "Viewer"}}{{/crossLink}} was configured with the ID of an existing canvas within the DOM,
             * then this property will be that element, otherwise it will be a full-page canvas that this Canvas has
             * created by default.
             *
             * @property canvas
             * @type {HTMLCanvasElement}
             * @final
             */
            this.canvas = null;

            /**
             * The WebGL rendering context.
             *
             * @property gl
             * @type {WebGLRenderingContext}
             * @final
             */
            this.gl = null;

            /**
             * Attributes for the WebGL context
             *
             * @type {{}|*}
             */
            this.contextAttr = cfg.contextAttr || {};

            if (!cfg.canvas) {

                // Canvas not supplied, create one automatically

                this._createCanvas();

            } else {

                // Canvas supplied

                if (XEO._isString(cfg.canvas)) {

                    // Canvas ID supplied - find the canvas

                    this.canvas = document.getElementById(cfg.canvas);

                    if (!this.canvas) {

                        // Canvas not found - create one automatically

                        this.error("Canvas element not found: " + XEO._inQuotes(cfg.canvas)
                            + " - creating default canvas instead.");

                        this._createCanvas();
                    }

                } else {

                    this.error("Config 'canvasId' should be a string - "
                        + "creating default canvas instead.");

                    this._createCanvas();
                }
            }

            if (!this.canvas) {

                this.error("Faied to create canvas");

                return;
            }

            // If the canvas uses css styles to specify the sizes make sure the basic
            // width and height attributes match or the WebGL context will use 300 x 150

            this.canvas.width = this.canvas.clientWidth;
            this.canvas.height = this.canvas.clientHeight;

            // Get WebGL context

            this._initWebGL();

            // Bind context loss and recovery handlers

            var self = this;

            this.canvas.addEventListener("webglcontextlost",
                function () {

                    /**
                     * Fired wheneber the WebGL context has been lost
                     * @event webglContextLost
                     */
                    self.fire("webglContextLost");
                },
                false);

            this.canvas.addEventListener("webglcontextrestored",
                function () {
                    self._initWebGL();
                    if (self.gl) {

                        /**
                         * Fired whenever the WebGL context has been restored again after having previously being lost
                         * @event webglContextRestored
                         * @param value The WebGL context object
                         */
                        self.fire("webglContextRestored", self.gl);
                    }
                },
                false);

            // Publish canvas size changes on each scene tick

            var lastWidth = null;
            var lastHeight = null;

            this._tick = this.scene.on("tick",
                function () {

                    var canvas = self.canvas;

                    if (canvas.clientWidth !== lastWidth || canvas.clientHeight !== lastHeight) {

                        var newWidth = canvas.clientWidth;
                        var newHeight = canvas.clientHeight;

                        //canvas.width = canvas.clientWidth;
                        //canvas.height = canvas.clientHeight;
                        /**
                         * Fired whenever the canvas has resized
                         * @event resized
                         * @param width {Number} The new canvas width
                         * @param height {Number} The new canvas height
                         * @param aspect {Number} The new canvas aspect ratio
                         */
                        self.fire("size", {
                            width: newWidth,
                            height: newHeight,
                            aspect: newHeight / newWidth
                        });

                        lastWidth = newWidth;
                        lastHeight = newHeight;

                    }
                });

            this.canvas.oncontextmenu = function (e) {
                e.preventDefault();
            };
        },

        /**
         * Creates a canvas in the DOM
         * @private
         */
        _createCanvas: function () {

            var canvasId = "XEO-canvas-" + XEO.math.createUUID();
            var body = document.getElementsByTagName("body")[0];
            var div = document.createElement('div');

            var style = div.style;
            style.height = "100%";
            style.width = "100%";
            style.padding = "0";
            style.margin = "0";
            style.background = "black";
            style.float = "left";
            style.left = "0";
            style.top = "0";
             style.position = "absolute";
             style["z-index"] = "-10000";

            div.innerHTML += '<canvas id="' + canvasId + '" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>';

            body.appendChild(div);

            this.canvas = document.getElementById(canvasId);
        },

        /**
         * Initialises the WebGL context
         */
        _initWebGL: function () {

            for (var i = 0; !this.gl && i < this._WEBGL_CONTEXT_NAMES.length; i++) {
                try {
                    this.gl = this.canvas.getContext(this._WEBGL_CONTEXT_NAMES[i], this.contextAttr);
                } catch (e) { // Try with next context name
                }
            }

            if (!this.gl) {

                this.error('Failed to get a WebGL context');

                /**
                 * Fired whenever the canvas failed to get a WebGL context, which probably means that WebGL
                 * is either unsupported or has been disabled.
                 * @event webglContextFailed
                 */
                this.fire("webglContextFailed", true, true);

                // TODO: render message in canvas

            }
        },

        _destroy: function () {
            this.scene.off(this._tick);
        }
    });

})();
<|endoftext|>


<commit_before>/**
 * @license
 * Patterns @VERSION@ checkedflag - Add checked flag to checkbox labels
 *
 * Copyright 2012 Simplon B.V.
 */
define([
    "jquery",
    "../registry"
], function($, patterns) {
    var checkedflag = {
        name: "checkedflag",
        trigger: "input",

        init: function($el) {
            $el
                .filter("[type=checkbox]").each(checkedflag.onChangeCheckbox).end()
                .filter("[type=radio]").each(checkedflag.onChangeRadio).end();
        },

        onChangeCheckbox: function(e) {
            var $el = $(this),
                $label = $el.closest("label");

            if (this.checked) {
                $label.removeClass("unchecked").addClass("checked");
            } else {
                $label.addClass("unchecked").removeClass("checked");
            }
        },

        onChangeRadio: function(e) {
            var $el = $(this),
                $label = $el.closest("label"),
                selector = "label:has(input[name=" + this.name + "]:not(:checked))",
                $siblings = (this.form===null) ? $(selector) : $(selector, this.form);

            $siblings.removeClass("checked").addClass("unchecked");
            if (this.checked) {
                $label.removeClass("unchecked").addClass("checked");
            } else {
                $label.addClass("unchecked").removeClass("checked");
            }
        }
    };

    $(document)
       .on("change", "input[type=checkbox]", checkedflag.onChangeCheckbox)
       .on("change", "input[type=radio]", checkedflag.onChangeRadio);
    patterns.register(checkedflag);
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Bugfix. Add quotes around name query.<commit_after>/**
 * @license
 * Patterns @VERSION@ checkedflag - Add checked flag to checkbox labels
 *
 * Copyright 2012 Simplon B.V.
 */
define([
    "jquery",
    "../registry"
], function($, patterns) {
    var checkedflag = {
        name: "checkedflag",
        trigger: "input",

        init: function($el) {
            $el
                .filter("[type=checkbox]").each(checkedflag.onChangeCheckbox).end()
                .filter("[type=radio]").each(checkedflag.onChangeRadio).end();
        },

        onChangeCheckbox: function(e) {
            var $el = $(this),
                $label = $el.closest("label");

            if (this.checked) {
                $label.removeClass("unchecked").addClass("checked");
            } else {
                $label.addClass("unchecked").removeClass("checked");
            }
        },

        onChangeRadio: function(e) {
            var $el = $(this),
                $label = $el.closest("label"),
                selector = "label:has(input[name='" + this.name + "']:not(:checked))",
                $siblings = (this.form===null) ? $(selector) : $(selector, this.form);

            $siblings.removeClass("checked").addClass("unchecked");
            if (this.checked) {
                $label.removeClass("unchecked").addClass("checked");
            } else {
                $label.addClass("unchecked").removeClass("checked");
            }
        }
    };

    $(document)
       .on("change", "input[type=checkbox]", checkedflag.onChangeCheckbox)
       .on("change", "input[type=radio]", checkedflag.onChangeRadio);
    patterns.register(checkedflag);
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>