<commit_before> /*Copyright 2018-2020 Bang & Olufsen A/S
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.*/

 // BEOCREATE UI DRAG ENGINE.
 // No dependencies.

 function Beodrag(element, options, context = document) {
 	var myThis = this;
 	this.element = element;
 	this.context = context;

 	this.options = {
 		touchImmediately: false,
 		touchDelay: 300,
 		enabled: true,
 		arrange: false,
 		pre: null,
 		start: null,
 		move: null,
 		end: null,
 		cancel: null
 	};
 	this.options = Object.assign(this.options, options);
 	if (!options.pre || typeof options.pre != "function") this.options.pre = null;
 	if (!options.start || typeof options.start != "function") this.options.start = null;
 	if (!options.move || typeof options.move != "function") this.options.move = null;
 	if (!options.end || typeof options.end != "function") this.options.end = null;
 	if (!options.cancel || typeof options.cancel != "function") this.options.cancel = null;

 	var elements = null;
 	var dragEvent = null;
	var dragging = false;
	var dragStarted = false;
	var dragTimeout = null;
	var clickHandler = null;
	var touch = false;
	var positions = {
		elementX: 0, // Position of the element including offsets.
		elementY: 0,
		pageX: 0,
		pageY: 0,
		offsetX: 0, // Calculated offset (element position - drag position + margin).
		offsetY: 0,
		deltaX: 0,
		deltaY: 0,
		startX: 0,
		startY: 0
	};

 	this.onDragStart = function(event) {
 		if (this.options.enabled) {
 			elements = this.context.querySelectorAll(this.element);
	 		elementFound = false;
	 		for (element in elements) {
		 		if (elements[element] == event.target) {
		 			elementFound = true;
		 			break;
		 		}
		 	}
	 		if (elementFound) {
		 		dragEvent = event;
				dragStarted = false;
				touch = (event.targetTouches) ? true : false;
				if (!touch) {
					positions.pageX = dragEvent.pageX;
					positions.pageY = dragEvent.pageY;
					event.preventDefault();
				} else {
					positions.pageX = event.targetTouches[0].pageX;
					positions.pageY = event.targetTouches[0].pageY;
					if (this.options.touchImmediately) event.preventDefault();
				}
				positions.startX = positions.pageX;
				positions.startY = positions.pageY;
				domRect = event.target.getBoundingClientRect();
				computedStyle = window.getComputedStyle(event.target);
				positions.offsetX = positions.pageX-domRect.x+parseFloat(computedStyle.marginLeft);
				positions.offsetY = positions.pageY-domRect.y+parseFloat(computedStyle.marginTop);
				positions.elementX = positions.pageX-positions.offsetX;
				positions.elementY = positions.pageY-positions.offsetY;
				if (!this.options.touchImmediately) {
					dragTimeout = setTimeout(function() {
						dragTimeout = null;
						if (myThis.options.pre) myThis.options.pre(event, positions, dragEvent.target);
					}, this.options.touchDelay);
				} else {
					if (this.options.pre) this.options.pre(event, positions, dragEvent.target);
				}
			}
		}
 	}
 	this.onDragMove = function(event) {
 		if (dragEvent) {
			if (!dragging && !dragStarted) {
				if (!touch) {
					clearTimeout(dragTimeout);
					dragTimeout = null;
				}
				if (!dragTimeout) {
					dragStarted = true;
					if (this.options.start) this.options.start(event, positions, dragEvent.target);
					if (this.options.arrange) this.arrangeStart(event);
					dragging = true;
					if (!touch) {
						if (dragEvent.target.getAttribute('onclick')) {
							clickHandler = dragEvent.target.getAttribute('onclick');
							dragEvent.target.removeAttribute('onclick');
						}
					}
					event.preventDefault();
				} else {
					this.onDragEnd(event, true);
				}
			} else if (dragging) {
				event.preventDefault();
				if (!touch) {
					x = event.pageX;
					y = event.pageY;
				} else {
					x = event.targetTouches[0].pageX;
					y = event.targetTouches[0].pageY;
				}
				if (x != positions.pageX || y != positions.pageY) {
					positions.pageX = x;
					positions.pageY = y;
					positions.deltaX = x-positions.startX;
					positions.deltaY = y-positions.startY;
					positions.elementX = positions.pageX-positions.offsetX;
					positions.elementY = positions.pageY-positions.offsetY;
					if (this.options.move) this.options.move(event, positions, dragEvent.target);
					if (this.options.arrange) this.arrangeMove(event);
				}
			}
		}
 	}
 	this.onDragEnd = function(event, fromDrag = false) {
 		if (dragging) {
			dragging = false;
			if (this.options.arrange) {
				this.arrangeEnd(event);
			} else if (this.options.end) {
				this.options.end(event, positions, dragEvent.target);
			}
			if (clickHandler) {
				setTimeout(function() {
					dragEvent.target.setAttribute('onclick', clickHandler);
					clickHandler = null;
					dragEvent = null;
				}, 20);
			} else {
				dragEvent = null;
			}
			event.preventDefault();
		} else if (dragEvent) {
			if (this.options.cancel) this.options.cancel(event, positions, dragEvent.target);
			dragEvent = null;
			if (!fromDrag) event.preventDefault();
			clearTimeout(dragTimeout);
			dragTimeout = null;
		}
 	}
 	this.context.addEventListener("mousedown", this.onDragStart.bind(this), false);
 	this.context.addEventListener("mousemove", this.onDragMove.bind(this), false);
 	document.addEventListener("mouseup", this.onDragEnd.bind(this), false);

 	this.context.addEventListener("touchstart", this.onDragStart.bind(this), false);
 	this.context.addEventListener("touchmove", this.onDragMove.bind(this), {passive: false, capture: false});
 	this.context.addEventListener("touchend", this.onDragEnd.bind(this), false);

 	var itemPositions = [];
	var currentPosition = 0;
	var newPosition = 0;
	var itemHeight = 0;

 	this.arrangeStart = function(event) {
		itemHeight = dragEvent.target.getBoundingClientRect().height;
		itemPositions = [];
		for (var i = 0; i < elements.length; i++) {
			itemPositions.push(elements[i].getBoundingClientRect().top);
			if (elements[i] == dragEvent.target) currentPosition = i;
		}
		newPosition = currentPosition;
 	}

 	this.arrangeMove = function(event) {
 		dragEvent.target.style.transform = "translateY("+positions.deltaY+"px)";
		newY = itemPositions[currentPosition]+positions.deltaY;
		for (pos in itemPositions) {
			if (itemPositions[pos] < newY+itemHeight/2) newPos = parseFloat(pos);
		}
		if (newPos != newPosition) {
			for (pos in itemPositions) {
				if (pos != currentPosition) {
					if (newPos > currentPosition) { // Moving down.
						if (newPos >= pos && pos > currentPosition) {
							oldItemDeltaY = itemPositions[pos-1]-itemPositions[pos];
							elements[pos].style.transform = "translateY("+oldItemDeltaY+"px)";
						} else {
							elements[pos].style.transform = null;
						}
					} else if (newPos < currentPosition) { // Moving up.
						if (newPos <= pos && pos < currentPosition) {
							oldItemDeltaY = itemPositions[parseInt(pos)+1]-itemPositions[pos];
							elements[pos].style.transform = "translateY("+oldItemDeltaY+"px)";
						} else {
							elements[pos].style.transform = null;
						}
					} else {
						elements[pos].style.transform = null;
					}
				}
			}
			newPosition = newPos;
		}
 	}

 	this.arrangeEnd = function(event) {
 		if (newPosition != currentPosition) {
			newDeltaY = itemPositions[newPosition]-itemPositions[currentPosition];
			dragEvent.target.style.transform = "translateY("+newDeltaY+"px)";
			// Run end
			if (this.options.end) this.options.end(event, positions, dragEvent.target, currentPosition, newPosition);
		} else {
			dragEvent.target.style.transform = null;
			if (this.options.end) this.options.end(event, positions, dragEvent.target);
		}
 	}
 }

 Beodrag.prototype.setOptions = function(options) {
 	this.options = Object.assign(this.options, options);
 	return this.options;
 }<commit_msg>Return elements in arrange end callback<commit_after> /*Copyright 2018-2020 Bang & Olufsen A/S
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.*/

 // BEOCREATE UI DRAG ENGINE.
 // No dependencies.

 function Beodrag(element, options, context = document) {
 	var myThis = this;
 	this.element = element;
 	this.context = context;

 	this.options = {
 		touchImmediately: false,
 		touchDelay: 300,
 		enabled: true,
 		arrange: false,
 		pre: null,
 		start: null,
 		move: null,
 		end: null,
 		cancel: null
 	};
 	this.options = Object.assign(this.options, options);
 	if (!options.pre || typeof options.pre != "function") this.options.pre = null;
 	if (!options.start || typeof options.start != "function") this.options.start = null;
 	if (!options.move || typeof options.move != "function") this.options.move = null;
 	if (!options.end || typeof options.end != "function") this.options.end = null;
 	if (!options.cancel || typeof options.cancel != "function") this.options.cancel = null;

 	var elements = null;
 	var dragEvent = null;
	var dragging = false;
	var dragStarted = false;
	var dragTimeout = null;
	var clickHandler = null;
	var touch = false;
	var positions = {
		elementX: 0, // Position of the element including offsets.
		elementY: 0,
		pageX: 0,
		pageY: 0,
		offsetX: 0, // Calculated offset (element position - drag position + margin).
		offsetY: 0,
		deltaX: 0,
		deltaY: 0,
		startX: 0,
		startY: 0
	};

 	this.onDragStart = function(event) {
 		if (this.options.enabled) {
 			elements = this.context.querySelectorAll(this.element);
	 		elementFound = false;
	 		for (element in elements) {
		 		if (elements[element] == event.target) {
		 			elementFound = true;
		 			break;
		 		}
		 	}
	 		if (elementFound) {
		 		dragEvent = event;
				dragStarted = false;
				touch = (event.targetTouches) ? true : false;
				if (!touch) {
					positions.pageX = dragEvent.pageX;
					positions.pageY = dragEvent.pageY;
					event.preventDefault();
				} else {
					positions.pageX = event.targetTouches[0].pageX;
					positions.pageY = event.targetTouches[0].pageY;
					if (this.options.touchImmediately) event.preventDefault();
				}
				positions.startX = positions.pageX;
				positions.startY = positions.pageY;
				domRect = event.target.getBoundingClientRect();
				computedStyle = window.getComputedStyle(event.target);
				positions.offsetX = positions.pageX-domRect.x+parseFloat(computedStyle.marginLeft);
				positions.offsetY = positions.pageY-domRect.y+parseFloat(computedStyle.marginTop);
				positions.elementX = positions.pageX-positions.offsetX;
				positions.elementY = positions.pageY-positions.offsetY;
				if (!this.options.touchImmediately) {
					dragTimeout = setTimeout(function() {
						dragTimeout = null;
						if (myThis.options.pre) myThis.options.pre(event, positions, dragEvent.target);
					}, this.options.touchDelay);
				} else {
					if (this.options.pre) this.options.pre(event, positions, dragEvent.target);
				}
			}
		}
 	}
 	this.onDragMove = function(event) {
 		if (dragEvent) {
			if (!dragging && !dragStarted) {
				if (!touch) {
					clearTimeout(dragTimeout);
					dragTimeout = null;
				}
				if (!dragTimeout) {
					dragStarted = true;
					if (this.options.start) this.options.start(event, positions, dragEvent.target);
					if (this.options.arrange) this.arrangeStart(event);
					dragging = true;
					if (!touch) {
						if (dragEvent.target.getAttribute('onclick')) {
							clickHandler = dragEvent.target.getAttribute('onclick');
							dragEvent.target.removeAttribute('onclick');
						}
					}
					event.preventDefault();
				} else {
					this.onDragEnd(event, true);
				}
			} else if (dragging) {
				event.preventDefault();
				if (!touch) {
					x = event.pageX;
					y = event.pageY;
				} else {
					x = event.targetTouches[0].pageX;
					y = event.targetTouches[0].pageY;
				}
				if (x != positions.pageX || y != positions.pageY) {
					positions.pageX = x;
					positions.pageY = y;
					positions.deltaX = x-positions.startX;
					positions.deltaY = y-positions.startY;
					positions.elementX = positions.pageX-positions.offsetX;
					positions.elementY = positions.pageY-positions.offsetY;
					if (this.options.move) this.options.move(event, positions, dragEvent.target);
					if (this.options.arrange) this.arrangeMove(event);
				}
			}
		}
 	}
 	this.onDragEnd = function(event, fromDrag = false) {
 		if (dragging) {
			dragging = false;
			if (this.options.arrange) {
				this.arrangeEnd(event);
			} else if (this.options.end) {
				this.options.end(event, positions, dragEvent.target);
			}
			if (clickHandler) {
				setTimeout(function() {
					dragEvent.target.setAttribute('onclick', clickHandler);
					clickHandler = null;
					dragEvent = null;
				}, 20);
			} else {
				dragEvent = null;
			}
			event.preventDefault();
		} else if (dragEvent) {
			if (this.options.cancel) this.options.cancel(event, positions, dragEvent.target);
			dragEvent = null;
			if (!fromDrag) event.preventDefault();
			clearTimeout(dragTimeout);
			dragTimeout = null;
		}
 	}
 	this.context.addEventListener("mousedown", this.onDragStart.bind(this), false);
 	this.context.addEventListener("mousemove", this.onDragMove.bind(this), false);
 	document.addEventListener("mouseup", this.onDragEnd.bind(this), false);

 	this.context.addEventListener("touchstart", this.onDragStart.bind(this), false);
 	this.context.addEventListener("touchmove", this.onDragMove.bind(this), {passive: false, capture: false});
 	this.context.addEventListener("touchend", this.onDragEnd.bind(this), false);

 	var itemPositions = [];
	var currentPosition = 0;
	var newPosition = 0;
	var itemHeight = 0;

 	this.arrangeStart = function(event) {
		itemHeight = dragEvent.target.getBoundingClientRect().height;
		itemPositions = [];
		for (var i = 0; i < elements.length; i++) {
			itemPositions.push(elements[i].getBoundingClientRect().top);
			if (elements[i] == dragEvent.target) currentPosition = i;
		}
		newPosition = currentPosition;
 	}

 	this.arrangeMove = function(event) {
 		dragEvent.target.style.transform = "translateY("+positions.deltaY+"px)";
		newY = itemPositions[currentPosition]+positions.deltaY;
		for (pos in itemPositions) {
			if (itemPositions[pos] < newY+itemHeight/2) newPos = parseFloat(pos);
		}
		if (newPos != newPosition) {
			for (pos in itemPositions) {
				if (pos != currentPosition) {
					if (newPos > currentPosition) { // Moving down.
						if (newPos >= pos && pos > currentPosition) {
							oldItemDeltaY = itemPositions[pos-1]-itemPositions[pos];
							elements[pos].style.transform = "translateY("+oldItemDeltaY+"px)";
						} else {
							elements[pos].style.transform = null;
						}
					} else if (newPos < currentPosition) { // Moving up.
						if (newPos <= pos && pos < currentPosition) {
							oldItemDeltaY = itemPositions[parseInt(pos)+1]-itemPositions[pos];
							elements[pos].style.transform = "translateY("+oldItemDeltaY+"px)";
						} else {
							elements[pos].style.transform = null;
						}
					} else {
						elements[pos].style.transform = null;
					}
				}
			}
			newPosition = newPos;
		}
 	}

 	this.arrangeEnd = function(event) {
 		if (newPosition != currentPosition) {
			newDeltaY = itemPositions[newPosition]-itemPositions[currentPosition];
			dragEvent.target.style.transform = "translateY("+newDeltaY+"px)";
			// Run end
			if (this.options.end) this.options.end(event, positions, dragEvent.target, currentPosition, newPosition, elements);
		} else {
			dragEvent.target.style.transform = null;
			if (this.options.end) this.options.end(event, positions, dragEvent.target);
		}
 	}
 }

 Beodrag.prototype.setOptions = function(options) {
 	this.options = Object.assign(this.options, options);
 	return this.options;
 }<|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 { routeActions } from 'redux-simple-router';
