<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var htmlWiring = require('html-wiring');

module.exports = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);
  },

  init: function () {
  },

  writing: {
    core: function () {
      this.log('updating "./src/core" directory');
      this.directory('../../app/templates/app/src/core', './src/core');
    },
    lib: function () {
      this.log('updating "./src/lib" directory');
      this.directory('../../app/templates/app/src/lib', './src/lib');
    },
    util: function () {
      this.log('updating "./src/util" directory');
      this.directory('../../app/templates/app/src/util', './src/util');
    },
    widget: function () {
      this.log('updating "./src/widget" directory');
      this.directory('../../app/templates/app/src/widget', './src/widget');
    },
    reqirejs: function () {
      this.log('updating reqirejs files');
      this.copy('../../app/templates/app/src/almond.js', './src/almond.js');
      this.copy('../../app/templates/app/src/require.js', './src/require.js');
      this.copy('../../app/templates/app/src/require-config.js', './src/require-config.js');
    },
    app: function(){
      this.log('updating some files in "./src/app/" directory');
      //copy Basic Controller.js
      this.copy('../../app/templates/app/src/app/controller/Controller.js', './src/app/controller/Controller.js');
      //copy Basic View.js
      this.copy('../../app/templates/app/src/app/view/View.js', './src/app/view/View.js');
      //copy Basic Model.js
      this.copy('../../app/templates/app/src/app/model/Model.js', './src/app/model/Model.js');
    },
    scss: function(){
      this.log('updating some files in "./scss/" directory');
      this.copy('../../app/templates/app/scss/_debug-common.scss','./scss/_debug-common.scss');
      this.copy('../../app/templates/app/scss/_debug-mixin.scss','./scss/_debug-mixin.scss');
      this.copy('../../app/templates/app/scss/_debug-components.scss','./scss/_debug-components.scss');
      this.copy('../../app/templates/app/scss/_debug-slide.scss','./scss/_debug-slide.scss');
      this.copy('../../app/templates/app/scss/_debug-msgbox.scss','./scss/_debug-msgbox.scss');
      this.copy('../../app/templates/app/scss/_debug-tooltip.scss','./scss/_debug-tooltip.scss');
      this.copy('../../app/templates/app/scss/_debug-animate.scss','./scss/_debug-animate.scss');
      this.copy('../../app/templates/app/scss/_debug-button.scss','./scss/_debug-button.scss');
    },
    html: function(){
      this.log('updating some files in "./html/" directory');
      this.copy('../../app/templates/app/html/site/include/msgbox.html','./html/site/include/msgbox.html');
      this.copy('../../app/templates/app/html/site/include/tooltip.html','./html/site/include/tooltip.html');
      this.copy('../../app/templates/app/html/site/include/components.html','./html/site/include/components.html');
      this.copy('../../app/templates/app/html/site/include/download.html','./html/site/include/download.html');
      this.copy('../../app/templates/app/html/site/include/scripts-version.html','./html/site/include/scripts-version.html');
      this.copy('../../app/templates/app/html/site/include/styles-version.html','./html/site/include/styles-version.html');
    },
    other: function(){
      this.copy('../../app/templates/app/README.md', './README.md');
    }
  }
});
<commit_msg>fix missing _debug-loading-spinner.scss<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var htmlWiring = require('html-wiring');

module.exports = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);
  },

  init: function () {
  },

  writing: {
    core: function () {
      this.log('updating "./src/core" directory');
      this.directory('../../app/templates/app/src/core', './src/core');
    },
    lib: function () {
      this.log('updating "./src/lib" directory');
      this.directory('../../app/templates/app/src/lib', './src/lib');
    },
    util: function () {
      this.log('updating "./src/util" directory');
      this.directory('../../app/templates/app/src/util', './src/util');
    },
    widget: function () {
      this.log('updating "./src/widget" directory');
      this.directory('../../app/templates/app/src/widget', './src/widget');
    },
    reqirejs: function () {
      this.log('updating reqirejs files');
      this.copy('../../app/templates/app/src/almond.js', './src/almond.js');
      this.copy('../../app/templates/app/src/require.js', './src/require.js');
      this.copy('../../app/templates/app/src/require-config.js', './src/require-config.js');
    },
    app: function(){
      this.log('updating some files in "./src/app/" directory');
      //copy Basic Controller.js
      this.copy('../../app/templates/app/src/app/controller/Controller.js', './src/app/controller/Controller.js');
      //copy Basic View.js
      this.copy('../../app/templates/app/src/app/view/View.js', './src/app/view/View.js');
      //copy Basic Model.js
      this.copy('../../app/templates/app/src/app/model/Model.js', './src/app/model/Model.js');
    },
    scss: function(){
      this.log('updating some files in "./scss/" directory');
      this.copy('../../app/templates/app/scss/_debug-common.scss','./scss/_debug-common.scss');
      this.copy('../../app/templates/app/scss/_debug-mixin.scss','./scss/_debug-mixin.scss');
      this.copy('../../app/templates/app/scss/_debug-components.scss','./scss/_debug-components.scss');
      this.copy('../../app/templates/app/scss/_debug-slide.scss','./scss/_debug-slide.scss');
      this.copy('../../app/templates/app/scss/_debug-msgbox.scss','./scss/_debug-msgbox.scss');
      this.copy('../../app/templates/app/scss/_debug-tooltip.scss','./scss/_debug-tooltip.scss');
      this.copy('../../app/templates/app/scss/_debug-loading-spinner.scss','./scss/_debug-loading-spinner.scss');
      this.copy('../../app/templates/app/scss/_debug-animate.scss','./scss/_debug-animate.scss');
      this.copy('../../app/templates/app/scss/_debug-button.scss','./scss/_debug-button.scss');
    },
    html: function(){
      this.log('updating some files in "./html/" directory');
      this.copy('../../app/templates/app/html/site/include/msgbox.html','./html/site/include/msgbox.html');
      this.copy('../../app/templates/app/html/site/include/tooltip.html','./html/site/include/tooltip.html');
      this.copy('../../app/templates/app/html/site/include/components.html','./html/site/include/components.html');
      this.copy('../../app/templates/app/html/site/include/download.html','./html/site/include/download.html');
      this.copy('../../app/templates/app/html/site/include/scripts-version.html','./html/site/include/scripts-version.html');
      this.copy('../../app/templates/app/html/site/include/styles-version.html','./html/site/include/styles-version.html');
    },
    other: function(){
      this.copy('../../app/templates/app/README.md', './README.md');
    }
  }
});
<|endoftext|>


<commit_before>// @flow

import PropTypes from 'prop-types';
import * as React from 'react';
import { View, ViewPropTypes, TouchableOpacity, TextInput } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

import { isLoggedIn } from 'lib/selectors/user-selectors';
import { connect } from 'lib/utils/redux-utils';

import type { AppState } from '../redux/redux-setup';
import {
  type Colors,
  colorsPropType,
  colorsSelector,
  styleSelector,
} from '../themes/colors';
import type { ViewStyle } from '../types/styles';

type Props = {|
  ...React.ElementConfig<typeof TextInput>,
  searchText: string,
  onChangeText: (searchText: string) => mixed,
  containerStyle?: ViewStyle,
  textInputRef?: React.Ref<typeof TextInput>,
  // Redux state
  colors: Colors,
  styles: typeof styles,
  loggedIn: boolean,
|};
class Search extends React.PureComponent<Props> {
  static propTypes = {
    searchText: PropTypes.string.isRequired,
    onChangeText: PropTypes.func.isRequired,
    containerStyle: ViewPropTypes.style,
    textInputRef: PropTypes.func,
    colors: colorsPropType.isRequired,
    styles: PropTypes.objectOf(PropTypes.object).isRequired,
    loggedIn: PropTypes.bool.isRequired,
  };

  componentDidUpdate(prevProps: Props) {
    if (!this.props.loggedIn && prevProps.loggedIn) {
      this.clearSearch();
    }
  }

  render() {
    const {
      searchText,
      onChangeText,
      containerStyle,
      textInputRef,
      colors,
      styles,
      loggedIn,
      ...rest
    } = this.props;
    const { listSearchIcon: iconColor } = colors;

    let clearSearchInputIcon = null;
    if (searchText) {
      clearSearchInputIcon = (
        <TouchableOpacity onPress={this.clearSearch} activeOpacity={0.5}>
          <Icon name="times-circle" size={18} color={iconColor} />
        </TouchableOpacity>
      );
    }

    const textInputProps: React.ElementProps<typeof TextInput> = {
      style: styles.searchInput,
      value: searchText,
      onChangeText: onChangeText,
      placeholderTextColor: iconColor,
      returnKeyType: 'go',
    };

    return (
      <View style={[this.props.styles.search, containerStyle]}>
        <Icon name="search" size={18} color={iconColor} />
        <TextInput {...textInputProps} {...rest} ref={textInputRef} />
        {clearSearchInputIcon}
      </View>
    );
  }

  clearSearch = () => {
    this.props.onChangeText('');
  };
}

const styles = {
  search: {
    alignItems: 'center',
    backgroundColor: 'listSearchBackground',
    borderRadius: 6,
    flexDirection: 'row',
    paddingLeft: 14,
    paddingRight: 12,
    paddingVertical: 6,
  },
  searchInput: {
    color: 'listForegroundLabel',
    flex: 1,
    fontSize: 16,
    marginLeft: 8,
    marginVertical: 0,
    padding: 0,
    borderBottomColor: 'transparent',
  },
};
const stylesSelector = styleSelector(styles);

const ConnectedSearch = connect((state: AppState) => ({
  colors: colorsSelector(state),
  styles: stylesSelector(state),
  loggedIn: isLoggedIn(state),
}))(Search);

type ConnectedProps = $Diff<
  Props,
  {|
    colors: Colors,
    styles: typeof styles,
    loggedIn: boolean,
  |},
>;
export default React.forwardRef<ConnectedProps, typeof TextInput>(
  function ForwardedConnectedSearch(
    props: ConnectedProps,
    ref: React.Ref<typeof TextInput>,
  ) {
    return <ConnectedSearch {...props} textInputRef={ref} />;
  },
);
<commit_msg>[native] Use hook instead of connect in Search<commit_after>// @flow

import * as React from 'react';
import { View, TouchableOpacity, TextInput } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

import { isLoggedIn } from 'lib/selectors/user-selectors';