import config from '../../config';

@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: routeActions.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
  };

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

  static reduxAsyncConnect(params, store) {
    const {dispatch, getState} = store;
    const promises = [];

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

  handleLogout = (event) => {
    event.preventDefault();
    this.props.logout();
  };

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

    return (

        <Helmet {...config.app.head}/>
        <Navbar fixedTop>
          <Navbar.Header>
            <Navbar.Brand>
              <IndexLink to="/" activeStyle={{color: '#33e0ff'}}>

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

          <Navbar.Collapse eventKey={0}>

              {user && <LinkContainer to="/chat">
                <NavItem eventKey={1}>Chat</NavItem>
              </LinkContainer>}

              <LinkContainer to="/widgets">
                <NavItem eventKey={2}>Widgets</NavItem>
              </LinkContainer>
              <LinkContainer to="/survey">
                <NavItem eventKey={3}>Survey</NavItem>
              </LinkContainer>
              <LinkContainer to="/about">
                <NavItem eventKey={4}>About Us</NavItem>
              </LinkContainer>

              {!user &&
              <LinkContainer to="/login">
                <NavItem eventKey={5}>Login</NavItem>
              </LinkContainer>}
              {user &&
              <LinkContainer to="/logout">
                <NavItem eventKey={6} className="logout-link" onClick={this.handleLogout}>
                  Logout
                </NavItem>
              </LinkContainer>}

            {user &&

Logged in as {user.name}.
}

              <NavItem eventKey={1} target="_blank" title="View on Github" href="https://github.com/erikras/react-redux-universal-hot-example">

              </NavItem>

          </Navbar.Collapse>
        </Navbar>

          {this.props.children}

        <InfoBar/>

          Have questions? Ask for help on Github or in the #react-redux-universal Discord channel.

    );
  }
}
<commit_msg>Fix duplicate re-render.<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 { routeActions } from 'redux-simple-router';
import config from '../../config';

@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: routeActions.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
  };

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

  static reduxAsyncConnect(params, store) {
    const {dispatch, getState} = store;
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }
    if (promises.length > 0) {
      return Promise.all(promises);
    }
  }

  handleLogout = (event) => {
    event.preventDefault();
    this.props.logout();
  };

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

    return (

        <Helmet {...config.app.head}/>
        <Navbar fixedTop>
          <Navbar.Header>
            <Navbar.Brand>
              <IndexLink to="/" activeStyle={{color: '#33e0ff'}}>

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

          <Navbar.Collapse eventKey={0}>

              {user && <LinkContainer to="/chat">
                <NavItem eventKey={1}>Chat</NavItem>
              </LinkContainer>}

              <LinkContainer to="/widgets">
                <NavItem eventKey={2}>Widgets</NavItem>
              </LinkContainer>
              <LinkContainer to="/survey">
                <NavItem eventKey={3}>Survey</NavItem>
              </LinkContainer>
              <LinkContainer to="/about">
                <NavItem eventKey={4}>About Us</NavItem>
              </LinkContainer>

              {!user &&
              <LinkContainer to="/login">
                <NavItem eventKey={5}>Login</NavItem>
              </LinkContainer>}
              {user &&
              <LinkContainer to="/logout">
                <NavItem eventKey={6} className="logout-link" onClick={this.handleLogout}>
                  Logout
                </NavItem>
              </LinkContainer>}

            {user &&

Logged in as {user.name}.
}

              <NavItem eventKey={1} target="_blank" title="View on Github" href="https://github.com/erikras/react-redux-universal-hot-example">

              </NavItem>

          </Navbar.Collapse>
        </Navbar>

          {this.props.children}

        <InfoBar/>

          Have questions? Ask for help on Github or in the #react-redux-universal Discord channel.

    );
  }
}
<|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';

@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();
    };

    componentWillMount() {
      setTimeout(function(){
        console.log(window.localStorage.getItem('ls_username'));
      }, 500);
    }

    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>
                {loginUsername &&
                  {loginUsername}
                }

            </Navbar.Collapse>
          </Navbar>

            {this.props.children}

          <InfoBar/>

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

      );
    }
  }
<commit_msg>new try v1<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';

@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,
      loggedIn: window.localStorage.getItem('ls_username')
    }

    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();
    }

    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() {
  "use strict";

  choona.Settings.GlobalEventBus = new choona.EventBus();

  var log = choona.Util.log;
  choona.View = choona.Base.extend({
    initialize: function(moduleConf, subModuleConf) {
      choona.Base.call(this);

      this.config = moduleConf.config;
      this._viewMetadata = {
        eventBus: choona.Settings.GlobalEventBus,
        topicList: {},
        subModuleList: {},
        id: moduleConf.id,
        eventsMap: [],
        mercykillFunc: null
      };

      if (typeof moduleConf.id !== "string" || moduleConf.id === "") {
        throw new Error("Id provided is not String or it is a blank sting");
      }

      if (subModuleConf !== undefined) {
        this._viewMetadata.mercykillFunc = subModuleConf.mercykillFunc;
        this._viewMetadata.eventBus = subModuleConf.parentEventBus;
        this.$ = subModuleConf.parentNode.querySelector("#" + moduleConf.id);
      } else {
        this.$ = document.querySelector("#" + moduleConf.id);
      }

      if (this.$ === null) {
        throw new Error("Unable to Load Module, as I am unable to find id=\"" + moduleConf.id + "\" inside Root DOM");
      }

      //setup this.$el & this.$$ if jQuery present.
      if (window.jQuery) {
        this.$el = this.$$ = window.jQuery(this.$);
      }

      //Loading Template !!
      //TODO -Support for underscore template
      var str = "";
      if (typeof this.template === "string") {
        str = this.template;
      }
      if (typeof this.template === "function") {
        str = this.template();
      }
      this.$.innerHTML = choona.Settings.postTemplateProcessing(str);

      /*
       * Please note that _startIsolatedEventBus() must be called before _subscribeGlobalEvents()
       * because, you need to get event bus for
       * */

      //Start Isolated EventBus , this will be useful for creating third party widget who do not want to create conflicts in naming
      if (this.isolatedEventBus === true) {
        this._viewMetadata.eventBus = new choona.EventBus();
      }

      //subscribeAll globalEvents();
      var self = this;

      if (this.globalEvents !== undefined) {
        choona.Util.for(this.globalEvents, function(methodName, eventName) {
          self.subscribeGlobalEvent(eventName, methodName);
        });
      }

      //subscribe all DOM events !

      if (this.events !== undefined) {
        this.on(this.events);
      }

      //Calling the global preStart function !
      if (typeof choona.Settings.preStart === "function") {
        choona.Settings.preStart.call(this);
      }
      //TODO - You can find all submodule from DOM and load subView

    },
    _getEventBus: function() {
      return this._viewMetadata.eventBus;
    },
    subscribeGlobalEvent: function(topic, methodName) {
      var self = this;
      var callback = function() {
        self[methodName].apply(self, arguments);
      };
      if (this._viewMetadata.topicList[topic] === undefined) {
        this._viewMetadata.topicList[topic] = [];
      }
      var bus = this._getEventBus();
      this._viewMetadata.topicList[topic].push(bus.subscribe(topic, callback));
      log("subscribed topic -> " + topic);
    },
    unsubscribeGlobalEvent: function(topic) {
      log("unsubscribing topic -> " + topic);
      var bus = this._getEventBus();
      if (this._viewMetadata.topicList[topic] !== undefined) {
        this._viewMetadata.topicList[topic].map(function(v, i) {
          bus.unsubscribe(v);
        });
        delete this._viewMetadata.topicList[topic];
      }
    },
    publishGlobalEvent: function(topic, val) {
      log("publishing topic ->" + arguments);
      var bus = this._getEventBus();
      bus.publish.apply(bus, arguments);
    },
    loadSubView: function(data) {
      var self = this;
      if (this._viewMetadata.subModuleList[data.id] === undefined) {
        this._viewMetadata.subModuleList[data.id] = new data.module(data, {
          parentNode: this.$,
          parentEventBus: this._getEventBus(),
          mercykillFunc: function() {
            self.removeSubView(data.id);
          }
        });
      } else {
        throw new Error("data.id::" + data.id + " is already contains a module.  Please provide separate id new module");
      }
    },
    killme: function() {
      if (typeof this._viewMetadata.mercykillFunc === "function") {
        this._viewMetadata.mercykillFunc();
      }
    },
    removeSubView: function(id) {
      if (this._viewMetadata.subModuleList[id] !== undefined) {
        this._viewMetadata.subModuleList[id]._endModule();
        delete this._viewMetadata.subModuleList[id];
      }
      //Deletion is needed because if parent get Ended, it should not try to delete the module again.
    },
    on: function(obj) {
      //We use {"eventName hash":"handler"} kind of notation !
      var self = this;
      choona.Util.for(obj, function(handler, key) {
        key = key.trim().replace(/ +/g, " ");

        var arr = key.split(" ");
        var eventName = arr.shift();
        var hash = arr.join(" ");

        var callback = function(e) {
          if (hash === "") {
            self[handler].call(self, e, e.target, e.target.dataset);
          } else {
            if (e.target.matches(hash)) {
              self[handler].call(self, e, e.target, e.target.dataset);
            }
          }
        };
        choona.Util.bindEvent(self.$, eventName, callback);
        self._viewMetadata.eventsMap[key] = {
          eventName: eventName,
          callback: callback
        };
      });
    },
    off: function(key) {
      //Unsubscribe dom event
      var v = this._viewMetadata.eventsMap[key];
      if (v !== undefined && typeof v === "object") {
        choona.Util.unbindEvent(this.$, v.eventName, v.callback);
        delete this._viewMetadata.eventsMap[key];
      }
    },
    end: function() {
      console.log("Ending base View");
    },
    _endModule: function() {

      //call postEnd();
      if (typeof choona.Settings.postEnd === "function") {
        choona.Settings.postEnd.call(this);
      }

      //endAllSubModules
      var self = this;
      choona.Util.for(this._viewMetadata.subModuleList, function(v, id) {
        self.removeSubView(id);
      });

      if (typeof this.end === "function") {
        this.end();
      }

      //unSubscribing All DOM events
      this._viewMetadata.eventsMap.map(function(v, key) {
        self.off(key);
      });

      //Remove all HTML inside this.$
      this.$.innerHTML = "";

      //unSubscribe All globalEvents
      choona.Util.for(this._viewMetadata.topicList, function(v, topic) {
        self.unsubscribeGlobalEvent(topic);
      });

      delete this.$;
      delete this.$el;
      delete this.$$;
      delete this.config;
      log("ended module -> " + this._viewMetadata.id);
      delete this._viewMetadata.id;
      delete this._viewMetadata.subModuleList;
      delete this._viewMetadata.eventBus;
      delete this._viewMetadata.topicList;
      delete this._viewMetadata.eventsMap;
      delete this._viewMetadata;
    }
  });

  choona.loadView = function(moduleConf) {
    var app = new moduleConf.module(moduleConf);
  };

})();
<commit_msg>loadView must return App<commit_after>(function() {
  "use strict";

  choona.Settings.GlobalEventBus = new choona.EventBus();

  var log = choona.Util.log;
  choona.View = choona.Base.extend({
    initialize: function(moduleConf, subModuleConf) {
      choona.Base.call(this);

      this.config = moduleConf.config;
      this._viewMetadata = {
        eventBus: choona.Settings.GlobalEventBus,
        topicList: {},
        subModuleList: {},
        id: moduleConf.id,
        eventsMap: [],
        mercykillFunc: null
      };

      if (typeof moduleConf.id !== "string" || moduleConf.id === "") {
        throw new Error("Id provided is not String or it is a blank sting");
      }

      if (subModuleConf !== undefined) {
        this._viewMetadata.mercykillFunc = subModuleConf.mercykillFunc;
        this._viewMetadata.eventBus = subModuleConf.parentEventBus;
        this.$ = subModuleConf.parentNode.querySelector("#" + moduleConf.id);
      } else {
        this.$ = document.querySelector("#" + moduleConf.id);
      }

      if (this.$ === null) {
        throw new Error("Unable to Load Module, as I am unable to find id=\"" + moduleConf.id + "\" inside Root DOM");
      }

      //setup this.$el & this.$$ if jQuery present.
      if (window.jQuery) {
        this.$el = this.$$ = window.jQuery(this.$);
      }

      //Loading Template !!
      //TODO -Support for underscore template
      var str = "";
      if (typeof this.template === "string") {
        str = this.template;
      }
      if (typeof this.template === "function") {
        str = this.template();
      }
      this.$.innerHTML = choona.Settings.postTemplateProcessing(str);

      /*
       * Please note that _startIsolatedEventBus() must be called before _subscribeGlobalEvents()
       * because, you need to get event bus for
       * */

      //Start Isolated EventBus , this will be useful for creating third party widget who do not want to create conflicts in naming
      if (this.isolatedEventBus === true) {
        this._viewMetadata.eventBus = new choona.EventBus();
      }

      //subscribeAll globalEvents();
      var self = this;

      if (this.globalEvents !== undefined) {
        choona.Util.for(this.globalEvents, function(methodName, eventName) {
          self.subscribeGlobalEvent(eventName, methodName);
        });
      }

      //subscribe all DOM events !

      if (this.events !== undefined) {
        this.on(this.events);
      }

      //Calling the global preStart function !
      if (typeof choona.Settings.preStart === "function") {
        choona.Settings.preStart.call(this);
      }
      //TODO - You can find all submodule from DOM and load subView

    },
    _getEventBus: function() {
      return this._viewMetadata.eventBus;
    },
    subscribeGlobalEvent: function(topic, methodName) {
      var self = this;
      var callback = function() {
        self[methodName].apply(self, arguments);
      };
      if (this._viewMetadata.topicList[topic] === undefined) {
        this._viewMetadata.topicList[topic] = [];
      }
      var bus = this._getEventBus();
      this._viewMetadata.topicList[topic].push(bus.subscribe(topic, callback));
      log("subscribed topic -> " + topic);
    },
    unsubscribeGlobalEvent: function(topic) {
      log("unsubscribing topic -> " + topic);
      var bus = this._getEventBus();
      if (this._viewMetadata.topicList[topic] !== undefined) {
        this._viewMetadata.topicList[topic].map(function(v, i) {
          bus.unsubscribe(v);
        });
        delete this._viewMetadata.topicList[topic];
      }
    },
    publishGlobalEvent: function(topic, val) {
      log("publishing topic ->" + arguments);
      var bus = this._getEventBus();
      bus.publish.apply(bus, arguments);
    },
    loadSubView: function(data) {
      var self = this;
      if (this._viewMetadata.subModuleList[data.id] === undefined) {
        this._viewMetadata.subModuleList[data.id] = new data.module(data, {
          parentNode: this.$,
          parentEventBus: this._getEventBus(),
          mercykillFunc: function() {
            self.removeSubView(data.id);
          }
        });
      } else {
        throw new Error("data.id::" + data.id + " is already contains a module.  Please provide separate id new module");
      }
    },
    killme: function() {
      if (typeof this._viewMetadata.mercykillFunc === "function") {
        this._viewMetadata.mercykillFunc();
      }
    },
    removeSubView: function(id) {
      if (this._viewMetadata.subModuleList[id] !== undefined) {
        this._viewMetadata.subModuleList[id]._endModule();
        delete this._viewMetadata.subModuleList[id];
      }
      //Deletion is needed because if parent get Ended, it should not try to delete the module again.
    },
    on: function(obj) {
      //We use {"eventName hash":"handler"} kind of notation !
      var self = this;
      choona.Util.for(obj, function(handler, key) {
        key = key.trim().replace(/ +/g, " ");

        var arr = key.split(" ");
        var eventName = arr.shift();
        var hash = arr.join(" ");

        var callback = function(e) {
          if (hash === "") {
            self[handler].call(self, e, e.target, e.target.dataset);
          } else {
            if (e.target.matches(hash)) {
              self[handler].call(self, e, e.target, e.target.dataset);
            }
          }
        };
        choona.Util.bindEvent(self.$, eventName, callback);
        self._viewMetadata.eventsMap[key] = {
          eventName: eventName,
          callback: callback
        };
      });
    },
    off: function(key) {
      //Unsubscribe dom event
      var v = this._viewMetadata.eventsMap[key];
      if (v !== undefined && typeof v === "object") {
        choona.Util.unbindEvent(this.$, v.eventName, v.callback);
        delete this._viewMetadata.eventsMap[key];
      }
    },
    end: function() {
      console.log("Ending base View");
    },
    _endModule: function() {

      //call postEnd();
      if (typeof choona.Settings.postEnd === "function") {
        choona.Settings.postEnd.call(this);
      }

      //endAllSubModules
      var self = this;
      choona.Util.for(this._viewMetadata.subModuleList, function(v, id) {
        self.removeSubView(id);
      });

      if (typeof this.end === "function") {
        this.end();
      }

      //unSubscribing All DOM events
      this._viewMetadata.eventsMap.map(function(v, key) {
        self.off(key);
      });

      //Remove all HTML inside this.$
      this.$.innerHTML = "";

      //unSubscribe All globalEvents
      choona.Util.for(this._viewMetadata.topicList, function(v, topic) {
        self.unsubscribeGlobalEvent(topic);
      });

      delete this.$;
      delete this.$el;
      delete this.$$;
      delete this.config;
      log("ended module -> " + this._viewMetadata.id);
      delete this._viewMetadata.id;
      delete this._viewMetadata.subModuleList;
      delete this._viewMetadata.eventBus;
      delete this._viewMetadata.topicList;
      delete this._viewMetadata.eventsMap;
      delete this._viewMetadata;
    }
  });

  choona.loadView = function(moduleConf) {
    return new moduleConf.module(moduleConf);
  };

})();
<|endoftext|>