import { useSelector } from '../redux/redux-utils';
import { useStyles, useColors } from '../themes/colors';
import type { ViewStyle } from '../types/styles';

type Props = {|
  ...React.ElementConfig<typeof TextInput>,
  +searchText: string,
  +onChangeText: (searchText: string) => mixed,
  +containerStyle?: ViewStyle,
|};
const Search = React.forwardRef<Props, typeof TextInput>(
  function ForwardedSearch(props: Props, ref: React.Ref<typeof TextInput>) {
    const { onChangeText, searchText, containerStyle, ...rest } = props;

    const clearSearch = React.useCallback(() => {
      onChangeText('');
    }, [onChangeText]);

    const loggedIn = useSelector(isLoggedIn);
    const styles = useStyles(unboundStyles);
    const colors = useColors();
    const prevLoggedInRef = React.useRef();
    React.useEffect(() => {
      const prevLoggedIn = prevLoggedInRef.current;
      prevLoggedInRef.current = loggedIn;
      if (!loggedIn && prevLoggedIn) {
        clearSearch();
      }
    }, [loggedIn, clearSearch]);

    const { listSearchIcon: iconColor } = colors;

    let clearSearchInputIcon = null;
    if (searchText) {
      clearSearchInputIcon = (
        <TouchableOpacity onPress={clearSearch} activeOpacity={0.5}>
          <Icon name="times-circle" size={18} color={iconColor} />
        </TouchableOpacity>
      );
    }

    const textInputProps: React.ElementProps<typeof TextInput> = {
      style: styles.searchInput,
      value: searchText,
      onChangeText: onChangeText,
      placeholderTextColor: iconColor,
      returnKeyType: 'go',
    };

    return (
      <View style={[styles.search, containerStyle]}>
        <Icon name="search" size={18} color={iconColor} />
        <TextInput {...textInputProps} {...rest} ref={ref} />
        {clearSearchInputIcon}
      </View>
    );
  },
);

const unboundStyles = {
  search: {
    alignItems: 'center',
    backgroundColor: 'listSearchBackground',
    borderRadius: 6,
    flexDirection: 'row',
    paddingLeft: 14,
    paddingRight: 12,
    paddingVertical: 6,
  },
  searchInput: {
    color: 'listForegroundLabel',
    flex: 1,
    fontSize: 16,
    marginLeft: 8,
    marginVertical: 0,
    padding: 0,
    borderBottomColor: 'transparent',
  },
};

export default React.memo<Props>(Search);
<|endoftext|>


<commit_before>var toggled = true;
function toggleSideBar() {
	$("#wrapper").toggleClass("toggled");
	toggled = toggled ? false : true;
}
function registerEventHanglers() {
	document.onmousemove=function(e) {
		if (e.pageX<=40) {
			if (!toggled) {
				toggleSideBar();
			}
		}
	};
	$("#sidebar-wrapper").mouseleave(toggleSideBar);
}
$(document).ready(function() {
	registerEventHanglers();
});<commit_msg>sidebar closed by default<commit_after>var toggled = false;
function toggleSideBar() {
	$("#wrapper").toggleClass("toggled");
	toggled = toggled ? false : true;
}
function registerEventHanglers() {
	document.onmousemove=function(e) {
		if (e.pageX<=40) {
			if (!toggled) {
				toggleSideBar();
			}
		}
	};
	$("#sidebar-wrapper").mouseleave(toggleSideBar);
}
$(document).ready(function() {
	$("#wrapper").toggleClass("toggled");
	registerEventHanglers();
});<|endoftext|>


<commit_before>var sys = require("sys");
var fs = require("fs");
var events = require("events");
var dns = require('dns');

var Buffer = require('buffer').Buffer;
var IOWatcher    = process.IOWatcher;
var binding      = process.binding('net');
var socket       = binding.socket;
var bind         = binding.bind;
var recvfrom     = binding.recvfrom;
var sendto       = binding.sendto;
var close        = binding.close;
var ENOENT       = binding.ENOENT;
var setBroadcast = binding.setBroadcast;

function isPort (x) { return parseInt(x) >= 0; }
var pool = null;

function getPool() {
  /* TODO: this effectively limits you to 8kb maximum packet sizes */
  var minPoolAvail = 1024 * 8;

  var poolSize = 1024 * 64;

  if (pool === null || (pool.used + minPoolAvail  > pool.length)) {
    pool = new Buffer(poolSize);
    pool.used = 0;
  }

  return pool;
}

function Socket (broadcast, listener) {
  events.EventEmitter.call(this);
  var self = this;

  if (typeof(broadcast) != 'boolean') {
    listener = broadcast;
    broadcast = false;
  }
  self.broadcast = broadcast;

  if (listener) {
    self.addListener('message', listener);
  }

  self.watcher = new IOWatcher();
  self.watcher.host = self;
  self.watcher.callback = function () {
    while (self.fd) {
      var p = getPool();
      var rinfo = recvfrom(self.fd, p, p.used, p.length - p.used, 0);

      if (!rinfo) return;
      //sys.error(sys.inspect(p.slice(p.used, p.used + rinfo.size)));
      self.emit('message', p.slice(p.used, p.used + rinfo.size), rinfo);

      p.used += rinfo.size;
    }
  };
}

sys.inherits(Socket, events.EventEmitter);
exports.Socket = Socket;

exports.createSocket = function (broadcast, listener) {
  return new Socket(broadcast, listener);
};

Socket.prototype.bind = function () {
  var self = this;
  if (self.fd) throw new Error('Server already opened');

  if (!isPort(arguments[0])) {
    /* TODO: unix path dgram */
    self.fd = socket('unix_dgram');
    self.type = 'unix_dgram';
    var path = arguments[0];
    self.path = path;
    // unlink sockfile if it exists
    fs.stat(path, function (err, r) {
      if (err) {
        if (err.errno == ENOENT) {
          bind(self.fd, path);
          process.nextTick(function() {
            self._startWatcher();
          });
        } else {
          throw r;
        }
      } else {
        if (!r.isFile()) {
          throw new Error("Non-file exists at  " + path);
        } else {
          fs.unlink(path, function (err) {
            if (err) {
              throw err;
            } else {
              bind(self.fd, path);
              process.nextTick(function() {
                self._startWatcher();
              });
            }
          });
        }
      }
    });
  } else if (!arguments[1]) {
    // Don't bind(). OS will assign a port with INADDR_ANY.
    // The port can be found with server.address()
    self.type = 'udp4';
    self.fd = socket(self.type);
    bind(self.fd, arguments[0]);
    process.nextTick(function() {
      self._startWatcher();
    });
  } else {
    // the first argument is the port, the second an IP
    var port = arguments[0];
    dns.lookup(arguments[1], function (err, ip, addressType) {
      if (err) {
        self.emit('error', err);
      } else {
        self.type = addressType == 4 ? 'udp4' : 'udp6';
        self.fd = socket(self.type);
        bind(self.fd, port, ip);
        process.nextTick(function() {
          self._startWatcher();
        });
      }
    });
  }
};

Socket.prototype._startWatcher = function () {
  this.watcher.set(this.fd, true, false);
  this.watcher.start();
  this.emit("listening");
};

Socket.prototype.address = function () {
  return getsockname(this.fd);
};

Socket.prototype.send = function(port, addr, buffer, offset, length) {
  var self = this;

  var lastArg = arguments[arguments.length - 1];
  var callback = typeof lastArg === 'function' ? lastArg : null;

  if (!isPort(arguments[0])) {
    try {
      if (!self.fd) {
        self.type = 'unix_dgram';
        self.fd = socket(self.type);
      }
      var bytes = sendto(self.fd, buffer, offset, length, 0, port, addr);
    } catch (e) {
      if (callback) callback(e);
      return;
    }

    if (callback) callback(null, bytes);

  } else {
    dns.lookup(arguments[1], function (err, ip, addressType) {
      // DNS error
      if (err) {
        if (callback) callback(err);
        self.emit('error', err);
        return;
      }

      try {
        if (!self.fd) {
          self.type = addressType == 4 ? 'udp4' : 'udp6';
          self.fd = socket(self.type);
          setBroadcast(self.fd, self.broadcast);
          process.nextTick(function() {
            self._startWatcher();
          });
        }
        var bytes = sendto(self.fd, buffer, offset, length, 0, port, ip);
      } catch (err) {
        // socket creation, or sendto error.
        if (callback) callback(err);
        return;
      }

      if (callback) callback(null, bytes);
    });
  }
};

Socket.prototype.close = function () {
  var self = this;

  if (!self.fd) throw new Error('Not running');

  self.watcher.stop();

  close(self.fd);
  self.fd = null;

  if (self.type === "unix_dgram") {
    fs.unlink(self.path, function () {
      self.emit("close");
    });
  } else {
    self.emit("close");
  }
};

<commit_msg>removing testint dgram<commit_after><|endoftext|>


<commit_before>/**
 * Component for rendering need-title, type and timestamp
 * Created by ksinger on 10.04.2017.
 */
import angular from "angular";
import "ng-redux";
import squareImageModule from "./square-image.js";
import { actionCreators } from "../actions/actions.js";
import { relativeTime } from "../won-label-utils.js";
import { attach, getIn } from "../utils.js";
import { connect2Redux } from "../won-utils.js";
import { selectLastUpdateTime } from "../selectors/general-selectors.js";
import won from "../won-es6.js";
import { classOnComponentRoot } from "../cstm-ng-utils.js";
import { generateNeedTypesLabel, isDirectResponseNeed } from "../need-utils.js";