<commit_before>/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

PageNetworking.prototype = {
    _init: function () {
        this.id = "networking";
        this._interfaceProxies = {};
    },

    getInterfaceProxy: function(ifname) {
        return this._interfaceProxies[ifname];
    },

    getTitle: function() {
        return C_("page-title", "Networking");
    },

    _set_subtract: function (a, b) {
        var result = {};
        for (var k in a) {
            if (!b[k])
                result[k] = true;
        }
        return result;
    },

    _resync_network_interface_list: function () {
        var manager = cockpit_dbus_client.lookup("/com/redhat/Cockpit/Network", "com.redhat.Cockpit.Network");
        var listContainer = $("#networking_content").get(0);

        var newInterfaceProxies = cockpit_dbus_client.getInterfacesFrom("/com/redhat/Cockpit/Network/",
                                                                    "com.redhat.Cockpit.Network.Netinterface");
        var newInterfaceProxyIndexes = {};

        var ifname, i, proxy, node, parent;

        for (i = 0; i < newInterfaceProxies.length; i++) {
            proxy = newInterfaceProxies[i];
            ifname = proxy['Name'];
            newInterfaceProxyIndexes[ifname] = true;
        }
        var currentInterfaceProxyIndexes = {};
        for (ifname in this._interfaceProxies) {
            currentInterfaceProxyIndexes[ifname] = true;
        }

        var deletedProxyIndexes = this._set_subtract(currentInterfaceProxyIndexes, newInterfaceProxyIndexes);

        for (ifname in deletedProxyIndexes) {
            proxy = this._interfaceProxies[ifname];
            delete this._interfaceProxies[ifname];
            $(proxy).off("notify");
            node = $("#networking-interface-" + ifname).get(0);
            parent = node.parentNode;
            parent.removeChild(node);
        }

        var addedProxyIndexes = this._set_subtract(newInterfaceProxyIndexes, currentInterfaceProxyIndexes);

        var match, insertBefore, interfaces, top, topA, header, ifaceContent;

        for (ifname in addedProxyIndexes) {
            match = $.grep(newInterfaceProxies, function (v) {
                return v['Name'] == ifname;
            });
            proxy = match[0];
            if (!proxy)
                throw Error("no matching proxy for " + ifname);
            this._interfaceProxies[ifname] = proxy;
            $(proxy).on("notify", $.proxy(this._on_iface_notify, this));

            insertBefore = null;
            interfaces = $(".networking-interface").each(function (i, node) {
                if (insertBefore === null) {
                    var cur_ifname = node._ifname;
                    if (cur_ifname > ifname) {
                        insertBefore = node;
                    }
                }
            });

            top = document.createElement("li");
            top.setAttribute("id", "networking-interface-" + ifname);
            top.classList.add("networking-interface");
            top._ifname = ifname; // expando

            topA = document.createElement("a");
            top.appendChild(topA);

            topA.setAttribute("onclick", cockpit_go_down_cmd("networking-iface", { ifname: ifname }));
            header = document.createElement("div");
            header.classList.add("cockpit-network-header");
            header.appendChild(document.createTextNode(proxy['Name']));
            topA.appendChild(header);
            ifaceContent = document.createElement("div");
            ifaceContent.setAttribute("id", "networking_interface_content_" + ifname);
            topA.appendChild(ifaceContent);

            ifaceContent.appendChild(document.createTextNode("Loading..."));

            if (insertBefore)
                listContainer.insertBefore(top, insertBefore);
            else
                listContainer.appendChild(top);
        }

        this._resync_network_interface_list_content();
        $("#networking_content").listview('refresh');
    },

    _ip4AddressToHTML: function (address) {
        var addrlen = 4;
        var p = document.createElement("span");
        var i;
        var text;
        var addressString;

        for (i = 0; i < addrlen; i++) {
            addressString = address[i].toString(10);
            text = document.createTextNode(addressString);
            p.appendChild(text);
            if (i < addrlen - 1)
                    p.appendChild(document.createTextNode('.'));
        }
        p.appendChild(document.createTextNode('/'));
        text = document.createTextNode(address[4]);
        p.appendChild(text);
        return p;

    },

    _ip6AddressToHTML: function (address) {
        var addrlen = 16;
        var p = document.createElement("span");
        var i;
        var text;
        var firstByte, secondByte;

        for (i = 0; i < addrlen; i += 2) {
            firstByte = address[i].toString(16);
            if (firstByte.length == 1)
                firstByte = "0" + firstByte;
            p.appendChild(document.createTextNode(firstByte));
            secondByte = address[i+1].toString(16);
            if (secondByte.length == 1)
                secondByte = "0" + secondByte;
            p.appendChild(document.createTextNode(secondByte));
            if (i < addrlen - 2)
                    p.appendChild(document.createTextNode(':'));
        }
        p.appendChild(document.createTextNode('/'));
        text = document.createTextNode(address[address.length - 1]);
        p.appendChild(text);
        return p;
    },

    _resync_network_interface_list_content: function () {
        var manager = cockpit_dbus_client.lookup("/com/redhat/Cockpit/Network", "com.redhat.Cockpit.Network");
        var i, j, ifname, proxy, content, ip4Addresses, ip6Addresses;
        var table, tr, td;

        for (ifname in this._interfaceProxies) {
            proxy = this._interfaceProxies[ifname];
            content = $("#networking_interface_content_" + ifname).get(0);

            $(content).empty();

            ip4Addresses = proxy['IP4Addresses'];
            ip6Addresses = proxy['IP6Addresses'];

            table = document.createElement('table');
            table.classList.add("cockpit-form-table");
            content.appendChild(table);

            tr = document.createElement('tr');
            table.appendChild(tr);
            td = document.createElement('td');
            tr.appendChild(td);
            td.appendChild(document.createTextNode("Hardware Address"));
            td = document.createElement('td');
            td.appendChild(document.createTextNode(proxy['HwAddress']));
            tr.appendChild(td);

            tr = document.createElement('tr');
            table.appendChild(tr);
            td = document.createElement('td');
            tr.appendChild(td);
            td.appendChild(document.createTextNode("IP Addresses"));

            for (j = 0; j < ip4Addresses.length; j++) {
                td = document.createElement('td');
                tr.appendChild(td);
                td.appendChild(this._ip4AddressToHTML(ip4Addresses[j]));

                tr = document.createElement('tr');
                table.appendChild(tr);
                td = document.createElement('td');
                tr.appendChild(td);
            }

            for (j = 0; j < ip6Addresses.length; j++) {
                td = document.createElement('td');
                tr.appendChild(td);
                td.appendChild(this._ip6AddressToHTML(ip6Addresses[j]));

                tr = document.createElement('tr');
                table.appendChild(tr);
                td = document.createElement('td');
                tr.appendChild(td);
            }

            td = document.createElement('td');
            tr.appendChild(td);
        }
    },

    _on_iface_notify: function (event) {
        var iface = event.target;
        this._resync_network_interface_list_content();
    },

    _resync_if_netinterface_changed: function (event, obj) {
        if (obj.objectPath.indexOf('/com/redhat/Cockpit/Network/') === 0)
            this._resync_network_interface_list();
    },

    enter: function (first_visit) {
        if (first_visit) {
            $(cockpit_dbus_client).on("objectAdded", $.proxy(this._resync_if_netinterface_changed, this));
            $(cockpit_dbus_client).on("objectRemoved", $.proxy(this._resync_if_netinterface_changed, this));
            this._resync_network_interface_list();
        }
    },

    show: function() {
        $("#networking_content").listview('refresh');
    },

    leave: function() {
    }
};

function PageNetworking() {
    this._init();
}

cockpit_pages.push(new PageNetworking());

PageNetworkingIface.prototype = {
    _init: function () {
        this.id = "networking-iface";
    },

    getTitle: function() {
        return C_("page-title", "Network Interface");
    },

    enter: function (first_visit) {
        var ifname = cockpit_get_page_param("ifname");
        if (!ifname)
            return;

        var networkingPage = cockpit_page_from_id("networking");
        var proxy = networkingPage.getInterfaceProxy(ifname);

        var node = $("#networking_iface_config_ip4_text").get(0);
        node.appendChild(document.createTextNode(proxy['IP4ConfigMode']));
        node = $("#networking_iface_config_ip6_text").get(0);
        node.appendChild(document.createTextNode(proxy['IP6ConfigMode']));
    },

    show: function() {
    },

    leave: function() {
    }
};

function PageNetworkingIface() {
    this._init();
}

cockpit_pages.push(new PageNetworkingIface());
<commit_msg>networking: Fix trivial bug in current UI<commit_after>/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

PageNetworking.prototype = {
    _init: function () {
        this.id = "networking";
        this._interfaceProxies = {};
    },

    getInterfaceProxy: function(ifname) {
        return this._interfaceProxies[ifname];
    },

    getTitle: function() {
        return C_("page-title", "Networking");
    },

    _set_subtract: function (a, b) {
        var result = {};
        for (var k in a) {
            if (!b[k])
                result[k] = true;
        }
        return result;
    },

    _resync_network_interface_list: function () {
        var manager = cockpit_dbus_client.lookup("/com/redhat/Cockpit/Network", "com.redhat.Cockpit.Network");
        var listContainer = $("#networking_content").get(0);

        var newInterfaceProxies = cockpit_dbus_client.getInterfacesFrom("/com/redhat/Cockpit/Network/",
                                                                    "com.redhat.Cockpit.Network.Netinterface");
        var newInterfaceProxyIndexes = {};

        var ifname, i, proxy, node, parent;

        for (i = 0; i < newInterfaceProxies.length; i++) {
            proxy = newInterfaceProxies[i];
            ifname = proxy['Name'];
            newInterfaceProxyIndexes[ifname] = true;
        }
        var currentInterfaceProxyIndexes = {};
        for (ifname in this._interfaceProxies) {
            currentInterfaceProxyIndexes[ifname] = true;
        }

        var deletedProxyIndexes = this._set_subtract(currentInterfaceProxyIndexes, newInterfaceProxyIndexes);

        for (ifname in deletedProxyIndexes) {
            proxy = this._interfaceProxies[ifname];
            delete this._interfaceProxies[ifname];
            $(proxy).off("notify");
            node = $("#networking-interface-" + ifname).get(0);
            parent = node.parentNode;
            parent.removeChild(node);
        }

        var addedProxyIndexes = this._set_subtract(newInterfaceProxyIndexes, currentInterfaceProxyIndexes);

        var match, insertBefore, interfaces, top, topA, header, ifaceContent;

        for (ifname in addedProxyIndexes) {
            match = $.grep(newInterfaceProxies, function (v) {
                return v['Name'] == ifname;
            });
            proxy = match[0];
            if (!proxy)
                throw Error("no matching proxy for " + ifname);
            this._interfaceProxies[ifname] = proxy;
            $(proxy).on("notify", $.proxy(this._on_iface_notify, this));

            insertBefore = null;
            interfaces = $(".networking-interface").each(function (i, node) {
                if (insertBefore === null) {
                    var cur_ifname = node._ifname;
                    if (cur_ifname > ifname) {
                        insertBefore = node;
                    }
                }
            });

            top = document.createElement("li");
            top.setAttribute("id", "networking-interface-" + ifname);
            top.classList.add("networking-interface");
            top._ifname = ifname; // expando

            topA = document.createElement("a");
            top.appendChild(topA);

            topA.setAttribute("onclick", cockpit_go_down_cmd("networking-iface", { ifname: ifname }));
            header = document.createElement("div");
            header.classList.add("cockpit-network-header");
            header.appendChild(document.createTextNode(proxy['Name']));
            topA.appendChild(header);
            ifaceContent = document.createElement("div");
            ifaceContent.setAttribute("id", "networking_interface_content_" + ifname);
            topA.appendChild(ifaceContent);

            ifaceContent.appendChild(document.createTextNode("Loading..."));

            if (insertBefore)
                listContainer.insertBefore(top, insertBefore);
            else
                listContainer.appendChild(top);
        }

        this._resync_network_interface_list_content();
        $("#networking_content").listview('refresh');
    },

    _ip4AddressToHTML: function (address) {
        var addrlen = 4;
        var p = document.createElement("span");
        var i;
        var text;
        var addressString;

        for (i = 0; i < addrlen; i++) {
            addressString = address[i].toString(10);
            text = document.createTextNode(addressString);
            p.appendChild(text);
            if (i < addrlen - 1)
                    p.appendChild(document.createTextNode('.'));
        }
        p.appendChild(document.createTextNode('/'));
        text = document.createTextNode(address[4]);
        p.appendChild(text);
        return p;

    },

    _ip6AddressToHTML: function (address) {
        var addrlen = 16;
        var p = document.createElement("span");
        var i;
        var text;
        var firstByte, secondByte;

        for (i = 0; i < addrlen; i += 2) {
            firstByte = address[i].toString(16);
            if (firstByte.length == 1)
                firstByte = "0" + firstByte;
            p.appendChild(document.createTextNode(firstByte));
            secondByte = address[i+1].toString(16);
            if (secondByte.length == 1)
                secondByte = "0" + secondByte;
            p.appendChild(document.createTextNode(secondByte));
            if (i < addrlen - 2)
                    p.appendChild(document.createTextNode(':'));
        }
        p.appendChild(document.createTextNode('/'));
        text = document.createTextNode(address[address.length - 1]);
        p.appendChild(text);
        return p;
    },

    _resync_network_interface_list_content: function () {
        var manager = cockpit_dbus_client.lookup("/com/redhat/Cockpit/Network", "com.redhat.Cockpit.Network");
        var i, j, ifname, proxy, content, ip4Addresses, ip6Addresses;
        var table, tr, td;

        for (ifname in this._interfaceProxies) {
            proxy = this._interfaceProxies[ifname];
            content = $("#networking_interface_content_" + ifname).get(0);

            $(content).empty();

            ip4Addresses = proxy['IP4Addresses'];
            ip6Addresses = proxy['IP6Addresses'];

            table = document.createElement('table');
            table.classList.add("cockpit-form-table");
            content.appendChild(table);

            tr = document.createElement('tr');
            table.appendChild(tr);
            td = document.createElement('td');
            tr.appendChild(td);
            td.appendChild(document.createTextNode("Hardware Address"));
            td = document.createElement('td');
            td.appendChild(document.createTextNode(proxy['HwAddress']));
            tr.appendChild(td);

            tr = document.createElement('tr');
            table.appendChild(tr);
            td = document.createElement('td');
            tr.appendChild(td);
            td.appendChild(document.createTextNode("IP Addresses"));

            for (j = 0; j < ip4Addresses.length; j++) {
                td = document.createElement('td');
                tr.appendChild(td);
                td.appendChild(this._ip4AddressToHTML(ip4Addresses[j]));

                tr = document.createElement('tr');
                table.appendChild(tr);
                td = document.createElement('td');
                tr.appendChild(td);
            }

            for (j = 0; j < ip6Addresses.length; j++) {
                td = document.createElement('td');
                tr.appendChild(td);
                td.appendChild(this._ip6AddressToHTML(ip6Addresses[j]));

                tr = document.createElement('tr');
                table.appendChild(tr);
                td = document.createElement('td');
                tr.appendChild(td);
            }

            td = document.createElement('td');
            tr.appendChild(td);
        }
    },

    _on_iface_notify: function (event) {
        var iface = event.target;
        this._resync_network_interface_list_content();
    },

    _resync_if_netinterface_changed: function (event, obj) {
        if (obj.objectPath.indexOf('/com/redhat/Cockpit/Network/') === 0)
            this._resync_network_interface_list();
    },

    enter: function (first_visit) {
        if (first_visit) {
            $(cockpit_dbus_client).on("objectAdded", $.proxy(this._resync_if_netinterface_changed, this));
            $(cockpit_dbus_client).on("objectRemoved", $.proxy(this._resync_if_netinterface_changed, this));
            this._resync_network_interface_list();
        }
    },

    show: function() {
        $("#networking_content").listview('refresh');
    },

    leave: function() {
    }
};