import "style/_post-header.scss";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

    <won-square-image
        ng-if="!self.isLoading()"
        ng-class="{'bigger' : self.biggerImage, 'inactive' : !self.need.get('isBeingCreated') && self.need.get('state') === self.WON.InactiveCompacted}"
        src="self.need.get('TODO')"
        uri="self.needUri"
        ng-show="!self.hideImage">
    </won-square-image>

         {{ self.generateTitle() }}

          RE: no title

          no title

          {{ self.generateNeedTypesLabel(self.need) }}

          {{ self.friendlyTimestamp }}

          Creating...

          {{ self.generateNeedTypesLabel(self.need) }}

    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      window.ph4dbg = this;
      this.generateNeedTypesLabel = generateNeedTypesLabel;
      this.WON = won.WON;
      const selectFromState = state => {
        const need = getIn(state, ["needs", this.needUri]);
        const isDirectResponse = isDirectResponseNeed(need);
        const responseToUri =
          isDirectResponse && getIn(need, ["content", "responseToUri"]);
        const responseToNeed =
          responseToUri && getIn(state, ["needs", responseToUri]);

        return {
          responseToNeed,
          need,
          isDirectResponse: isDirectResponse,
          friendlyTimestamp:
            need &&
            relativeTime(
              selectLastUpdateTime(state),
              need.get("lastUpdateDate")
            ),
        };
      };

      connect2Redux(
        selectFromState,
        actionCreators,
        ["self.needUri", "self.timestamp"],
        this
      );

      classOnComponentRoot("won-is-loading", () => this.isLoading(), this);
      classOnComponentRoot("won-is-toload", () => this.isToLoad(), this);
    }

    isLoading() {
      return !this.need || this.need.get("isLoading");
    }
    isToLoad() {
      return !this.need || this.need.get("toLoad");
    }

    hasTitle() {
      if (this.isDirectResponse && this.responseToNeed) {
        return !!this.responseToNeed.get("humanReadable");
      } else {
        return !!this.need.get("humanReadable");
      }
    }

    generateTitle() {
      if (this.isDirectResponse && this.responseToNeed) {
        return "Re: " + this.responseToNeed.get("humanReadable");
      } else {
        return this.need.get("humanReadable");
      }
    }
  }
  Controller.$inject = serviceDependencies;
  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      needUri: "=",

      /**
       * Will be used instead of the posts creation date if specified.
       * Use if you e.g. instead want to show the date when a request was made.
       */
      timestamp: "=",
      /**
       * one of:
       * - "fullpage" (NOT_YET_IMPLEMENTED) (used in post-info page)
       * - "medium" (NOT_YET_IMPLEMENTED) (used in incoming/outgoing requests)
       * - "small" (NOT_YET_IMPLEMENTED) (in matches-list)
       */
      //size: '=',

      /**
       * if set, the avatar will be hidden
       */
      hideImage: "=",

      /**
       * If true, the title image will be a bit bigger. This
       * can be used to create visual contrast.
       */
      biggerImage: "=",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.postHeader", [squareImageModule])
  .directive("wonPostHeader", genComponentConf).name;
<commit_msg>Fixes Label mismatch<commit_after>/**
 * Component for rendering need-title, type and timestamp
 * Created by ksinger on 10.04.2017.
 */
import angular from "angular";
import "ng-redux";
import squareImageModule from "./square-image.js";
import { actionCreators } from "../actions/actions.js";
import { relativeTime } from "../won-label-utils.js";
import { attach, getIn } from "../utils.js";
import { connect2Redux } from "../won-utils.js";
import { selectLastUpdateTime } from "../selectors/general-selectors.js";
import won from "../won-es6.js";
import { classOnComponentRoot } from "../cstm-ng-utils.js";
import { generateNeedTypesLabel, isDirectResponseNeed } from "../need-utils.js";

import "style/_post-header.scss";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

    <won-square-image
        ng-if="!self.isLoading()"
        ng-class="{'bigger' : self.biggerImage, 'inactive' : !self.need.get('isBeingCreated') && self.need.get('state') === self.WON.InactiveCompacted}"
        src="self.need.get('TODO')"
        uri="self.needUri"
        ng-show="!self.hideImage">
    </won-square-image>

         {{ self.generateTitle() }}

          no title

          RE: no title

          {{ self.generateNeedTypesLabel(self.need) }}

          {{ self.friendlyTimestamp }}

          Creating...

          {{ self.generateNeedTypesLabel(self.need) }}

    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      window.ph4dbg = this;
      this.generateNeedTypesLabel = generateNeedTypesLabel;
      this.WON = won.WON;
      const selectFromState = state => {
        const need = getIn(state, ["needs", this.needUri]);
        const isDirectResponse = isDirectResponseNeed(need);
        const responseToUri =
          isDirectResponse && getIn(need, ["content", "responseToUri"]);
        const responseToNeed =
          responseToUri && getIn(state, ["needs", responseToUri]);

        return {
          responseToNeed,
          need,
          isDirectResponse: isDirectResponse,
          friendlyTimestamp:
            need &&
            relativeTime(
              selectLastUpdateTime(state),
              need.get("lastUpdateDate")
            ),
        };
      };

      connect2Redux(
        selectFromState,
        actionCreators,
        ["self.needUri", "self.timestamp"],
        this
      );

      classOnComponentRoot("won-is-loading", () => this.isLoading(), this);
      classOnComponentRoot("won-is-toload", () => this.isToLoad(), this);
    }

    isLoading() {
      return !this.need || this.need.get("isLoading");
    }
    isToLoad() {
      return !this.need || this.need.get("toLoad");
    }

    hasTitle() {
      if (this.isDirectResponse && this.responseToNeed) {
        return !!this.responseToNeed.get("humanReadable");
      } else {
        return !!this.need.get("humanReadable");
      }
    }

    generateTitle() {
      if (this.isDirectResponse && this.responseToNeed) {
        return "Re: " + this.responseToNeed.get("humanReadable");
      } else {
        return this.need.get("humanReadable");
      }
    }
  }
  Controller.$inject = serviceDependencies;
  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      needUri: "=",

      /**
       * Will be used instead of the posts creation date if specified.
       * Use if you e.g. instead want to show the date when a request was made.
       */
      timestamp: "=",
      /**
       * one of:
       * - "fullpage" (NOT_YET_IMPLEMENTED) (used in post-info page)
       * - "medium" (NOT_YET_IMPLEMENTED) (used in incoming/outgoing requests)
       * - "small" (NOT_YET_IMPLEMENTED) (in matches-list)
       */
      //size: '=',

      /**
       * if set, the avatar will be hidden
       */
      hideImage: "=",

      /**
       * If true, the title image will be a bit bigger. This
       * can be used to create visual contrast.
       */
      biggerImage: "=",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.postHeader", [squareImageModule])
  .directive("wonPostHeader", genComponentConf).name;
<|endoftext|>


<commit_before>/**
 *
 * Spinner
 *
 */

import React from 'react';
import CircularProgress from 'material-ui/CircularProgress';

import { accentColor } from '../../containers/App/muitheme'

import { Dimmer, Loader } from 'semantic-ui-react'

const styles = {
    spinner: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        height: '100%',
    },
    inlineSpinner: {
        display: 'inline',
        // justifyContent: 'center',
        // alignItems: 'center',
        // width: '100%',
        // height: '100%',
    },
}

export function Spinner({ size, style={} }) {
    return (
        <Loader active={true}/>
    )
}

export function InlineSpinner({ size, style={} }) {
    const myStyles = Object.assign({}, styles.inlineSpinner, style)
    return (
        <div style={myStyles}>
            <CircularProgress color={accentColor} size={size || 1.5} />
        </div>
    );
}

export default Spinner

<commit_msg>remove unused material-ui code<commit_after>/**
 *
 * Spinner
 *
 */

import React from 'react';

import { Dimmer, Loader } from 'semantic-ui-react'

export function Spinner({ size, style={} }) {
    return (
        <Loader active={true}/>
    )
}

export default Spinner

<|endoftext|>


<commit_before><commit_msg>update nimrod<commit_after><|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mailin = require('mailin');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

mailin.start({
  port: 25,
  disableWebhook: true // Disable the webhook posting.
});

/* Access simplesmtp server instance. */
mailin.on('authorizeUser', function(connection, username, password, done) {
  if (username == "johnsmith" && password == "mysecret") {
    done(null, true);
  } else {
    done(new Error("Unauthorized!"), false);
  }
});

/* Event emitted when a connection with the Mailin smtp server is initiated. */
mailin.on('startMessage', function (connection) {
  /* connection = {
      from: 'sender@somedomain.com',
      to: 'someaddress@yourdomain.com',
      id: 't84h5ugf',
      authentication: { username: null, authenticated: false, status: 'NORMAL' }
  }
  }; */
  console.log(connection);
});