function PageNetworking() {
    this._init();
}

cockpit_pages.push(new PageNetworking());

PageNetworkingIface.prototype = {
    _init: function () {
        this.id = "networking-iface";
    },

    getTitle: function() {
        return C_("page-title", "Network Interface");
    },

    enter: function (first_visit) {
        var ifname = cockpit_get_page_param("ifname");
        if (!ifname)
            return;

        var networkingPage = cockpit_page_from_id("networking");
        var proxy = networkingPage.getInterfaceProxy(ifname);

        $("#networking_iface_config_ip4_text").text(proxy['IP4ConfigMode']);
        $("#networking_iface_config_ip6_text").text(proxy['IP6ConfigMode']);
    },

    show: function() {
    },

    leave: function() {
    }
};

function PageNetworkingIface() {
    this._init();
}

cockpit_pages.push(new PageNetworkingIface());
<|endoftext|>


<commit_before>const { join, resolve } = require('path');
const fs = require('fs-extra');
const globby = require('globby');
const {
  getPkgPathFromName,
  getPkgDependents,
  getPkgDependencies,
  getPkgList,
  getPkgFiles,
  getFilesPkgSync,
  getFilesChanged,
  findTwigFilesUsedInFile,
  getFilesPkg,
  getTwigFilePath,
} = require('@bolt/testing-utils');

/**
 * @param {string} pkgName
 * @param {string[]} deps
 */
function pkgToHaveDependenciesOn(pkgName, deps) {
  const listedDeps = getPkgDependencies(pkgName);
  const missingDeps = [];
  deps.forEach(dep => {
    if (!listedDeps.some(d => d === dep)) {
      if (dep !== pkgName) {
        if (dep !== '@bolt/global') {
          missingDeps.push(dep);
        }
      }
    }
  });

  const pass = missingDeps.length === 0;

  return pass
    ? {
        pass,
        message: () => `${pkgName} has all dependencies listed correctly`,
      }
    : {
        pass,
        message: () =>
          `${pkgName} is missing these dependencies in package.json: ${missingDeps.join(
            ', ',
          )}`,
      };
}

expect.extend({ pkgToHaveDependenciesOn });

/** @type {BoltPkg[]} */
const boltPkgs = getPkgList();

describe('Bolt Components declare dependencies in package.json if used in Twig files', () => {
  const excludedPkgs = ['generator-bolt'];

  boltPkgs
    .filter(boltPkg => !excludedPkgs.includes(boltPkg.name))
    .forEach(
      /** @type {BoltPkg} */
      boltPkg => {
        test(`pkg: ${boltPkg.name}`, async () => {
          const twigFilePaths = await globby(
            [join(boltPkg.location, '**/*.twig')],
            {
              gitignore: true,
              ignore: ['**/__tests__/**', '**/node_modules/**', '**/vendor/**'],
            },
          );

          if (twigFilePaths.length === 0) {
            expect(true).toBe(true);
          } else {
            /** @type {Set<string>} */
            const twigDeps = new Set();
            /** @type {Set<string>} */
            const twigDepPkgs = new Set();

            await Promise.all(
              twigFilePaths.map(async twigFilePath => {
                const theseTwigDeps = await findTwigFilesUsedInFile(
                  twigFilePath,
                );
                theseTwigDeps.forEach(x => twigDeps.add(x));
              }),
            );

            await Promise.all(
              [...twigDeps].map(twigDep => {
                return getTwigFilePath(twigDep)
                  .then(getFilesPkg)
                  .then(pkgName => twigDepPkgs.add(pkgName));
              }),
            );

            twigDepPkgs.delete(boltPkg.name);

            expect(boltPkg.name).pkgToHaveDependenciesOn([...twigDepPkgs]);
          }
        });
      },
    );
});
<commit_msg>test: give monorepo deps test longer<commit_after>const { join, resolve } = require('path');
const fs = require('fs-extra');
const globby = require('globby');
const {
  getPkgPathFromName,
  getPkgDependents,
  getPkgDependencies,
  getPkgList,
  getPkgFiles,
  getFilesPkgSync,
  getFilesChanged,
  findTwigFilesUsedInFile,
  getFilesPkg,
  getTwigFilePath,
} = require('@bolt/testing-utils');

/**
 * @param {string} pkgName
 * @param {string[]} deps
 */
function pkgToHaveDependenciesOn(pkgName, deps) {
  const listedDeps = getPkgDependencies(pkgName);
  const missingDeps = [];
  deps.forEach(dep => {
    if (!listedDeps.some(d => d === dep)) {
      if (dep !== pkgName) {
        if (dep !== '@bolt/global') {
          missingDeps.push(dep);
        }
      }
    }
  });

  const pass = missingDeps.length === 0;

  return pass
    ? {
        pass,
        message: () => `${pkgName} has all dependencies listed correctly`,
      }
    : {
        pass,
        message: () =>
          `${pkgName} is missing these dependencies in package.json: ${missingDeps.join(
            ', ',
          )}`,
      };
}

expect.extend({ pkgToHaveDependenciesOn });

/** @type {BoltPkg[]} */
const boltPkgs = getPkgList();

describe('Bolt Components declare dependencies in package.json if used in Twig files', () => {
  const excludedPkgs = ['generator-bolt'];

  boltPkgs
    .filter(boltPkg => !excludedPkgs.includes(boltPkg.name))
    .forEach(
      /** @type {BoltPkg} */
      boltPkg => {
        test(`pkg: ${boltPkg.name}`, async () => {
          const twigFilePaths = await globby(
            [join(boltPkg.location, '**/*.twig')],
            {
              gitignore: true,
              ignore: ['**/__tests__/**', '**/node_modules/**', '**/vendor/**'],
            },
          );

          if (twigFilePaths.length === 0) {
            expect(true).toBe(true);
          } else {
            /** @type {Set<string>} */
            const twigDeps = new Set();
            /** @type {Set<string>} */
            const twigDepPkgs = new Set();

            await Promise.all(
              twigFilePaths.map(async twigFilePath => {
                const theseTwigDeps = await findTwigFilesUsedInFile(
                  twigFilePath,
                );
                theseTwigDeps.forEach(x => twigDeps.add(x));
              }),
            );

            await Promise.all(
              [...twigDeps].map(twigDep => {
                return getTwigFilePath(twigDep)
                  .then(getFilesPkg)
                  .then(pkgName => twigDepPkgs.add(pkgName));
              }),
            );

            twigDepPkgs.delete(boltPkg.name);

            expect(boltPkg.name).pkgToHaveDependenciesOn([...twigDepPkgs]);
          }
        }, 10000);
      },
    );
});
<|endoftext|>


<commit_before>require('babel-polyfill');
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackExcludeAssetsPlugin = require('html-webpack-exclude-assets-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const entries = require('../../configs/entries');
const transpiling = require('../../configs/transpiling');
const os = require('os');
const moduleExclude = new RegExp(
    'node_modules/(?!(' + transpiling.join('|') + ')/).*'
);

// Load custome webpack config
var webpackConfig = (env, config) => config;
try {
    webpackConfig = require('../site/webpack.config.js');
} catch (e) {}

module.exports = env => {
    /**
     * Augument entries with 'whatwg-fetch' and 'babel-polyfill'
     */
    const _entries = {};
    Object.keys(entries).forEach((key, i) => {
        if (key === 'base') {
            _entries[key] = ['babel-polyfill', 'whatwg-fetch'].concat(
                entries[key]
            );
        } else {
            _entries[key] = ['whatwg-fetch'].concat(entries[key]);
        }
    });

    //
    const entriesOrder = { core: 0 };
    Object.keys(entries).forEach((key, i) => {
        entriesOrder[key] = i + 1;
    });

    /**
     * Plugin setting
     */
    var plugins = [
        new ExtractTextPlugin('../css/app.bundle.css'),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'core',
            minChunks: Infinity
        }),
        new HtmlWebpackPlugin({
            excludeAssets: [/app.*.css/],
            minify: false,
            chunksSortMode: (e1, e2) =>
                entriesOrder[e1.names[0]] - entriesOrder[e2.names[0]],
            filename: path.resolve('../_includes/dist/footer_scripts.inc'),
            template: 'src/core/.empty'
        }),
        new HtmlWebpackExcludeAssetsPlugin(),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
        }),
    ];
    // Production
    if (env.prod) {
        plugins = plugins.concat([
            new webpack.LoaderOptionsPlugin({
                minimize: true,
                debug: false
            }),
            new webpack.DefinePlugin(
                Object.assign(
                    {},
                    {},
                    {
                        'process.env': {
                            NODE_ENV: JSON.stringify('production')
                        }
                    }
                )
            ),
            new UglifyJsPlugin({
                uglifyOptions: {
                    warnings: false,
                    ie8: false
                },
                parallel: os.cpus().length,
                cache: true,
            })
        ]);
    }
    // Dev
    else if (env.dev) {
        plugins = plugins.concat([new webpack.DefinePlugin({})]);
    }

    return webpackConfig(env, {
        entry: _entries,
        output: {
            filename: env.prod
                ? '[name].[chunkhash].bundle.js'
                : '[name].[chunkhash].dev.bundle.js',
            path: path.resolve('../assets/dist/js/'),
            publicPath: '/assets/dist/js/'
        },
        resolve: {
            extensions: ['.js', '.jsx', '.yaml']
        },
        devtool: env.dev ? 'source-map' : '',
        module: {
            loaders: [
                {
                    exclude: moduleExclude,
                    test: /(\.js$|\.jsx$)/,
                    loader: 'babel-loader',
                    query: {
                        plugins: ['transform-decorators-legacy'],
                        presets: ['env', 'react', 'stage-2']
                    }
                },
                {
                    exclude: /(node_modules|bower_components)/,
                    test: /\.yaml$/,
                    loader: 'yaml-loader'
                },
                {
                    test: /\.json$/,
                    loader: 'json-loader'
                },
                {
                    test: /\.scss$|\.css$/,
                    loader: ExtractTextPlugin.extract('css-loader!sass-loader')
                }
            ]
        },
        plugins: plugins,
        node: {
            fs: 'empty',
            child_process: 'empty'
        }
    });
};
<commit_msg>Update webpack.config.js<commit_after>require('babel-polyfill');
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackExcludeAssetsPlugin = require('html-webpack-exclude-assets-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const entries = require('../../configs/entries');
const transpiling = require('../../configs/transpiling');
const os = require('os');
const moduleExclude = new RegExp(
    'node_modules/(?!(' + transpiling.join('|') + ')/).*'
);

// Load custome webpack config
var webpackConfig = (env, config) => config;
try {
    webpackConfig = require('../site/webpack.config.js');
} catch (e) {}

module.exports = env => {
    /**
     * Augument entries with 'whatwg-fetch' and 'babel-polyfill'
     */
    const _entries = {};
    Object.keys(entries).forEach((key, i) => {
        if (key === 'base') {
            _entries[key] = ['babel-polyfill', 'whatwg-fetch'].concat(
                entries[key]
            );
        } else {
            _entries[key] = ['whatwg-fetch'].concat(entries[key]);
        }
    });

    //
    const entriesOrder = { core: 0 };
    Object.keys(entries).forEach((key, i) => {
        entriesOrder[key] = i + 1;
    });

    /**
     * Plugin setting
     */
    var plugins = [
        new ExtractTextPlugin('../css/app.bundle.css'),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'core'
        }),
        new HtmlWebpackPlugin({
            excludeAssets: [/app.*.css/],
            minify: false,
            chunksSortMode: (e1, e2) =>
                entriesOrder[e1.names[0]] - entriesOrder[e2.names[0]],
            filename: path.resolve('../_includes/dist/footer_scripts.inc'),
            template: 'src/core/.empty'
        }),
        new HtmlWebpackExcludeAssetsPlugin(),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
        }),
    ];
    // Production
    if (env.prod) {
        plugins = plugins.concat([
            new webpack.LoaderOptionsPlugin({
                minimize: true,
                debug: false
            }),
            new webpack.DefinePlugin(
                Object.assign(
                    {},
                    {},
                    {
                        'process.env': {
                            NODE_ENV: JSON.stringify('production')
                        }
                    }
                )
            ),
            new UglifyJsPlugin({
                uglifyOptions: {
                    warnings: false,
                    ie8: false
                },
                parallel: os.cpus().length,
                cache: true,
            })
        ]);
    }
    // Dev
    else if (env.dev) {
        plugins = plugins.concat([new webpack.DefinePlugin({})]);
    }

    return webpackConfig(env, {
        entry: _entries,
        output: {
            filename: env.prod
                ? '[name].[chunkhash].bundle.js'
                : '[name].[chunkhash].dev.bundle.js',
            path: path.resolve('../assets/dist/js/'),
            publicPath: '/assets/dist/js/'
        },
        resolve: {
            extensions: ['.js', '.jsx', '.yaml']
        },
        devtool: env.dev ? 'source-map' : '',
        module: {
            loaders: [
                {
                    exclude: moduleExclude,
                    test: /(\.js$|\.jsx$)/,
                    loader: 'babel-loader',
                    query: {
                        plugins: ['transform-decorators-legacy'],
                        presets: ['env', 'react', 'stage-2']
                    }
                },
                {
                    exclude: /(node_modules|bower_components)/,
                    test: /\.yaml$/,
                    loader: 'yaml-loader'
                },
                {
                    test: /\.json$/,
                    loader: 'json-loader'
                },
                {
                    test: /\.scss$|\.css$/,
                    loader: ExtractTextPlugin.extract('css-loader!sass-loader')
                }
            ]
        },
        plugins: plugins,
        node: {
            fs: 'empty',
            child_process: 'empty'
        }
    });
};
<|endoftext|>


<commit_before>

// console.log("nav js loaded");

// $(window).scroll(function() {
//   if ($(document).scrollTop() > 35) {
//     // $('.navbar').addClass('shrink');
//    $('img#nav-logo').animate({width: "15px"}, 300);
//    console.log("ran shrink");
// //$('img#nav-logo').animate({"width": "20px"}, 5000, "linear");

//   } else if($(document).scrollTop() < 10){
//     // $('.navbar').removeClass('shrink');
//    $('img#nav-logo').animate({width: "100px"}, 300);
//    console.log("ran expand");

//   // $('img#nav-logo').animate({"width": "100px"}, 5000, "linear");

//   }
// });