/* Event emitted after a message was received and parsed. */
mailin.on('message', function (connection, data, content) {
  console.log(data);
  console.log(content.length);
  /* Do something useful with the parsed message here.
   * Use parsed message `data` directly or use raw message `content`. */
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

app.listen(80);<commit_msg>Updated unpacking message<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mailin = require('mailin');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

mailin.start({
  port: 25,
  disableWebhook: true // Disable the webhook posting.
});

/* Access simplesmtp server instance. */
mailin.on('authorizeUser', function(connection, username, password, done) {
  if (username == "johnsmith" && password == "mysecret") {
    done(null, true);
  } else {
    done(new Error("Unauthorized!"), false);
  }
});

/* Event emitted when a connection with the Mailin smtp server is initiated. */
mailin.on('startMessage', function (connection) {
  /* connection = {
      from: 'sender@somedomain.com',
      to: 'someaddress@yourdomain.com',
      id: 't84h5ugf',
      authentication: { username: null, authenticated: false, status: 'NORMAL' }
  }
  }; */
  console.log(connection);
});

/* Event emitted after a message was received and parsed. */
mailin.on('message', function (connection, data, content) {
  console.log(data);
  console.log(data.text.length);
  /* Do something useful with the parsed message here.
   * Use parsed message `data` directly or use raw message `content`. */
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

app.listen(80);<|endoftext|>


<commit_before>var path = require('path');
var http = require('http');
var express = require('express');
var compression = require('compression');
var bodyParser = require('body-parser');
var printf = require('printf');
var open = require('open');

var apps = require('../apps');

var ip = require('../util/ip');
var logging = require('../util/logging');

var config = require('../config');
var jvmtools = require('../jvmtools');

var appRoutes = require('./appRoutes');

var logger = logging.get('serve');

var Z_BEST_COMPRESSION = 9;

// launches the web server
exports.serveWeb = function (opts, cb) {
  var port = opts.port;

  // common.track("BasilServe");
  var app = express();
  var server = http.Server(app);

  app.io = require('socket.io')(server);

  // var deviceManager = require('./deviceManager').get();
  // deviceManager.init(app.io);

  app.use(compression({level: Z_BEST_COMPRESSION}));

  app.use(function noCacheControl(req, res, next) {
    res.header('Cache-Control', 'no-cache');
    res.header('Expires', '-1');
    next();
  });

  app.use('/api/', getAPIRouter(merge({
    app: app
  }, opts)));

  // serve static files
  app.use('/', express.static(getPath('static')));

  // Serve
  server.listen(port, function () {
    if (opts.testApp) {
      exports.serveTestApp(port);
    }

    logger.log(printf('serving at http://localhost:%(port)s/ and '
      + 'http://%(ip)s:%(port)s/', {
          ip: ip.getLocalIP(),
          port: port
        }));

    config.startWatch();

    cb && cb();
  }).on('error', function (e) {
    console.log(e);
    if (e.code === 'EADDRINUSE') {
      cb && cb(e);
      cb = null;
    }
  });
};

exports.serveTestApp = function (port) {
  // Launch multicast server (only on OS X for now)
  var addresses = ip.getLocalIP();
  var address = addresses[0];
  if (address) {
    var hostname = require('os').hostname();
    jvmtools.exec({
      tool: 'jmdns',
      args: [
        '-rs', hostname, 'devkit._tcp', 'local', port
      ]
    }, function (err, stdout, stderr) {
    });
  }
};

function getAPIRouter(opts) {

  var api = express();
  var deviceTypes = require('../util/deviceTypes');

  api.get('/devices', function (req, res) {
    res.json(deviceTypes);
  });

  api.get('/app', function (req, res) {
    var appPath = req.query.app;
    apps.get(appPath, {updateLastOpened: false}, function (err, app) {
      res.json(app);
    });
  });

  api.get('/apps', function (req, res) {
    var reload = req.query.reload;
    apps.getApps(function (err, apps) {
      if (reload) {
        for (var appPath in apps) {
          apps[appPath].reloadSync();
        }
      }

      if (err) {
        res.status(404).send(err);
      } else {
        res.json(apps);
      }
    });
  });

  api.get('/openAppExternal', function (req, res) {
    apps.get(req.query.app, {updateLastOpened: false}, function (err, app) {
      if (app) {
        // Used open package to
        open(app.paths.root);
      }

      res.status(200).send();
    });

  });

  api.get('/title', function (req, res) {
    var appPath = req.query.app;
    apps.get(appPath, {updateLastOpened: false}, function (err, app) {
      if (err) { return res.status(404).send(err); }

      // TODO: localized titles?
      res.status(200).send(app.manifest.title);
    });
  });

  api.get('/icon', function (req, res) {
    var appPath = req.query.app;
    apps.get(appPath, {updateLastOpened: false}, function (err, app) {
      if (err) { return res.status(404).send(err); }
      var iconFile = app.getIcon(req.query.targetSize || 512);
      var iconPath = path.join(app.paths.root, iconFile);
      res.sendFile(iconPath);
    });
  });

  api.get('/manifest', function (req, res) {
    var appPath = req.query.app;
    apps.get(appPath, {updateLastOpened: false}, function (err, app) {
      if (err) { return res.status(404).send(err); }
      res.send(app.manifest);
    });
  });

  api.get('/upgrade', function (req, res) {
    apps.get(req.query.app, {updateLastOpened: false}, function (err, app) {
      var module = req.query.module || 'devkit-core';
      var version = req.query.version || 'latest';
      require('../install').installModule(app, module, {version: version}, function (err, result) {
        if (err) {
          console.log(err.stack);
          res.status(500).send(err.message);
        } else {
          res.status(200).send(result);
        }
      });
    });
  });

  api.get('/home', function (req, res) {
    res.json({path: process.env.HOME
      || process.env.HOMEPATH
      || process.env.USERPROFILE});
  });

  // gets the ip of the server.
  // usage: make a GET request to /api/ip
  api.get('/ip', function (req, res) {
    res.json({ip: ip.getLocalIP()});
  });

  // a better js syntax checker
  api.use('/syntax', bodyParser.urlencoded({extended: true}));
  api.post('/syntax', function(req, res) {
    jvmtools.checkSyntax(req.body.javascript, function (err, syntaxErrors) {
      if (err) {
        res.send([false, err]);
      } else {
        res.send([true, syntaxErrors]);
      }
    });
  });

  appRoutes.addToAPI(opts, api);

  return api;
}

function getPath() {
  var args = [__dirname].concat(Array.prototype.slice.call(arguments));
  return path.join.apply(path, args);
}
<commit_msg>remove serve jvmtools deps<commit_after>var path = require('path');
var http = require('http');
var express = require('express');
var compression = require('compression');
var bodyParser = require('body-parser');
var printf = require('printf');
var open = require('open');

var apps = require('../apps');

var ip = require('../util/ip');
var logging = require('../util/logging');

var config = require('../config');

var appRoutes = require('./appRoutes');

var logger = logging.get('serve');

var Z_BEST_COMPRESSION = 9;

// launches the web server
exports.serveWeb = function (opts, cb) {
  var port = opts.port;

  // common.track("BasilServe");
  var app = express();
  var server = http.Server(app);

  app.io = require('socket.io')(server);

  // var deviceManager = require('./deviceManager').get();
  // deviceManager.init(app.io);

  app.use(compression({level: Z_BEST_COMPRESSION}));

  app.use(function noCacheControl(req, res, next) {
    res.header('Cache-Control', 'no-cache');
    res.header('Expires', '-1');
    next();
  });

  app.use('/api/', getAPIRouter(merge({
    app: app
  }, opts)));

  // serve static files
  app.use('/', express.static(getPath('static')));

  // Serve
  server.listen(port, function () {
    logger.log(printf('serving at http://localhost:%(port)s/ and '
      + 'http://%(ip)s:%(port)s/', {
          ip: ip.getLocalIP(),
          port: port
        }));

    config.startWatch();

    cb && cb();
  }).on('error', function (e) {
    console.log(e);
    if (e.code === 'EADDRINUSE') {
      cb && cb(e);
      cb = null;
    }
  });
};

function getAPIRouter(opts) {

  var api = express();
  var deviceTypes = require('../util/deviceTypes');

  api.get('/devices', function (req, res) {
    res.json(deviceTypes);
  });

  api.get('/app', function (req, res) {
    var appPath = req.query.app;
    apps.get(appPath, {updateLastOpened: false}, function (err, app) {
      res.json(app);
    });
  });

  api.get('/apps', function (req, res) {
    var reload = req.query.reload;
    apps.getApps(function (err, apps) {
      if (reload) {
        for (var appPath in apps) {
          apps[appPath].reloadSync();
        }
      }

      if (err) {
        res.status(404).send(err);
      } else {
        res.json(apps);
      }
    });
  });

  api.get('/openAppExternal', function (req, res) {
    apps.get(req.query.app, {updateLastOpened: false}, function (err, app) {
      if (app) {
        // Used open package to
        open(app.paths.root);
      }

      res.status(200).send();
    });

  });

  api.get('/title', function (req, res) {
    var appPath = req.query.app;
    apps.get(appPath, {updateLastOpened: false}, function (err, app) {
      if (err) { return res.status(404).send(err); }

      // TODO: localized titles?
      res.status(200).send(app.manifest.title);
    });
  });

  api.get('/icon', function (req, res) {
    var appPath = req.query.app;
    apps.get(appPath, {updateLastOpened: false}, function (err, app) {
      if (err) { return res.status(404).send(err); }
      var iconFile = app.getIcon(req.query.targetSize || 512);
      var iconPath = path.join(app.paths.root, iconFile);
      res.sendFile(iconPath);
    });
  });

  api.get('/manifest', function (req, res) {
    var appPath = req.query.app;
    apps.get(appPath, {updateLastOpened: false}, function (err, app) {
      if (err) { return res.status(404).send(err); }
      res.send(app.manifest);
    });
  });

  api.get('/upgrade', function (req, res) {
    apps.get(req.query.app, {updateLastOpened: false}, function (err, app) {
      var module = req.query.module || 'devkit-core';
      var version = req.query.version || 'latest';
      require('../install').installModule(app, module, {version: version}, function (err, result) {
        if (err) {
          console.log(err.stack);
          res.status(500).send(err.message);
        } else {
          res.status(200).send(result);
        }
      });
    });
  });

  api.get('/home', function (req, res) {
    res.json({path: process.env.HOME
      || process.env.HOMEPATH
      || process.env.USERPROFILE});
  });

  // gets the ip of the server.
  // usage: make a GET request to /api/ip
  api.get('/ip', function (req, res) {
    res.json({ip: ip.getLocalIP()});
  });

  appRoutes.addToAPI(opts, api);

  return api;
}

function getPath() {
  var args = [__dirname].concat(Array.prototype.slice.call(arguments));
  return path.join.apply(path, args);
}
<|endoftext|>


<commit_before>angular.module('reply', [])
.directive('myReply', function(MessageService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {

                var feedid = scope.feedid;
                MessageService.fetch_messages('msg');
                MessageService.register_reply_message();

                MessageService.get_replybody(feedid);
                MessageService.register_replybody();

                $('div#reply-to-user').draggable();
                $('div#reply-to-user.lightbox').show();

                $(".dialog-form[feedid="+feedid+"]").show();

                e.preventDefault();

            });
        }
    }
})
.directive('replyCancel', function(MessageService){
    return function($scope, element, attrs){
        $(element).bind('click', function(e) {

            var choice = $(this).attr('value');

            $scope.$apply(function() {
                $scope.template = { name: "reply_form", url: "/feedback/load_reply_form" };
            });

            if(choice == 'Cancel') {
                $('textarea[name=bcc]').clearFields();
                $('textarea[name=message]').clearFields();
                $(this).parents(".dialog-form").fadeOut();
                $('div#reply-to-user').draggable("destroy");
                $(".reply_cancel_button").val("Cancel");
            }

            if(choice == 'Back') {
                $(".reply_cancel_button").val("Cancel");
            }

            $(".reply_send_button").val("Send");

            MessageService.fetch_messages('msg');
            MessageService.register_reply_message();

            e.preventDefault();
        });
    }
})
.directive('replySend', function(MessageService) {
    return {
        restrict: 'A'
      , link: function($scope, element, attrs) {
            $(element).bind('click', function(e) {

                var choice = $(this).attr('value');

                if(choice == 'Save') {

                    if($('#mymessage').val() == "") {
                        $('#mymessage').css({
                            'border': '1px solid red'
                        })
                    } else {

                        $('#mymessage').removeAttr('style');

                        MessageService.save(MessageService.msgdata);

                        var msgtype = MessageService.msgdata.msgtype;

                        if(msgtype == 'msg') {
                            MessageService.fetch_messages(msgtype);
                            MessageService.register_reply_message();
                        }

                        $scope.$apply(function() {
                            $scope.template = { name: "reply_form", url: "/feedback/load_reply_form" };
                        });
                    }
                }

                if(choice == 'Send') {
                    var data = $('form.reply-form').serializeForm();
                    if($('#email_message').val() == "") {
                        $('#email_message').css({
                            'border': '1px solid red'
                        })
                    } else {
                        $('#email_message').removeAttr('style');
                        MessageService.send_email(data, function() {
                            alert("Email Sent!");
                            $('textarea[name=bcc]').clearFields();
                            $('textarea[name=message]').clearFields();
                            $(".dialog-form").fadeOut();
                            $('div#reply-to-user').draggable("destroy");
                            $(".reply_cancel_button").val("Cancel");
                        });
                    }

                }

                $(".reply_cancel_button").val("Cancel");
                $(".reply_send_button").val("Send");
                e.preventDefault();
            });
        }
    }
})
.directive('addReply', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var quickmessage = $(this).attr('req-text');
                var textarea = $("textarea[name=message]");
                textarea.val(quickmessage);
                e.preventDefault();
            });
        }
    }
})
.directive('deleteReply', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(this).parents('li').remove();
                e.preventDefault();
            })
        }
    }
})
.directive('editReply', function() {
    return {
        restrict: 'A'
      , link: function($scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".reply_send_button").val("Save");
                $(".reply_cancel_button").val("Back");
                e.preventDefault();
            })
        }
    }
})
.directive('configureReply', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(".reply_send_button").val("Save");
                $(".reply_cancel_button").val("Back");
                e.preventDefault();
            })
        }
    }
})
.directive('bcc', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var feedid = $(this).attr('feedid');
                var email = $(this).attr('email');
                var textarea = $('textarea[name=bcc][feedid=' + feedid + ']');
                var values = textarea.val() + email + ',';

                textarea.val(values);
                e.preventDefault();
            });

        }
    }
})
.directive('editReplySettings', function(MessageService) {
    return {
        restrict: 'A'
      , scope: {
            msgid: '=msgid'
          , action: '@action'
        }
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {

                var deselect_this = false;

                var id = scope.msgid;
                var action = scope.action;

                var me = $(this);

                console.log(me.parents("div.g1of3").siblings().children("textarea").each());

                /*
                if(!deselect_this) {
                    me.attr('style', "background: #cd5555");
                }
                */

                var input = $("textarea#" + id + ".dashboard-text");
                //input.autoGrow();
                var span = $("span#" + id + ".replymsg-text");

                if(action == 'edit') {
                    var sib = me.next();
                } else {
                    var sib = me.prev();
                }

                if(action == 'edit') {
                    me.hide();
                    sib.show();
                    input.show();
                    span.hide();
                } else {

                    if(input.val() == "") {
                        alert("Please provide a reply message.");
                    } else {
                        me.hide();
                        sib.show();
                        input.hide();
                        span.show();

                        var data = { 'msgtype': 'msg', 'id': id, 'text': input.val() };
                        MessageService.save(data);
                        span.html(MessageService.pushdata.short_text);
                    }

                }
                e.preventDefault();
            });
        }
    }
})
<commit_msg>selling<commit_after>angular.module('reply', [])
.directive('myReply', function(MessageService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {

                var feedid = scope.feedid;
                MessageService.fetch_messages('msg');
                MessageService.register_reply_message();

                MessageService.get_replybody(feedid);
                MessageService.register_replybody();

                $('div#reply-to-user').draggable();
                $('div#reply-to-user.lightbox').show();

                $(".dialog-form[feedid="+feedid+"]").show();

                e.preventDefault();

            });
        }
    }
})
.directive('replyCancel', function(MessageService){
    return function($scope, element, attrs){
        $(element).bind('click', function(e) {

            var choice = $(this).attr('value');

            $scope.$apply(function() {
                $scope.template = { name: "reply_form", url: "/feedback/load_reply_form" };
            });

            if(choice == 'Cancel') {
                $('textarea[name=bcc]').clearFields();
                $('textarea[name=message]').clearFields();
                $(this).parents(".dialog-form").fadeOut();
                $('div#reply-to-user').draggable("destroy");
                $(".reply_cancel_button").val("Cancel");
            }

            if(choice == 'Back') {
                $(".reply_cancel_button").val("Cancel");
            }

            $(".reply_send_button").val("Send");

            MessageService.fetch_messages('msg');
            MessageService.register_reply_message();

            e.preventDefault();
        });
    }
})
.directive('replySend', function(MessageService) {
    return {
        restrict: 'A'
      , link: function($scope, element, attrs) {
            $(element).bind('click', function(e) {

                var choice = $(this).attr('value');

                if(choice == 'Save') {

                    if($('#mymessage').val() == "") {
                        $('#mymessage').css({
                            'border': '1px solid red'
                        })
                    } else {

                        $('#mymessage').removeAttr('style');

                        MessageService.save(MessageService.msgdata);

                        var msgtype = MessageService.msgdata.msgtype;

                        if(msgtype == 'msg') {
                            MessageService.fetch_messages(msgtype);
                            MessageService.register_reply_message();
                        }

                        $scope.$apply(function() {
                            $scope.template = { name: "reply_form", url: "/feedback/load_reply_form" };
                        });
                    }
                }

                if(choice == 'Send') {
                    var data = $('form.reply-form').serializeForm();
                    if($('#email_message').val() == "") {
                        $('#email_message').css({
                            'border': '1px solid red'
                        })
                    } else {
                        $('#email_message').removeAttr('style');
                        MessageService.send_email(data, function() {
                            alert("Email Sent!");
                            $('textarea[name=bcc]').clearFields();
                            $('textarea[name=message]').clearFields();
                            $(".dialog-form").fadeOut();
                            $('div#reply-to-user').draggable("destroy");
                            $(".reply_cancel_button").val("Cancel");
                        });
                    }

                }

                $(".reply_cancel_button").val("Cancel");
                $(".reply_send_button").val("Send");
                e.preventDefault();
            });
        }
    }
})
.directive('addReply', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var quickmessage = $(this).attr('req-text');
                var textarea = $("textarea[name=message]");
                textarea.val(quickmessage);
                e.preventDefault();
            });
        }
    }
})
.directive('deleteReply', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(this).parents('li').remove();
                e.preventDefault();
            })
        }
    }
})
.directive('editReply', function() {
    return {
        restrict: 'A'
      , link: function($scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".reply_send_button").val("Save");
                $(".reply_cancel_button").val("Back");
                e.preventDefault();
            })
        }
    }
})
.directive('configureReply', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(".reply_send_button").val("Save");
                $(".reply_cancel_button").val("Back");
                e.preventDefault();
            })
        }
    }
})
.directive('bcc', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var feedid = $(this).attr('feedid');
                var email = $(this).attr('email');
                var textarea = $('textarea[name=bcc][feedid=' + feedid + ']');
                var values = textarea.val() + email + ',';

                textarea.val(values);
                e.preventDefault();
            });

        }
    }
})
.directive('editReplySettings', function(MessageService) {
    return {
        restrict: 'A'
      , scope: {
            msgid: '=msgid'
          , action: '@action'
        }
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {

                var deselect_this = false;

                var id = scope.msgid;
                var action = scope.action;

                var me = $(this);

                console.log(me.parents("div.g1of3").siblings().children("textarea"));

                /*
                if(!deselect_this) {
                    me.attr('style', "background: #cd5555");
                }
                */

                var input = $("textarea#" + id + ".dashboard-text");
                //input.autoGrow();
                var span = $("span#" + id + ".replymsg-text");

                if(action == 'edit') {
                    var sib = me.next();
                } else {
                    var sib = me.prev();
                }

                if(action == 'edit') {
                    me.hide();
                    sib.show();
                    input.show();
                    span.hide();
                } else {

                    if(input.val() == "") {
                        alert("Please provide a reply message.");
                    } else {
                        me.hide();
                        sib.show();
                        input.hide();
                        span.show();

                        var data = { 'msgtype': 'msg', 'id': id, 'text': input.val() };
                        MessageService.save(data);
                        span.html(MessageService.pushdata.short_text);
                    }

                }
                e.preventDefault();
            });
        }
    }
})
<|endoftext|>


<commit_before>/*global module */
module.exports = function( grunt ) {
    'use strict';

    grunt.initConfig({
        meta: {
          version: '2.6.2pre',
          banner: '/*!\n' +
            ' * Modernizr v<%= meta.version %>\n' +
            ' * www.modernizr.com\n *\n' +
            ' * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton\n' +
            ' * Available under the BSD and MIT licenses: www.modernizr.com/license/\n */'
        },
        qunit: {
            files: ['test/index.html']
        },
        lint: {
            files: [
                'grunt.js',
                'modernizr.js',
                'feature-detects/*.js'
            ]
        },
        min: {
            dist: {
                src: [
                    '<banner:meta.banner>',
                    'modernizr.js'
                ],
                dest: 'modernizr.min.js'
            }
        },
        watch: {
            files: '<config:lint.files>',
            tasks: 'lint'
        },
        jshint: {
            options: {
                boss: true,
                browser: true,
                curly: false,
                devel: true,
                eqeqeq: false,
                eqnull: true,
                expr: true,
                evil: true,
                immed: false,
                laxcomma: true,
                newcap: false,
                noarg: true,
                smarttabs: true,
                sub: true,
                undef: true
            },
            globals: {
                Modernizr: true,
                DocumentTouch: true,
                TEST: true,
                SVGFEColorMatrixElement : true,
                Blob: true
            }
        }
    });

    grunt.registerTask('default', 'min');

    // Travis CI task.
    grunt.registerTask('travis', 'qunit');
};
<commit_msg>bump 2.6.3pre on grunt<commit_after>/*global module */
module.exports = function( grunt ) {
    'use strict';

    grunt.initConfig({
        meta: {
          version: '2.6.3pre',
          banner: '/*!\n' +
            ' * Modernizr v<%= meta.version %>\n' +
            ' * www.modernizr.com\n *\n' +
            ' * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton\n' +
            ' * Available under the BSD and MIT licenses: www.modernizr.com/license/\n */'
        },
        qunit: {
            files: ['test/index.html']
        },
        lint: {
            files: [
                'grunt.js',
                'modernizr.js',
                'feature-detects/*.js'
            ]
        },
        min: {
            dist: {
                src: [
                    '<banner:meta.banner>',
                    'modernizr.js'
                ],
                dest: 'modernizr.min.js'
            }
        },
        watch: {
            files: '<config:lint.files>',
            tasks: 'lint'
        },
        jshint: {
            options: {
                boss: true,
                browser: true,
                curly: false,
                devel: true,
                eqeqeq: false,
                eqnull: true,
                expr: true,
                evil: true,
                immed: false,
                laxcomma: true,
                newcap: false,
                noarg: true,
                smarttabs: true,
                sub: true,
                undef: true
            },
            globals: {
                Modernizr: true,
                DocumentTouch: true,
                TEST: true,
                SVGFEColorMatrixElement : true,
                Blob: true
            }
        }
    });

    grunt.registerTask('default', 'min');

    // Travis CI task.
    grunt.registerTask('travis', 'qunit');
};
<|endoftext|>