$(document).ready(function(){

var collapsedBar = false;

 if(window.pageYOffset > 35 && collapsedBar == false){  // collapsed size
         collapsedBar = true;
          //collapse bar

          $('img#nav-logo').animate({width: "20px"},300,function(){});

         // document.getElementById('span1').innerHTML='some value...';

console.log("greater than ");
        }

        if(window.pageYOffset == 0){ //full size
         collapsedBar = false;

         $('img#nav-logo').animate({width: "100px"},300,function(){});

         console.log("zero");

        }

});

   <commit_msg>trying different code<commit_after>

// console.log("nav js loaded");

// $(window).scroll(function() {
//   if ($(document).scrollTop() > 35) {
//     // $('.navbar').addClass('shrink');
//    $('img#nav-logo').animate({width: "15px"}, 300);
//    console.log("ran shrink");
// //$('img#nav-logo').animate({"width": "20px"}, 5000, "linear");

//   } else if($(document).scrollTop() < 10){
//     // $('.navbar').removeClass('shrink');
//    $('img#nav-logo').animate({width: "100px"}, 300);
//    console.log("ran expand");

//   // $('img#nav-logo').animate({"width": "100px"}, 5000, "linear");

//   }
// });

// $(document).ready(function(){

// var collapsedBar = false;

//  if(window.pageYOffset > 35 && collapsedBar == false){  // collapsed size
//          collapsedBar = true;
//           //collapse bar

//           $('img#nav-logo').animate({width: "20px"},300,function(){});

//          // document.getElementById('span1').innerHTML='some value...';

// console.log("greater than ");
//         }

//         if(window.pageYOffset == 0){ //full size
//          collapsedBar = false;

//          $('img#nav-logo').animate({width: "100px"},300,function(){});

//          console.log("zero");

//         }

// });

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
      $('img#nav-logo').animate({width: "20px"},300,function(){});
      console.log("greater than ");

  } else {

         $('img#nav-logo').animate({width: "100px"},300,function(){});
         console.log("shrunk");

  }
});

   <|endoftext|>


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

module.exports = function(RED) {
    "use strict";
    var owfs = require("owfs");
    var async = require("async");

    function OwfsNode(n) {
        RED.nodes.createNode(this,n);
        this.host = n.host;
        this.port = n.port;
        this.paths = n.paths;

        var node = this;
        node.on("input", function(msg) {
            var host = msg.host  ||  node.host;
            var port = msg.port  ||  node.port;
            var client = new owfs.Client(host, port);
            var paths = node.paths;
            if (msg.topic) {
                paths = [msg.topic];
            }

            if (paths && paths.length > 0) {
                // Query owfs for each path, one at a time
                async.eachSeries(paths, function(path, callback) {
                    client.read(path, function(error, result) {
                        if (!error) {
                            if (result.match(/^\-?\d+\.\d+$/)) {
                                msg.payload = parseFloat(result);
                            } else if (result.match(/^\-?\d+$/)) {
                                msg.payload = parseInt(result);
                            } else {
                                msg.payload = result;
                            }
                            msg.topic = path;
                            msg.timestamp = Date.now();
                            node.send(msg);
                        } else {
                            if ('msg' in error) {
                                node.error(error.msg, msg);
                            } else {
                                node.error(error, msg);
                            }
                        }
                        callback();
                    });
                });
            } else {
                node.warn("no owfs paths configured and msg.topic is empty");
            }
        });
    }
    RED.nodes.registerType("owfs",OwfsNode);

    RED.httpAdmin.get("/owfs/dirall",function(req,res) {
        var blacklist = new RegExp("/(?:address|crc8|errata|family|id|locator|r_[a-z]+)$");
        if (!req.query.host) {
            return res.status(400).send({'error': "Missing 'host' parameter in query string"});
        } else if (!req.query.port) {
            return res.status(400).send({'error': "Missing 'port' parameter in query string"});
        }

        var client = new owfs.Client(req.query.host, req.query.port);
        var node = this;
        client.dirall("/",function(error, directories) {
            if (!error) {
                async.mapSeries(directories,
                    function(directory,cb) {
                        client.dirall(directory,cb);
                    },
                    function(error, results) {
                        if (!error) {
                            var paths = [];
                            var count = 0;
                            results.forEach(function(device) {
                                count++;
                                device.forEach(function(property) {
                                    if (property && !property.match(blacklist)) {
                                        paths.push(property.substr(1));
                                    }
                                });
                            });
                            res.send({'deviceCount': count, 'paths': paths.sort()});
                        } else {
                            res.send({'error': error.message});
                        }
                    }
                );
            } else {
                res.send({'error': error.message});
            }
        });
    });
}
<commit_msg>Warning message if port and host not provided<commit_after>/**
 * Copyright 2014 Nicholas Humfrey
 * Copyright 2013 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

module.exports = function(RED) {
    "use strict";
    var owfs = require("owfs");
    var async = require("async");

    function OwfsNode(n) {
        RED.nodes.createNode(this,n);
        this.host = n.host;
        this.port = n.port;
        this.paths = n.paths;

        var node = this;
        node.on("input", function(msg) {
            var host = msg.host  ||  node.host;
            var port = msg.port  ||  node.port;
            var client = new owfs.Client(host, port);
            var paths = node.paths;
            if (msg.topic) {
                paths = [msg.topic];
            }

            if (host && host.length > 0 && port && port.length > 0) {
              if (paths && paths.length > 0) {
                  // Query owfs for each path, one at a time
                  async.eachSeries(paths, function(path, callback) {
                      client.read(path, function(error, result) {
                          if (!error) {
                              if (result.match(/^\-?\d+\.\d+$/)) {
                                  msg.payload = parseFloat(result);
                              } else if (result.match(/^\-?\d+$/)) {
                                  msg.payload = parseInt(result);
                              } else {
                                  msg.payload = result;
                              }
                              msg.topic = path;
                              msg.timestamp = Date.now();
                              node.send(msg);
                          } else {
                              if ('msg' in error) {
                                  node.error(error.msg, msg);
                              } else {
                                  node.error(error, msg);
                              }
                          }
                          callback();
                      });
                  });
              } else {
                  node.warn("no owfs paths configured and msg.topic is empty");
              }
          } else {
              node.warn("missing host or port configuration and not provided by msg.host and msg.port");
          }
        });
    }
    RED.nodes.registerType("owfs",OwfsNode);

    RED.httpAdmin.get("/owfs/dirall",function(req,res) {
        var blacklist = new RegExp("/(?:address|crc8|errata|family|id|locator|r_[a-z]+)$");
        if (!req.query.host) {
            return res.status(400).send({'error': "Missing 'host' parameter in query string"});
        } else if (!req.query.port) {
            return res.status(400).send({'error': "Missing 'port' parameter in query string"});
        }

        var client = new owfs.Client(req.query.host, req.query.port);
        var node = this;
        client.dirall("/",function(error, directories) {
            if (!error) {
                async.mapSeries(directories,
                    function(directory,cb) {
                        client.dirall(directory,cb);
                    },
                    function(error, results) {
                        if (!error) {
                            var paths = [];
                            var count = 0;
                            results.forEach(function(device) {
                                count++;
                                device.forEach(function(property) {
                                    if (property && !property.match(blacklist)) {
                                        paths.push(property.substr(1));
                                    }
                                });
                            });
                            res.send({'deviceCount': count, 'paths': paths.sort()});
                        } else {
                            res.send({'error': error.message});
                        }
                    }
                );
            } else {
                res.send({'error': error.message});
            }
        });
    });
}
<|endoftext|>


<commit_before>var githubFeed = ({
  feedUrl: "",

  loadFeedUrl: function() {
    var self = this;
    chrome.storage.local.get("current_user_url", function(data) {
      self.feedUrl = data.current_user_url;
    });
  },

  urlChanged: function() {
    chrome.storage.onChanged.addListener(function(changes, namespace) {
      for (var key in changes) {
        if (key === "current_user_url") {
          alert("!!!");
          console.log(changes[key].newValue);
          this.feedUrl = chages[key].newValue;
        }
      }
    });
  },

  getUserFeed: function() {
    $.ajax({
      type: "GET",
      url: this.feedUrl,
      success: function (data) {
        debugger;
      },
      error: function (xhr, status, data) {
        debugger;
      },
    });
  },

  init: function() {
    this.urlChanged();
    return this;
  },
}).init();
githubFeed.loadFeedUrl();
<commit_msg>Fix variable name<commit_after>var githubFeed = ({
  feedUrl: "",

  loadFeedUrl: function() {
    var self = this;
    chrome.storage.local.get("current_user_url", function(data) {
      self.feedUrl = data.current_user_url;
    });
  },

  urlChanged: function() {
    chrome.storage.onChanged.addListener(function(changes, namespace) {
      for (var key in changes) {
        if (key === "current_user_url") {
          alert("!!!");
          console.log(changes[key].newValue);
          this.feedUrl = changes[key].newValue;
        }
      }
    });
  },

  getUserFeed: function() {
    $.ajax({
      type: "GET",
      url: this.feedUrl,
      success: function (data) {
        debugger;
      },
      error: function (xhr, status, data) {
        debugger;
      },
    });
  },

  init: function() {
    this.urlChanged();
    return this;
  },
}).init();
githubFeed.loadFeedUrl();
<|endoftext|>