<commit_before>var assert = require('assert'),
    fs = require('fs'),
    exec = require('child_process').exec,
    Tempfile = require('temporary/lib/file'),
    json2css = require('../lib/json2css.js'),
    expectedDir = __dirname + '/expected_files';

module.exports = {
  // Common setup/assertion
  'An array of image positions, dimensions, and names': function () {
    // TODO: The malicious URL should be placed in a separate test but I want to test every engine and hate the bloat
    this.info = [
      {'name': 'sprite1', 'x': 0, 'y': 0, 'width': 10, 'height': 20, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/spritesheet.png'},
      {'name': 'sprite2', 'x': 10, 'y': 20, 'width': 20, 'height': 30, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/spritesheet.png'},
      {'name': 'sprite3', 'x': 30, 'y': 50, 'width': 50, 'height': 50, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/( \'")/spritesheet.png'}
    ];
  },
  'An object of image positions and dimensions keyed by names': function () {
    this.info = {
      'sprite1': {'x': 0, 'y': 0, 'width': 10, 'height': 20, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/spritesheet.png'},
      'sprite2': {'x': 10, 'y': 20, 'width': 20, 'height': 30, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/spritesheet.png'},
      'sprite3': {'x': 30, 'y': 50, 'width': 50, 'height': 50, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/( \'")/spritesheet.png'}
    };
  },
  'processed via json2css': function () {
    // Convert info into result via json2css
    var options = this.options,
        info = this.info,
        result = options ? json2css(info, options) : json2css(info);
    this.result = result;

    // If we are debugging, output results to a file
    if (true) {
    // if (false) {
      try { fs.mkdirSync(__dirname + '/actual_files/'); } catch (e) {}
      fs.writeFileSync(__dirname + '/actual_files/' + this.filename, result, 'utf8');
    }
  },
  'matches as expected': function () {
    // Load in the files and assert
    var actual = this.result,
        expected = fs.readFileSync(expectedDir  + '/' + this.filename, 'utf8');
    assert.strictEqual(actual, expected);
  },
  'is deep equal to expected': function () {
    // Load in the files and assert
    var actual = JSON.parse(this.result),
        expected = require(expectedDir  + '/' + this.filename, 'utf8');
    assert.deepEqual(actual, expected);
  },

  // JSON
  'processed into JSON': [function () {
    this.options = {'format': 'json'};
    this.filename = 'json.json';
  }, 'processed via json2css'],
  'is valid JSON': function () {
    var result = this.result;
    assert.doesNotThrow(function () {
      JSON.parse(result);
    });
  },

  // CSS
  'processed into CSS': [function () {
    this.options = null;
    this.filename = 'css.css';
  }, 'processed via json2css'],
  'is valid CSS': function () {
    // Add some stylus which hooks into our result
    var css = this.result;

    // Assert no errors and validity of CSS
    assert.notEqual(css, '');

    // TODO: Validate CSS
    // console.log('CSS', css);
  },

  // Stylus
  'processed into Stylus': [function () {
    this.options = {'format': 'stylus'};
    this.filename = 'stylus.styl';
  }, 'processed via json2css'],
  'is valid Stylus': function (done) {
    // Add some stylus which hooks into our result
    var styl = this.result;
    styl += [
      '.feature',
      '  height: $sprite1_height;',
      '  spriteWidth($sprite2)',
      '  spriteImage($sprite3)',
      '',
      '.feature2',
      '  sprite($sprite2)'
    ].join('\n');

    // Render the stylus
    var stylus = require('stylus');

    stylus.render(styl, function handleStylus (err, css) {
      // Assert no errors and validity of CSS
      assert.strictEqual(err, null);
      assert.notEqual(css, '');

      // TODO: Validate CSS
      // console.log('Stylus', css);

      // Callback
      done(err);
    });
  },

  // LESS
  'processed into LESS': [function () {
    this.options = {'format': 'less'};
    this.filename = 'less.less';
  }, 'processed via json2css'],
  'is valid LESS': function (done) {
    // Add some LESS to our result
    var lessStr = this.result;
    lessStr += [
      '.feature {',
      '  height: @sprite1-height;',
      '  .sprite-width(@sprite2);',
      '  .sprite-image(@sprite3);',
      '}',
      '',
      '.feature2 {',
      '  .sprite(@sprite2);',
      '}'
    ].join('\n');

    // Render the LESS, assert no errors, and valid CSS
    var less = require('less');
    less.render(lessStr, function (err, css) {
      assert.strictEqual(err, null);
      assert.notEqual(css, '');

      // console.log('LESS', css);

      // Verify there are no braces in the CSS (array string coercion)
      assert.strictEqual(css.indexOf(']'), -1);

      // Callback
      done(err);
    });
  },

  // SASS
  'processed into SASS': [function () {
    this.options = {'format': 'sass'};
    this.filename = 'sass.sass';
  }, 'processed via json2css'],
  'is valid SASS': function (done) {
    // Add some SASS to our result
    var sassStr = this.result;
    sassStr += '\n' + [
      '.feature',
      '  height: $sprite1-height',
      '  @include sprite-width($sprite2)',
      '  @include sprite-image($sprite3)',
      '',
      '.feature2',
      '  @include sprite($sprite2)'
    ].join('\n');

    // Render the SASS, assert no errors, and valid CSS
    var tmp = new Tempfile();
    tmp.writeFileSync(sassStr);
    exec('sass ' + tmp.path, function (err, css, stderr) {
      assert.strictEqual(stderr, '');
      assert.strictEqual(err, null);
      assert.notEqual(css, '');
      // console.log('SASS', css);
      done(err);
    });
  },

  // SCSS
  'processed into SCSS': [function () {
    this.options = {'format': 'scss'};
    this.filename = 'scss.scss';
  }, 'processed via json2css'],
  'is valid SCSS': function (done) {
    // Add some SCSS to our result
    var scssStr = this.result;
    scssStr += '\n' + [
      '.feature {',
      '  height: $sprite1-height;',
      '  @include sprite-width($sprite2);',
      '  @include sprite-image($sprite3);',
      '}',
      '',
      '.feature2 {',
      '  @include sprite($sprite2);',
      '}'
    ].join('\n');

    // Render the SCSS, assert no errors, and valid CSS
    var tmp = new Tempfile();
    tmp.writeFileSync(scssStr);
    exec('sass --scss ' + tmp.path, function (err, css, stderr) {
      assert.strictEqual(stderr, '');
      assert.strictEqual(err, null);
      assert.notEqual(css, '');
      // console.log('SCSS', css);
      done(err);
    });
  },

  // SCSS with size
  'processed into SCSS with size': [function () {
    this.options = {'format': 'scss'};
    this.options.formatOpts = {'size': {'height': '100', 'width': '50'}, 'name': 'spriteName'};
    this.filename = 'scss.scss';
  }, 'processed via json2css'],
  'is valid SCSS': function (done) {
    // Add some SCSS to our result
    var scssStr = this.result;
    scssStr += '\n' + [
      '.feature {',
      '  height: $sprite1-height;',
      '  @include sprite-width($sprite2);',
      '  @include sprite-image($sprite3);',
      '}',
      '',
      '.feature2 {',
      '  @include sprite($sprite2);',
      '}'
    ].join('\n');

    // Render the SCSS, assert no errors, and valid CSS
    var tmp = new Tempfile();
    tmp.writeFileSync(scssStr);
    exec('sass --scss ' + tmp.path, function (err, css, stderr) {
      assert.strictEqual(stderr, '');
      assert.strictEqual(err, null);
      assert.notEqual(css, '');
      // console.log('SCSS', css);
      done(err);
    });
  }
};
<commit_msg>Removed stylesheet-wide image test. Verified all CSS looks good<commit_after>var assert = require('assert'),
    fs = require('fs'),
    exec = require('child_process').exec,
    Tempfile = require('temporary/lib/file'),
    json2css = require('../lib/json2css.js'),
    expectedDir = __dirname + '/expected_files';

module.exports = {
  // Common setup/assertion
  'An array of image positions, dimensions, and names': function () {
    // TODO: The malicious URL should be placed in a separate test but I want to test every engine and hate the bloat
    this.info = [
      {'name': 'sprite1', 'x': 0, 'y': 0, 'width': 10, 'height': 20, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/spritesheet.png'},
      {'name': 'sprite2', 'x': 10, 'y': 20, 'width': 20, 'height': 30, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/spritesheet.png'},
      {'name': 'sprite3', 'x': 30, 'y': 50, 'width': 50, 'height': 50, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/( \'")/spritesheet.png'}
    ];
  },
  'An object of image positions and dimensions keyed by names': function () {
    this.info = {
      'sprite1': {'x': 0, 'y': 0, 'width': 10, 'height': 20, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/spritesheet.png'},
      'sprite2': {'x': 10, 'y': 20, 'width': 20, 'height': 30, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/spritesheet.png'},
      'sprite3': {'x': 30, 'y': 50, 'width': 50, 'height': 50, 'total_width': 80, 'total_height': 100, 'image': 'nested/dir/( \'")/spritesheet.png'}
    };
  },
  'processed via json2css': function () {
    // Convert info into result via json2css
    var options = this.options,
        info = this.info,
        result = options ? json2css(info, options) : json2css(info);
    this.result = result;

    // If we are debugging, output results to a file
    if (true) {
    // if (false) {
      try { fs.mkdirSync(__dirname + '/actual_files/'); } catch (e) {}
      fs.writeFileSync(__dirname + '/actual_files/' + this.filename, result, 'utf8');
    }
  },
  'matches as expected': function () {
    // Load in the files and assert
    var actual = this.result,
        expected = fs.readFileSync(expectedDir  + '/' + this.filename, 'utf8');
    assert.strictEqual(actual, expected);
  },
  'is deep equal to expected': function () {
    // Load in the files and assert
    var actual = JSON.parse(this.result),
        expected = require(expectedDir  + '/' + this.filename, 'utf8');
    assert.deepEqual(actual, expected);
  },

  // JSON
  'processed into JSON': [function () {
    this.options = {'format': 'json'};
    this.filename = 'json.json';
  }, 'processed via json2css'],
  'is valid JSON': function () {
    var result = this.result;
    assert.doesNotThrow(function () {
      JSON.parse(result);
    });
  },

  // CSS
  'processed into CSS': [function () {
    this.options = null;
    this.filename = 'css.css';
  }, 'processed via json2css'],
  'is valid CSS': function () {
    // Add some stylus which hooks into our result
    var css = this.result;

    // Assert no errors and validity of CSS
    assert.notEqual(css, '');

    // TODO: Validate CSS
    // console.log('CSS', css);
  },

  // Stylus
  'processed into Stylus': [function () {
    this.options = {'format': 'stylus'};
    this.filename = 'stylus.styl';
  }, 'processed via json2css'],
  'is valid Stylus': function (done) {
    // Add some stylus which hooks into our result
    var styl = this.result;
    styl += [
      '.feature',
      '  height: $sprite1_height;',
      '  spriteWidth($sprite2)',
      '  spriteImage($sprite3)',
      '',
      '.feature2',
      '  sprite($sprite2)'
    ].join('\n');

    // Render the stylus
    var stylus = require('stylus');

    stylus.render(styl, function handleStylus (err, css) {
      // Assert no errors and validity of CSS
      assert.strictEqual(err, null);
      assert.notEqual(css, '');

      // TODO: Validate CSS
      // console.log('Stylus', css);

      // Callback
      done(err);
    });
  },

  // LESS
  'processed into LESS': [function () {
    this.options = {'format': 'less'};
    this.filename = 'less.less';
  }, 'processed via json2css'],
  'is valid LESS': function (done) {
    // Add some LESS to our result
    var lessStr = this.result;
    lessStr += [
      '.feature {',
      '  height: @sprite1-height;',
      '  .sprite-width(@sprite2);',
      '  .sprite-image(@sprite3);',
      '}',
      '',
      '.feature2 {',
      '  .sprite(@sprite2);',
      '}'
    ].join('\n');

    // Render the LESS, assert no errors, and valid CSS
    var less = require('less');
    less.render(lessStr, function (err, css) {
      assert.strictEqual(err, null);
      assert.notEqual(css, '');

      // console.log('LESS', css);

      // Verify there are no braces in the CSS (array string coercion)
      assert.strictEqual(css.indexOf(']'), -1);

      // Callback
      done(err);
    });
  },

  // SASS
  'processed into SASS': [function () {
    this.options = {'format': 'sass'};
    this.filename = 'sass.sass';
  }, 'processed via json2css'],
  'is valid SASS': function (done) {
    // Add some SASS to our result
    var sassStr = this.result;
    sassStr += '\n' + [
      '.feature',
      '  height: $sprite1-height',
      '  @include sprite-width($sprite2)',
      '  @include sprite-image($sprite3)',
      '',
      '.feature2',
      '  @include sprite($sprite2)'
    ].join('\n');

    // Render the SASS, assert no errors, and valid CSS
    var tmp = new Tempfile();
    tmp.writeFileSync(sassStr);
    exec('sass ' + tmp.path, function (err, css, stderr) {
      assert.strictEqual(stderr, '');
      assert.strictEqual(err, null);
      assert.notEqual(css, '');
      // console.log('SASS', css);
      done(err);
    });
  },

  // SCSS
  'processed into SCSS': [function () {
    this.options = {'format': 'scss'};
    this.filename = 'scss.scss';
  }, 'processed via json2css'],
  'is valid SCSS': function (done) {
    // Add some SCSS to our result
    var scssStr = this.result;
    scssStr += '\n' + [
      '.feature {',
      '  height: $sprite1-height;',
      '  @include sprite-width($sprite2);',
      '  @include sprite-image($sprite3);',
      '}',
      '',
      '.feature2 {',
      '  @include sprite($sprite2);',
      '}'
    ].join('\n');

    // Render the SCSS, assert no errors, and valid CSS
    var tmp = new Tempfile();
    tmp.writeFileSync(scssStr);
    exec('sass --scss ' + tmp.path, function (err, css, stderr) {
      assert.strictEqual(stderr, '');
      assert.strictEqual(err, null);
      assert.notEqual(css, '');
      // console.log('SCSS', css);
      done(err);
    });
  }
};
<|endoftext|>


<commit_before><commit_msg>Added better errors when calling contracts with incorrect number of arguments.<commit_after><|endoftext|>


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

    function FocusLock($timeout, $rootScope, angularHelper) {

        // If the umb-auto-focus directive is in use we respect that by leaving the default focus on it instead of choosing the first focusable element using this function
        function getAutoFocusElement (elements) {
            var elmentWithAutoFocus = null;

            elements.forEach((element) => {
                if(element.getAttribute('umb-auto-focus') === 'true') {
                    elmentWithAutoFocus = element;
                }
            });

            return elmentWithAutoFocus;
        }

        function link(scope, element) {
            var target = element[0];
            var focusableElements;
            var firstFocusableElement;
            var lastFocusableElement;
            var infiniteEditorsWrapper;
            var infiniteEditors;
            var disconnectObserver = false;
            var closingEditor = false;

            if(!$rootScope.lastKnownFocusableElements){
                $rootScope.lastKnownFocusableElements = [];
            }

            $rootScope.lastKnownFocusableElements.push(document.activeElement);

            // List of elements that can be focusable within the focus lock
            var focusableElementsSelector = '[role="button"], a[href]:not([disabled]):not(.ng-hide), button:not([disabled]):not(.ng-hide), textarea:not([disabled]):not(.ng-hide), input:not([disabled]):not(.ng-hide), select:not([disabled]):not(.ng-hide)';

            // Grab the body element so we can add the tabbing class on it when needed
            var bodyElement = document.querySelector('body');

            function getDomNodes(){
                infiniteEditorsWrapper = document.querySelector('.umb-editors');
                if(infiniteEditorsWrapper) {
                    infiniteEditors = Array.from(infiniteEditorsWrapper.querySelectorAll('.umb-editor') || []);
                }
            }

            function getFocusableElements(targetElm) {
                var elm = targetElm ? targetElm : target;
                focusableElements = elm.querySelectorAll(focusableElementsSelector);
                // Set first and last focusable elements
                firstFocusableElement = focusableElements[0];
                lastFocusableElement = focusableElements[focusableElements.length - 1];
            }

            function handleKeydown(event) {
                var isTabPressed = (event.key === 'Tab' || event.keyCode === 9);

                if (!isTabPressed){
                    return;
                }

                // If shift + tab key
                if(event.shiftKey){
                    // Set focus on the last focusable element if shift+tab are pressed meaning we go backwards
                    if(document.activeElement === firstFocusableElement){
                        lastFocusableElement.focus();
                        event.preventDefault();
                    }
                }
                // Else only the tab key is pressed
                else{
                    // Using only the tab key we set focus on the first focusable element mening we go forward
                    if (document.activeElement === lastFocusableElement) {
                        firstFocusableElement.focus();
                        event.preventDefault();
                    }
                }
            }

            function clearLastKnownFocusedElements() {
                $rootScope.lastKnownFocusableElements = [];
            }

            function setElementFocus() {
                var defaultFocusedElement = getAutoFocusElement(focusableElements);
                var lastKnownElement;

                // If an infinite editor is being closed then we reset the focus to the element that triggered the the overlay
                if(closingEditor){

                    // If there is only one editor open, search for the "editor-info" inside it and set focus on it
                    // This is relevant when a property editor has been selected and the editor where we selected it from
                    // is closed taking us back to the first layer
                    // Otherwise set it to the last element in the lastKnownFocusedElements array
                    if(infiniteEditors && infiniteEditors.length === 1){
                        var editorInfo = infiniteEditors[0].querySelector('.editor-info');
                        if(infiniteEditors && infiniteEditors.length === 1 && editorInfo !== null) {
                            lastKnownElement = editorInfo;

                            // Clear the array
                            clearLastKnownFocusedElements();
                        }
                    }
                    else {
                        var lastItemIndex = $rootScope.lastKnownFocusableElements.length - 1;
                        lastKnownElement = $rootScope.lastKnownFocusableElements[lastItemIndex];

                        // Remove the last item from the array so we always set the correct lastKnowFocus for each layer
                        $rootScope.lastKnownFocusableElements.splice(lastItemIndex, 1);
                    }

                    // Update the lastknowelement variable here
                    closingEditor = false;
                }

                // 1st - we check for any last known element - Usually the element the trigger the opening of a new layer
                // If it exists it will receive fous
                // 2nd - We check to see if a default focus has been set using the umb-auto-focus directive. If not we set focus on
                // the first focusable element
                // 3rd - Otherwise put the focus on the default focused element
                if(lastKnownElement){
                    lastKnownElement.focus();
                }
                else if(defaultFocusedElement === null ){
                    firstFocusableElement.focus();
                }
                else {
                    defaultFocusedElement.focus();
                }
            }

            function observeDomChanges() {
                // Watch for DOM changes - so we can refresh the focusable elements if an element
                // changes from being disabled to being enabled for instance
                var observer = new MutationObserver(_.debounce(domChange, 200));

                // Options for the observer (which mutations to observe)
                var config = { attributes: true, childList: true, subtree: true};

                // Whenever the DOM changes ensure the list of focused elements is updated
                function domChange() {
                    getFocusableElements();
                }

                // Start observing the target node for configured mutations
                observer.observe(target, config);

                // Disconnect observer
                if(disconnectObserver){
                    observer.disconnect();
                }
            }

            function cleanupEventHandlers() {
                //if we're in infinite editing mode
                if(infiniteEditors.length > 0) {
                    var activeEditor = infiniteEditors[infiniteEditors.length - 1];
                    var inactiveEditors = infiniteEditors.filter(editor => editor !== activeEditor);

                    if(inactiveEditors.length > 0) {
                        for (var index = 0; index < inactiveEditors.length; index++) {
                            var inactiveEditor = inactiveEditors[index];

                            // Remove event handlers from inactive editors
                            inactiveEditor.removeEventListener('keydown', handleKeydown);
                        }
                    }
                    else {
                        // Why is this one only begin called if there is no other infinite editors, wouldn't it make sense always to clean this up?
                        // Remove event handlers from the active editor
                        activeEditor.removeEventListener('keydown', handleKeydown);
                    }
                }
            }

            function onInit(targetElm) {

                $timeout(() => {

                    // Fetch the DOM nodes we need
                    getDomNodes();

                    cleanupEventHandlers();

                    getFocusableElements(targetElm);

                    if(focusableElements.length > 0) {

                        observeDomChanges();

                        setElementFocus();

                        //  Handle keydown
                        target.addEventListener('keydown', handleKeydown);
                    }

                });
            }

            scope.$on('$includeContentLoaded', () => {
                angularHelper.safeApply(scope, () => {
                    onInit();
                });
            });

            // If more than one editor is still open then re-initialize otherwise remove the event listener
            scope.$on('$destroy', function () {
                // Make sure to disconnect the observer so we potentially don't end up with having many active ones
                disconnectObserver = true;

                if(infiniteEditors && infiniteEditors.length > 1) {
                    // Pass the correct editor in order to find the focusable elements
                    var newTarget = infiniteEditors[infiniteEditors.length - 2];

                    if(infiniteEditors.length > 1) {
                        // Setting closing till true will let us re-apply the last known focus to then opened layer that then becomes
                        // active
                        closingEditor = true;

                        onInit(newTarget);

                        return;
                    }
                }

                // Clear lastKnownFocusableElements
                clearLastKnownFocusedElements();

                // Cleanup event handler
                target.removeEventListener('keydown', handleKeydown);
            });
        }

        var directive = {
            restrict: 'A',
            link: link
        };

        return directive;
    }

    angular.module('umbraco.directives').directive('umbFocusLock', FocusLock);

})();

// TODO: Ensure the domObserver is NOT started when there is only one infinite overlay and it's being destroyed!
<commit_msg>Turn nodelist into an array and filter out elements whose parent, grandparents etc. has a .ng-hide class<commit_after>(function() {
    'use strict';

    function FocusLock($timeout, $rootScope, angularHelper) {

        // If the umb-auto-focus directive is in use we respect that by leaving the default focus on it instead of choosing the first focusable element using this function
        function getAutoFocusElement (elements) {
            var elmentWithAutoFocus = null;

            elements.forEach((element) => {
                if(element.getAttribute('umb-auto-focus') === 'true') {
                    elmentWithAutoFocus = element;
                }
            });

            return elmentWithAutoFocus;
        }

        function link(scope, element) {
            var target = element[0];
            var focusableElements;
            var firstFocusableElement;
            var lastFocusableElement;
            var infiniteEditorsWrapper;
            var infiniteEditors;
            var disconnectObserver = false;
            var closingEditor = false;

            if(!$rootScope.lastKnownFocusableElements){
                $rootScope.lastKnownFocusableElements = [];
            }

            $rootScope.lastKnownFocusableElements.push(document.activeElement);

            // List of elements that can be focusable within the focus lock
            var focusableElementsSelector = '[role="button"], a[href]:not([disabled]):not(.ng-hide), button:not([disabled]):not(.ng-hide), textarea:not([disabled]):not(.ng-hide), input:not([disabled]):not(.ng-hide), select:not([disabled]):not(.ng-hide)';

            function getDomNodes(){
                infiniteEditorsWrapper = document.querySelector('.umb-editors');
                if(infiniteEditorsWrapper) {
                    infiniteEditors = Array.from(infiniteEditorsWrapper.querySelectorAll('.umb-editor') || []);
                }
            }

            function getFocusableElements(targetElm) {
                var elm = targetElm ? targetElm : target;

                // Filter out elements that are children of parents with the .ng-hide class
                focusableElements = [...elm.querySelectorAll(focusableElementsSelector)].filter(elm => !elm.closest('.ng-hide'));

                // Set first and last focusable elements
                firstFocusableElement = focusableElements[0];
                lastFocusableElement = focusableElements[focusableElements.length - 1];
            }

            function handleKeydown(event) {
                var isTabPressed = (event.key === 'Tab' || event.keyCode === 9);

                if (!isTabPressed){
                    return;
                }

                // If shift + tab key
                if(event.shiftKey){
                    // Set focus on the last focusable element if shift+tab are pressed meaning we go backwards
                    if(document.activeElement === firstFocusableElement){
                        lastFocusableElement.focus();
                        event.preventDefault();
                    }
                }
                // Else only the tab key is pressed
                else{
                    // Using only the tab key we set focus on the first focusable element mening we go forward
                    if (document.activeElement === lastFocusableElement) {
                        firstFocusableElement.focus();
                        event.preventDefault();
                    }
                }
            }

            function clearLastKnownFocusedElements() {
                $rootScope.lastKnownFocusableElements = [];
            }

            function setElementFocus() {
                var defaultFocusedElement = getAutoFocusElement(focusableElements);
                var lastKnownElement;

                // If an infinite editor is being closed then we reset the focus to the element that triggered the the overlay
                if(closingEditor){

                    // If there is only one editor open, search for the "editor-info" inside it and set focus on it
                    // This is relevant when a property editor has been selected and the editor where we selected it from
                    // is closed taking us back to the first layer
                    // Otherwise set it to the last element in the lastKnownFocusedElements array
                    if(infiniteEditors && infiniteEditors.length === 1){
                        var editorInfo = infiniteEditors[0].querySelector('.editor-info');
                        if(infiniteEditors && infiniteEditors.length === 1 && editorInfo !== null) {
                            lastKnownElement = editorInfo;

                            // Clear the array
                            clearLastKnownFocusedElements();
                        }
                    }
                    else {
                        var lastItemIndex = $rootScope.lastKnownFocusableElements.length - 1;
                        lastKnownElement = $rootScope.lastKnownFocusableElements[lastItemIndex];

                        // Remove the last item from the array so we always set the correct lastKnowFocus for each layer
                        $rootScope.lastKnownFocusableElements.splice(lastItemIndex, 1);
                    }

                    // Update the lastknowelement variable here
                    closingEditor = false;
                }

                // 1st - we check for any last known element - Usually the element the trigger the opening of a new layer
                // If it exists it will receive fous
                // 2nd - We check to see if a default focus has been set using the umb-auto-focus directive. If not we set focus on
                // the first focusable element
                // 3rd - Otherwise put the focus on the default focused element
                if(lastKnownElement){
                    lastKnownElement.focus();
                }
                else if(defaultFocusedElement === null ){
                    firstFocusableElement.focus();
                }
                else {
                    defaultFocusedElement.focus();
                }
            }

            function observeDomChanges() {
                // Watch for DOM changes - so we can refresh the focusable elements if an element
                // changes from being disabled to being enabled for instance
                var observer = new MutationObserver(_.debounce(domChange, 200));

                // Options for the observer (which mutations to observe)
                var config = { attributes: true, childList: true, subtree: true};

                // Whenever the DOM changes ensure the list of focused elements is updated
                function domChange() {
                    getFocusableElements();
                }

                // Start observing the target node for configured mutations
                observer.observe(target, config);

                // Disconnect observer
                if(disconnectObserver){
                    observer.disconnect();
                }
            }

            function cleanupEventHandlers() {
                //if we're in infinite editing mode
                if(infiniteEditors.length > 0) {
                    var activeEditor = infiniteEditors[infiniteEditors.length - 1];
                    var inactiveEditors = infiniteEditors.filter(editor => editor !== activeEditor);

                    if(inactiveEditors.length > 0) {
                        for (var index = 0; index < inactiveEditors.length; index++) {
                            var inactiveEditor = inactiveEditors[index];

                            // Remove event handlers from inactive editors
                            inactiveEditor.removeEventListener('keydown', handleKeydown);
                        }
                    }
                    else {
                        // Why is this one only begin called if there is no other infinite editors, wouldn't it make sense always to clean this up?
                        // Remove event handlers from the active editor
                        activeEditor.removeEventListener('keydown', handleKeydown);
                    }
                }
            }

            function onInit(targetElm) {

                $timeout(() => {

                    // Fetch the DOM nodes we need
                    getDomNodes();

                    cleanupEventHandlers();

                    getFocusableElements(targetElm);

                    if(focusableElements.length > 0) {

                        observeDomChanges();

                        setElementFocus();

                        //  Handle keydown
                        target.addEventListener('keydown', handleKeydown);
                    }

                });
            }

            scope.$on('$includeContentLoaded', () => {
                angularHelper.safeApply(scope, () => {
                    onInit();
                });
            });

            // If more than one editor is still open then re-initialize otherwise remove the event listener
            scope.$on('$destroy', function () {
                // Make sure to disconnect the observer so we potentially don't end up with having many active ones
                disconnectObserver = true;

                if(infiniteEditors && infiniteEditors.length > 1) {
                    // Pass the correct editor in order to find the focusable elements
                    var newTarget = infiniteEditors[infiniteEditors.length - 2];

                    if(infiniteEditors.length > 1) {
                        // Setting closing till true will let us re-apply the last known focus to then opened layer that then becomes
                        // active
                        closingEditor = true;

                        onInit(newTarget);

                        return;
                    }
                }

                // Clear lastKnownFocusableElements
                clearLastKnownFocusedElements();

                // Cleanup event handler
                target.removeEventListener('keydown', handleKeydown);
            });
        }

        var directive = {
            restrict: 'A',
            link: link
        };

        return directive;
    }

    angular.module('umbraco.directives').directive('umbFocusLock', FocusLock);

})();

// TODO: Ensure the domObserver is NOT started when there is only one infinite overlay and it's being destroyed!
<|endoftext|>