<commit_before>!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.basicLightbox=e()}}(function(){return function e(n,o,t){function r(f,a){if(!o[f]){if(!n[f]){var c="function"==typeof require&&require;if(!a&&c)return c(f,!0);if(i)return i(f,!0);var l=new Error("Cannot find module '"+f+"'");throw l.code="MODULE_NOT_FOUND",l}var u=o[f]={exports:{}};n[f][0].call(u.exports,function(e){var o=n[f][1][e];return r(o?o:e)},u,u.exports,e,n,o,t)}return o[f].exports}for(var i="function"==typeof require&&require,f=0;f<t.length;f++)r(t[f]);return r}({1:[function(e,n,o){"use strict";Object.defineProperty(o,"__esModule",{value:!0});var t=function(e){"function"==typeof e.stopPropagation&&e.stopPropagation(),"function"==typeof e.preventDefault&&e.preventDefault()},r=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return e=Object.assign({},e),e.closable!==!1&&(e.closable=!0),"function"==typeof e.className&&(e.className=e.className()),"string"!=typeof e.className&&(e.className=null),"function"!=typeof e.beforeShow&&(e.beforeShow=function(){}),"function"!=typeof e.afterShow&&(e.afterShow=function(){}),"function"!=typeof e.beforeClose&&(e.beforeClose=function(){}),"function"!=typeof e.afterClose&&(e.afterClose=function(){}),"function"==typeof e.beforePlaceholder&&(e.beforePlaceholder=e.beforePlaceholder()),"string"!=typeof e.beforePlaceholder&&(e.beforePlaceholder=""),"function"==typeof e.afterPlaceholder&&(e.afterPlaceholder=e.afterPlaceholder()),"string"!=typeof e.afterPlaceholder&&(e.afterPlaceholder=""),e},i=function(e){var n=e.children;return 1===n.length&&"IMG"===n[0].tagName},f=o.visible=function(e){return e=e||document.querySelector(".basicLightbox"),null!=e&&e.ownerDocument.body.contains(e)===!0},a=function(){var e=arguments.length<=0||void 0===arguments[0]?"":arguments[0],n=arguments[1],o=document.createElement("div");o.classList.add("basicLightbox"),null!=n.className&&o.classList.add(n.className),o.innerHTML="\n		"+n.beforePlaceholder+'\n
\n			'+e+"\n
\n		"+n.afterPlaceholder+"\n	";var t=i(o.querySelector(".basicLightbox__placeholder"));return t===!0&&o.classList.add("basicLightbox--img"),o},c=function(e,n){return document.body.appendChild(e),setTimeout(function(){requestAnimationFrame(function(){return e.classList.add("basicLightbox--visible"),n()})},10),!0},l=function(e,n){return e.classList.remove("basicLightbox--visible"),setTimeout(function(){requestAnimationFrame(function(){return f(e)===!1?n():(e.parentElement.removeChild(e),n())})},410),!0};o.create=function(e,n){n=r(n);var o=a(e,n),i=function(){return o},u=function(){return f(o)},s=function(e){return n.beforeShow(b)===!1?!1:(c(o,function(){return n.afterShow(b),"function"==typeof e?e(b):void 0}),!0)},d=function(e){return n.beforeClose(b)===!1?!1:(l(o,function(){return n.afterClose(b),"function"==typeof e?e(b):void 0}),!0)};n.closable===!0&&(o.onclick=function(e){e.target===this&&(d(),t(e))});var b={element:i,visible:u,show:s,close:d};return b}},{}]},{},[1])(1)});<commit_msg>Rebuild<commit_after>!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.basicLightbox=e()}}(function(){return function e(t,n,o){function r(f,a){if(!n[f]){if(!t[f]){var c="function"==typeof require&&require;if(!a&&c)return c(f,!0);if(i)return i(f,!0);var l=new Error("Cannot find module '"+f+"'");throw l.code="MODULE_NOT_FOUND",l}var u=n[f]={exports:{}};t[f][0].call(u.exports,function(e){var n=t[f][1][e];return r(n?n:e)},u,u.exports,e,t,n,o)}return n[f].exports}for(var i="function"==typeof require&&require,f=0;f<o.length;f++)r(o[f]);return r}({1:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o=function(e){"function"==typeof e.stopPropagation&&e.stopPropagation(),"function"==typeof e.preventDefault&&e.preventDefault()},r=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return e=Object.assign({},e),e.closable!==!1&&(e.closable=!0),"function"==typeof e.className&&(e.className=e.className()),"string"!=typeof e.className&&(e.className=null),"function"!=typeof e.beforeShow&&(e.beforeShow=function(){}),"function"!=typeof e.afterShow&&(e.afterShow=function(){}),"function"!=typeof e.beforeClose&&(e.beforeClose=function(){}),"function"!=typeof e.afterClose&&(e.afterClose=function(){}),"function"==typeof e.beforePlaceholder&&(e.beforePlaceholder=e.beforePlaceholder()),"string"!=typeof e.beforePlaceholder&&(e.beforePlaceholder=""),"function"==typeof e.afterPlaceholder&&(e.afterPlaceholder=e.afterPlaceholder()),"string"!=typeof e.afterPlaceholder&&(e.afterPlaceholder=""),e},i=function(e){var t=e.children;return 1===t.length&&"IMG"===t[0].tagName},f=n.visible=function(e){return e=e||document.querySelector(".basicLightbox"),null!=e&&e.ownerDocument.body.contains(e)===!0},a=function(){var e=arguments.length<=0||void 0===arguments[0]?"":arguments[0],t=arguments[1],n=document.createElement("div");n.classList.add("basicLightbox"),null!=t.className&&n.classList.add(t.className),n.innerHTML="\n\t\t"+t.beforePlaceholder+'\n\t\t
\n\t\t\t'+e+"\n\t\t
\n\t\t"+t.afterPlaceholder+"\n\t";var o=i(n.querySelector(".basicLightbox__placeholder"));return o===!0&&n.classList.add("basicLightbox--img"),n},c=function(e,t){return document.body.appendChild(e),setTimeout(function(){requestAnimationFrame(function(){return e.classList.add("basicLightbox--visible"),t()})},10),!0},l=function(e,t){return e.classList.remove("basicLightbox--visible"),setTimeout(function(){requestAnimationFrame(function(){return f(e)===!1?t():(e.parentElement.removeChild(e),t())})},410),!0};n.create=function(e,t){t=r(t);var n=a(e,t),i=function(){return n},u=function(){return f(n)},s=function(e){return t.beforeShow(b)!==!1&&(c(n,function(){if(t.afterShow(b),"function"==typeof e)return e(b)}),!0)},d=function(e){return t.beforeClose(b)!==!1&&(l(n,function(){if(t.afterClose(b),"function"==typeof e)return e(b)}),!0)};t.closable===!0&&(n.onclick=function(e){e.target===this&&(d(),o(e))});var b={element:i,visible:u,show:s,close:d};return b}},{}]},{},[1])(1)});<|endoftext|>


<commit_before>import { softNavigate } from './helpers/navigation';
import { updateQueryStringParameter } from './helpers/queryStringParameter';

function loadSearchResult(event){
	event.preventDefault();
	const newUrl = updateQueryStringParameter("q",document.querySelector(".search-field").value, true);
	softNavigate(newUrl, ".ajaxcontent", ".pagination");
}

window.addEventListener("DOMContentLoaded", function(){
    /* FEATHERS FILTER MODULE */
    const filterModule = document.getElementById("filter");
    if(filterModule){
        filterModule.addEventListener('newFilter', (e) => {
            const filter = e.detail;
			const newurl = `?q=${document.querySelector('.search-field').value}&filterQuery=${escape(JSON.stringify(filter[0]))}`;
            softNavigate(newurl, ".ajaxcontent", ".pagination");
        });
        document.querySelector(".filter").dispatchEvent(new CustomEvent("getFilter"));
	}

	/* SOFT NAVIGATE SEARCH */
	const searchField = document.querySelector(".search-field");
	if(document.querySelector('#filter') && searchField){
		searchField.closest("form").addEventListener("submit", loadSearchResult);
	}
});

$(document).ready(function () {
	var $modals = $('.modal');
	var $editModal = $('.edit-modal');
	var $externalLinkModal = $('.external-link-modal');

	var populateCourseSelection = function (modal, courses) {
		var $selection = modal.find('.course-selection');
		courses.forEach(function (course) {
			var option = document.createElement("option");
			option.text = course.name;
			option.value = course._id;
			$selection.append(option);
		});
		$selection.chosen().trigger("chosen:updated");
	};

	var populateLessonSelection = function (modal, lessons) {
		var $selection = modal.find('.lesson-selection');
		$selection
			.find('option')
			.remove()
			.end();

		lessons.forEach(function (lesson) {
			var option = document.createElement("option");
			option.text = lesson.name;
			option.value = lesson._id;
			$selection.append(option);
		});

		modal.find('.lessons').css("display", "block");
		$selection.chosen().trigger("chosen:updated");
	};

	$('.add-to-lesson').on('click', function (e) {
		e.preventDefault();
		var entry = $(this).attr('href');
		var query = $('.search-field');

		$.getJSON(entry, function (result) {
			var fields = result.content;
			fields.query = query.val();

			if(window.isInline) {
					window.opener.addResource({
						url: fields.url,
						title: fields.title,
						description: fields.description,
						client: fields.providerName
					});
					window.close();
					return;
			}

			populateModalForm($editModal, {
				title: 'Material zu Thema hinzufügen',
				closeLabel: 'Abbrechen',
				submitLabel: 'Senden',
				fields: fields
			});
			populateCourseSelection($editModal, result.courses.data);
			$editModal.appendTo('body').modal('show');
		});

	});

	$('.course-selection').on('change', function () {
		var selectedCourse = $(this).find("option:selected").val();
		$.getJSON('/courses/' + selectedCourse + '/json', function (res) {
			populateLessonSelection($editModal, res.lessons.data);
		});
	});

	$('.external-link').on('click', function () {
		populateModalForm($externalLinkModal, {
				title: 'Sie verlassen jetzt die Schul-Cloud',
				closeLabel: 'Abbrechen',
		});
		$externalLinkModal.find('.external-link-btn').attr('href', $(this).data('external-link'));
		var provider = $externalLinkModal.find('.provider');
		provider.html($(this).data('provider') || provider.html());
		$externalLinkModal.appendTo('body').modal('show');
	});

	$modals.find('.close, .btn-close, .external-link-btn').on('click', function () {
		$modals.modal('hide');
	});
});
<commit_msg>SC-2123 hotfix from staging<commit_after>import { softNavigate } from './helpers/navigation';
import { updateQueryStringParameter } from './helpers/queryStringParameter';

function loadSearchResult(event){
	event.preventDefault();
	const newUrl = updateQueryStringParameter("q",document.querySelector(".search-field").value, true);
	softNavigate(newUrl, ".ajaxcontent", ".pagination");
}

window.addEventListener("DOMContentLoaded", function(){
    /* FEATHERS FILTER MODULE */
    const filterModule = document.getElementById("filter");
    if(filterModule){
        filterModule.addEventListener('newFilter', (e) => {
            const filter = e.detail;
			const newurl = `?q=${document.querySelector('.search-field').value}&filterQuery=${escape(JSON.stringify(filter[0]))}`;
            softNavigate(newurl, ".ajaxcontent", ".pagination");
        });
        document.querySelector(".filter").dispatchEvent(new CustomEvent("getFilter"));
	}

	/* SOFT NAVIGATE SEARCH */
	const searchField = document.querySelector(".search-field");
	if(document.querySelector('#filter') && searchField){
		searchField.closest("form").addEventListener("submit", loadSearchResult);
	}
});

$(document).ready(function () {
	var $modals = $('.modal');
	var $editModal = $('.edit-modal');
	var $externalLinkModal = $('.external-link-modal');

	var populateCourseSelection = function (modal, courses) {
		var $selection = modal.find('.course-selection');
		courses.forEach(function (course) {
			var option = document.createElement("option");
			option.text = course.name;
			option.value = course._id;
			$selection.append(option);
		});
		$selection.chosen().trigger("chosen:updated");
	};

	var populateLessonSelection = function (modal, lessons) {
		var $selection = modal.find('.lesson-selection');
		$selection
			.find('option')
			.remove()
			.end();

		lessons.forEach(function (lesson) {
			var option = document.createElement("option");
			option.text = lesson.name;
			option.value = lesson._id;
			$selection.append(option);
		});

		modal.find('.lessons').css("display", "block");
		$selection.chosen().trigger("chosen:updated");
	};

	$('.add-to-lesson').on('click', function (e) {
		e.preventDefault();
		var entry = $(this).attr('href');
		var query = $('.search-field');

		$.getJSON(entry, function (result) {
			var fields = result.content;
			fields.query = query.val();

			if(window.isInline) {
					window.opener.addResource({
						url: fields.url,
						title: fields.title,
						description: fields.description,
						client: fields.providerName
					});
					window.close();
					return;
			}

			populateModalForm($editModal, {
				title: 'Material zu Thema hinzufügen',
				closeLabel: 'Abbrechen',
				submitLabel: 'Senden',
				fields: fields
			});
			populateCourseSelection($editModal, result.courses);
			$editModal.appendTo('body').modal('show');
		});

	});

	$('.course-selection').on('change', function () {
		var selectedCourse = $(this).find("option:selected").val();
		$.getJSON('/courses/' + selectedCourse + '/json', function (res) {
			populateLessonSelection($editModal, res.lessons.data);
		});
	});

	$('.external-link').on('click', function () {
		populateModalForm($externalLinkModal, {
				title: 'Sie verlassen jetzt die Schul-Cloud',
				closeLabel: 'Abbrechen',
		});
		$externalLinkModal.find('.external-link-btn').attr('href', $(this).data('external-link'));
		var provider = $externalLinkModal.find('.provider');
		provider.html($(this).data('provider') || provider.html());
		$externalLinkModal.appendTo('body').modal('show');
	});

	$modals.find('.close, .btn-close, .external-link-btn').on('click', function () {
		$modals.modal('hide');
	});
});
<|endoftext|>


<commit_before>var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
<commit_msg>Reduce vendor.js file size<commit_after>var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

var env = config.build.env

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ]),
    // https://github.com/moment/moment-timezone/issues/356#issuecomment-225258637
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import Colors from '../utils/Colors'
import { insert_anchor } from '../utils/transform';

class MessageList extends Component {

  arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
      return false;
    for(var i = arr1.length; i--;) {
      if(arr1[i] !== arr2[i])
        return false;
    }
    return true;
  }

  shouldComponentUpdate(nextProps, nextState) {
    const newMessages = nextProps.messages
    const messages = this.props.messages
    return !this.arraysEqual(newMessages, messages)
  }

  componentDidUpdate(prevProps, prevState) {
    this.scrollToBottom()
  }

  componentDidMount() {
    this.scrollToBottom()
  }

  scrollToBottom = () => {
    this.messagesEnd.scrollIntoView()
  }

  renderMessagesForParticipant = () => {
    const { messages, currentUserId, authorId } = this.props
    return (

        {messages.map(m => {
          const isCurrentUserMessage = m.createdByUserId === currentUserId
          const isAuthor = m.createdByUserId === authorId
          const anotherUserFace = !isCurrentUserMessage && currentUserId !== authorId ? 'plato-red.jpg' : 'plato.jpg'

          const text = insert_anchor(m.text, m.id)

          return (

              {!isCurrentUserMessage && <img src={`/static/${anotherUserFace}`} alt="Platonos" className="plato" />}

{text}

                  {moment(m.createdAt).fromNow()}

          )
        })}

    )
  }

  renderMessagesForPublic = () => {
    const { messages, authorId } = this.props
    return (

        {messages.map(m => {
          const isAuthor = m.createdByUserId === authorId
          const platoFace = isAuthor ? 'plato-red.jpg' : 'plato.jpg'

          const text = insert_anchor(m.text)

          return (

              <img src={`/static/${platoFace}`} alt="Platonos" className="plato" />

{text
                }

                  {moment(m.createdAt).fromNow()}

          )
        })}

    )
  }

  render() {
    const { currentUserId, userIds } = this.props
    return (

        {
          userIds.indexOf(currentUserId) > -1 ?
          this.renderMessagesForParticipant()
          :
          this.renderMessagesForPublic()
        }
        {this.props.isClosed &&

...End of chat...

        }

 { this.messagesEnd = el; }}>

    );
  }
}

MessageList.propTypes = {
  userIds: PropTypes.array.isRequired,
  authorId: PropTypes.string.isRequired,
  messages: PropTypes.array.isRequired,
  currentUserId: PropTypes.string,
  isClosed: PropTypes.bool.isRequired,
}

export default MessageList
<commit_msg>Use render directly for messages rendering<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import Colors from '../utils/Colors'
import { insert_anchor } from '../utils/transform';

class MessageList extends Component {

  arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
      return false;
    for(var i = arr1.length; i--;) {
      if(arr1[i] !== arr2[i])
        return false;
    }
    return true;
  }

  shouldComponentUpdate(nextProps, nextState) {
    const newMessages = nextProps.messages
    const messages = this.props.messages
    return !this.arraysEqual(newMessages, messages)
  }

  componentDidUpdate(prevProps, prevState) {
    this.scrollToBottom()
  }

  componentDidMount() {
    this.scrollToBottom()
  }

  scrollToBottom = () => {
    this.messagesEnd.scrollIntoView()
  }

  render() {
    const { currentUserId, userIds, messages, authorId } = this.props
    const renderForParticipants = userIds.indexOf(currentUserId) > -1
    return (

          {messages.map(m => {
            const isAuthor = m.createdByUserId === authorId
            let renderMessageRightSide, platoFace;

            if (renderForParticipants) {
              renderMessageRightSide = m.createdByUserId === currentUserId
              platoFace = !renderMessageRightSide && currentUserId !== authorId ? 'plato-red.jpg' : 'plato.jpg'
            } else {
              renderMessageRightSide = isAuthor
              platoFace = isAuthor ? 'plato-red.jpg' : 'plato.jpg'
            }

            const text = insert_anchor(m.text, m.id)

            return (
              <div
                key={m.id}
                className={`msg-list ${renderMessageRightSide ? 'right-side':'left-side' }`}
              >
                {renderForParticipants ?
                  (!renderMessageRightSide && <img src={`/static/${platoFace}`} alt="Platonos" className="plato" />)
                  :
                  <img src={`/static/${platoFace}`} alt="Platonos" className="plato" />}

{text}

                    {moment(m.createdAt).fromNow()}

            )
          })}

        {this.props.isClosed &&

...End of chat...

        }

 { this.messagesEnd = el; }}>

    );
  }
}

MessageList.propTypes = {
  userIds: PropTypes.array.isRequired,
  authorId: PropTypes.string.isRequired,
  messages: PropTypes.array.isRequired,
  currentUserId: PropTypes.string,
  isClosed: PropTypes.bool.isRequired,
}

export default MessageList
<|endoftext|>


<commit_before>'use strict';

// model.js - A mongoose model
// https://www.edu-apps.org/code.html - LTI Parameters
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const homeworkModel = mongoose.model('homework', new Schema({
    schoolId: {type: Schema.Types.ObjectId, required: true},
    createdAt: {type: Date, 'default': Date.now},
    updatedAt: {type: Date, 'default': Date.now},
    name: {type: String, required: true},
    description: {type: String},
    dueDate: {type: Date, required: true},
    availableDate: {type: Date, required: true},
    teacherId: {type: Schema.Types.ObjectId, required: true, ref: 'user'},
    courseId: {type: Schema.Types.ObjectId, 'default': null, ref: 'course'},
    lessonId: {type: Schema.Types.ObjectId, 'default': null, ref: 'lesson'},
    private: {type: Boolean},
    publicSubmissions: {type: Boolean},
    teamSubmissions: {type: Boolean},
    maxTeamMembers: {type: Number, 'default':null, min: 1},
    archived: [{type: Schema.Types.ObjectId, ref: 'user'}]
}));

const submissionModel = mongoose.model('submission', new Schema({
    schoolId: {type: Schema.Types.ObjectId, required: true},
    createdAt: {type: Date, 'default': Date.now},
    updatedAt: {type: Date, 'default': Date.now},
    comment: {type: String},
    grade: {type: Number, min: 0, max: 100},
    gradeComment: {type: String},
    homeworkId: {type: Schema.Types.ObjectId, required: true, ref: 'homework'},
    studentId: {type: Schema.Types.ObjectId, required: true, ref: 'user'},
    teamMembers: [{type: Schema.Types.ObjectId, required: true, ref: 'user'}],
    fileIds: [{type: Schema.Types.ObjectId, ref: 'file'}],
    comments: [{type: Schema.Types.ObjectId, ref: 'comment'}]
}));

const commentModel = mongoose.model('comment', new Schema({
    comment: {type: String, required: true},
    submissionId: {type: Schema.Types.ObjectId, required: true, ref: 'submission'},
    createdAt: {type: Date, 'default': Date.now},
    author: {type: Schema.Types.ObjectId, required: true, ref: 'user'}
}));

module.exports = {
    homeworkModel,
    submissionModel,
    commentModel
};
<commit_msg>add courseGroup to submission model<commit_after>'use strict';

// model.js - A mongoose model
// https://www.edu-apps.org/code.html - LTI Parameters
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const homeworkModel = mongoose.model('homework', new Schema({
    schoolId: {type: Schema.Types.ObjectId, required: true},
    createdAt: {type: Date, 'default': Date.now},
    updatedAt: {type: Date, 'default': Date.now},
    name: {type: String, required: true},
    description: {type: String},
    dueDate: {type: Date, required: true},
    availableDate: {type: Date, required: true},
    teacherId: {type: Schema.Types.ObjectId, required: true, ref: 'user'},
    courseId: {type: Schema.Types.ObjectId, 'default': null, ref: 'course'},
    lessonId: {type: Schema.Types.ObjectId, 'default': null, ref: 'lesson'},
    private: {type: Boolean},
    publicSubmissions: {type: Boolean},
    teamSubmissions: {type: Boolean},
    maxTeamMembers: {type: Number, 'default':null, min: 1},
    archived: [{type: Schema.Types.ObjectId, ref: 'user'}]
}));

const submissionModel = mongoose.model('submission', new Schema({
    schoolId: {type: Schema.Types.ObjectId, required: true},
    createdAt: {type: Date, 'default': Date.now},
    updatedAt: {type: Date, 'default': Date.now},
    comment: {type: String},
    grade: {type: Number, min: 0, max: 100},
    gradeComment: {type: String},
    homeworkId: {type: Schema.Types.ObjectId, required: true, ref: 'homework'},
    studentId: {type: Schema.Types.ObjectId, required: true, ref: 'user'},
    teamMembers: [{type: Schema.Types.ObjectId, required: true, ref: 'user'}],
    courseGroup: {type: Schema.Types.ObjectId, ref: 'courseGroup'},
    fileIds: [{type: Schema.Types.ObjectId, ref: 'file'}],
    comments: [{type: Schema.Types.ObjectId, ref: 'comment'}]
}));

const commentModel = mongoose.model('comment', new Schema({
    comment: {type: String, required: true},
    submissionId: {type: Schema.Types.ObjectId, required: true, ref: 'submission'},
    createdAt: {type: Date, 'default': Date.now},
    author: {type: Schema.Types.ObjectId, required: true, ref: 'user'}
}));

module.exports = {
    homeworkModel,
    submissionModel,
    commentModel
};
<|endoftext|>


<commit_before>import {
  transformArrayForSalesforce,
  transformArrayFromSalesforce,
} from './array'

import {
  transformDateForSalesforce,
  transformDateFromSalesforce,
  getFormattedBirthdate,
} from './date'

import { HousingPicklistValues } from '../constants'

const FORM_FIELD_TO_SALESFORCE_FIELD = {
  firstName: 'FirstName',
  lastName: 'LastName',
  socialSecurityNumber: 'SS_Num__c',
  dateOfBirth: 'Birthdate__c',
  phoneNumber: 'Phone',
  emailAddress: 'PersonEmail',
  gender: 'Gender__c',
  isLGBTQ: 'Identify_as_GLBT__c',
  ethnicity: 'Race__c',
  ethnicityOther: 'Other_Race__c',
  language: 'Primary_Language__c',
  languageOther: 'Other_Language__c',
  hasBeenInFosterCare: 'Foster_Care__c',
  hasServedInTheMilitary: 'Veteran__c',
  primaryHealthcareLocation: 'Where_do_you_usually_go_for_healthcare__c',
  isHomeless: 'Housing_Status_New__c',  // TODO: Is this right?
  lengthOfHomelessness: 'How_long_have_you_been_homeless__c',
}

// Invert the map given above.
const SALESFORCE_FIELD_TO_FORM_FIELD = Object.keys(FORM_FIELD_TO_SALESFORCE_FIELD).reduce((map, key) => {
  map[FORM_FIELD_TO_SALESFORCE_FIELD[key]] = key;
  return map;
}, {});

// Performs any additional transformations needed to coerce a field so Salesforce will accept it
export function transformFieldForSalesforce (field, value) {
  if (field === 'dateOfBirth') {
    return transformDateForSalesforce(value)
  } else if (field === 'socialSecurityNumber') {
    if (value.length === 4) {
      return `00000${value}`
    }
    return value && value.replace(/-/g, '')
  } else if (field === 'isHomeless') {
    return value ? HousingPicklistValues.HOMELESS : HousingPicklistValues.HOUSED
  } else if (value instanceof Array) {
    return value.join(';')
  } else {
    return value
  }
}

// Performs any additional transformations needed to coerce a field from Salesforce to its form equivalent
export function transformFieldFromSalesforce (field, value) {
  if (field === 'Birthdate__c') {
    return transformDateFromSalesforce(value)
  } else if (field === 'Race__c') {
    return value && value.split(';')
  } else if (field === 'SS_Num__c') {
    if (value.length === 4) {
      return `00000${value}`
    }
    return value
  } else {
    return value
  }
}

// Returns whether or not a form field can be mapped to something in Salesforce
export function isFieldMappableToSalesforce (field) {
  return field in FORM_FIELD_TO_SALESFORCE_FIELD
}

export function isFieldMappableFromSalesforce (field) {
  return field in SALESFORCE_FIELD_TO_FORM_FIELD
}

export function mapSalesforceFieldToFormField (field) {
  return SALESFORCE_FIELD_TO_FORM_FIELD[field]
}

export function mapFormFieldToSalesforceField (field) {
  return FORM_FIELD_TO_SALESFORCE_FIELD[field]
}
<commit_msg>Fix null pointer exception<commit_after>import {
  transformArrayForSalesforce,
  transformArrayFromSalesforce,
} from './array'

import {
  transformDateForSalesforce,
  transformDateFromSalesforce,
  getFormattedBirthdate,
} from './date'

import { HousingPicklistValues } from '../constants'

const FORM_FIELD_TO_SALESFORCE_FIELD = {
  firstName: 'FirstName',
  lastName: 'LastName',
  socialSecurityNumber: 'SS_Num__c',
  dateOfBirth: 'Birthdate__c',
  phoneNumber: 'Phone',
  emailAddress: 'PersonEmail',
  gender: 'Gender__c',
  isLGBTQ: 'Identify_as_GLBT__c',
  ethnicity: 'Race__c',
  ethnicityOther: 'Other_Race__c',
  language: 'Primary_Language__c',
  languageOther: 'Other_Language__c',
  hasBeenInFosterCare: 'Foster_Care__c',
  hasServedInTheMilitary: 'Veteran__c',
  primaryHealthcareLocation: 'Where_do_you_usually_go_for_healthcare__c',
  isHomeless: 'Housing_Status_New__c',  // TODO: Is this right?
  lengthOfHomelessness: 'How_long_have_you_been_homeless__c',
}

// Invert the map given above.
const SALESFORCE_FIELD_TO_FORM_FIELD = Object.keys(FORM_FIELD_TO_SALESFORCE_FIELD).reduce((map, key) => {
  map[FORM_FIELD_TO_SALESFORCE_FIELD[key]] = key;
  return map;
}, {});

// Performs any additional transformations needed to coerce a field so Salesforce will accept it
export function transformFieldForSalesforce (field, value) {
  if (field === 'dateOfBirth') {
    return transformDateForSalesforce(value)
  } else if (field === 'socialSecurityNumber') {
    if (value && value.length === 4) {
      return `00000${value}`
    }
    return value && value.replace(/-/g, '')
  } else if (field === 'isHomeless') {
    return value ? HousingPicklistValues.HOMELESS : HousingPicklistValues.HOUSED
  } else if (value instanceof Array) {
    return value.join(';')
  } else {
    return value
  }
}

// Performs any additional transformations needed to coerce a field from Salesforce to its form equivalent
export function transformFieldFromSalesforce (field, value) {
  if (field === 'Birthdate__c') {
    return transformDateFromSalesforce(value)
  } else if (field === 'Race__c') {
    return value && value.split(';')
  } else if (field === 'SS_Num__c') {
    if (value && value.length === 4) {
      return `00000${value}`
    }
    return value
  } else {
    return value
  }
}

// Returns whether or not a form field can be mapped to something in Salesforce
export function isFieldMappableToSalesforce (field) {
  return field in FORM_FIELD_TO_SALESFORCE_FIELD
}

export function isFieldMappableFromSalesforce (field) {
  return field in SALESFORCE_FIELD_TO_FORM_FIELD
}

export function mapSalesforceFieldToFormField (field) {
  return SALESFORCE_FIELD_TO_FORM_FIELD[field]
}

export function mapFormFieldToSalesforceField (field) {
  return FORM_FIELD_TO_SALESFORCE_FIELD[field]
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Animated, StyleSheet, View } from 'react-native';

import {
  PanGestureHandler,
  ScrollView,
  State,
} from 'react-native-gesture-handler';

import { USE_NATIVE_DRIVER } from '../config';
import { LoremIpsum } from '../common';

export class DraggableBox extends Component {
  constructor(props) {
    super(props);
    this._translateX = new Animated.Value(0);
    this._translateY = new Animated.Value(0);
    this._lastOffset = { x: 0, y: 0 };
    this._onGestureEvent = Animated.event(
      [
        {
          nativeEvent: {
            translationX: this._translateX,
            translationY: this._translateY,
          },
        },
      ],
      { useNativeDriver: USE_NATIVE_DRIVER }
    );
  }
  _onHandlerStateChange = event => {
    if (event.nativeEvent.oldState === State.ACTIVE) {
      this._lastOffset.x += event.nativeEvent.translationX;
      this._lastOffset.y += event.nativeEvent.translationY;
      this._translateX.setOffset(this._lastOffset.x);
      this._translateX.setValue(0);
      this._translateY.setOffset(this._lastOffset.y);
      this._translateY.setValue(0);
    }
  };
  render() {
    return (
      <PanGestureHandler
        {...this.props}
        onGestureEvent={this._onGestureEvent}
        onHandlerStateChange={this._onHandlerStateChange}
        id="dragbox">
        <Animated.View
          style={[
            styles.box,
            {
              transform: [
                { translateX: this._translateX },
                { translateY: this._translateY },
              ],
            },
          ]}
        />
      </PanGestureHandler>
    );
  }
}

export default class Example extends Component {
  _onClick = () => {
    Alert.alert("I'm so touched");
  };
  render() {
    return (
      <ScrollView
        waitFor={['dragbox', 'image_pinch', 'image_rotation', 'image_tilt']}
        style={styles.scrollView}>
        <LoremIpsum words={40} />
        <DraggableBox />
        <LoremIpsum />
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    flex: 1,
  },
  box: {
    width: 150,
    height: 150,
    alignSelf: 'center',
    backgroundColor: 'plum',
    margin: 10,
    zIndex: 200,
  },
});
<commit_msg>In draggable example let scrollview scroll on vertical movement over the box.<commit_after>import React, { Component } from 'react';
import { Animated, StyleSheet, View } from 'react-native';

import {
  PanGestureHandler,
  ScrollView,
  State,
} from 'react-native-gesture-handler';

import { USE_NATIVE_DRIVER } from '../config';
import { LoremIpsum } from '../common';

export class DraggableBox extends Component {
  constructor(props) {
    super(props);
    this._translateX = new Animated.Value(0);
    this._translateY = new Animated.Value(0);
    this._lastOffset = { x: 0, y: 0 };
    this._onGestureEvent = Animated.event(
      [
        {
          nativeEvent: {
            translationX: this._translateX,
            translationY: this._translateY,
          },
        },
      ],
      { useNativeDriver: USE_NATIVE_DRIVER }
    );
  }
  _onHandlerStateChange = event => {
    if (event.nativeEvent.oldState === State.ACTIVE) {
      this._lastOffset.x += event.nativeEvent.translationX;
      this._lastOffset.y += event.nativeEvent.translationY;
      this._translateX.setOffset(this._lastOffset.x);
      this._translateX.setValue(0);
      this._translateY.setOffset(this._lastOffset.y);
      this._translateY.setValue(0);
    }
  };
  render() {
    return (
      <PanGestureHandler
        {...this.props}
        onGestureEvent={this._onGestureEvent}
        onHandlerStateChange={this._onHandlerStateChange}
        id="dragbox">
        <Animated.View
          style={[
            styles.box,
            {
              transform: [
                { translateX: this._translateX },
                { translateY: this._translateY },
              ],
            },
          ]}
        />
      </PanGestureHandler>
    );
  }
}

export default class Example extends Component {
  _onClick = () => {
    Alert.alert("I'm so touched");
  };
  render() {
    return (
      <ScrollView style={styles.scrollView}>
        <LoremIpsum words={40} />
        <DraggableBox minDist={30} />
        <LoremIpsum />
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    flex: 1,
  },
  box: {
    width: 150,
    height: 150,
    alignSelf: 'center',
    backgroundColor: 'plum',
    margin: 10,
    zIndex: 200,
  },
});
<|endoftext|>


<commit_before>var ab = require('../lib/express-ab');
var assert = require('assert');
var express = require('express');
var request = require('supertest');

describe('weighted', function () {
    function setReqVarMiddleware(req, res, next) {
        req.ab = {
            random: req.get('ab-random'),
            weightSum: 0
        };
        next();
    }

    function skipRouteMiddleware(req, res, next) {
        next('route');
    }

    var app = express();
    var abTest = ab.test('unit-test');

    app.get('/', setReqVarMiddleware, abTest(null, 0.2), function (req, res) {
        res.send('variantA');
    });

    app.get('/', setReqVarMiddleware, abTest(null, 0.8), function (req, res) {
        res.send('variantB');
    });

    app.get('/random', abTest(null, 1), function (req, res) {
        res.send(req.ab);
    });

    describe('variant selection', function () {
        it('should set ab object on req', function (done) {
            request(app)
                .get('/random')
                .expect(function (res) {
                    assert('random' in res.body);
                    assert('weightSum' in res.body);
                })
                .end(done);
        });

        it('should select route A', function (done) {
            request(app)
                .get('/')
                .set('ab-random', 0.11)
                .expect(200)
                .expect('variantA', done);
        });

        it('should select route B', function (done) {
            request(app)
                .get('/')
                .set('ab-random', 0.42)
                .expect(200)
                .expect('variantB', done);
        });
    });

    describe('fallthrough', function () {

        app.get('/fallthrough', skipRouteMiddleware, setReqVarMiddleware, abTest(null, 0.5), function (req, res) {
            res.send('variantA');
        });

        app.get('/fallthrough', setReqVarMiddleware, abTest(null, 0.5), function (req, res) {
            res.send('variantB');
        });

        it('should fallthrough if first is skipped', function (done) {
            request(app)
                .get('/fallthrough')
                .set('ab-random', 0.42)
                .expect(200)
                .expect('variantB', done);
        });
    });
});<commit_msg>Formatting.<commit_after>var ab = require('../lib/express-ab');
var assert = require('assert');
var express = require('express');
var request = require('supertest');

describe('weighted', function () {
    function setReqVarMiddleware(req, res, next) {
        req.ab = {
            random: req.get('ab-random'),
            weightSum: 0
        };
        next();
    }

    function skipRouteMiddleware(req, res, next) {
        next('route');
    }

    var app = express();

    describe('variant selection', function () {
        var abTest = ab.test('variant-test');

        app.get('/', setReqVarMiddleware, abTest(null, 0.2), function (req, res) {
            res.send('variantA');
        });

        app.get('/', setReqVarMiddleware, abTest(null, 0.8), function (req, res) {
            res.send('variantB');
        });

        app.get('/random', abTest(null, 1), function (req, res) {
            res.send(req.ab);
        });

        it('should set ab object on req', function (done) {
            request(app)
                .get('/random')
                .expect(function (res) {
                    assert('random' in res.body);
                    assert('weightSum' in res.body);
                })
                .end(done);
        });

        it('should select route A', function (done) {
            request(app)
                .get('/')
                .set('ab-random', 0.11)
                .expect(200)
                .expect('variantA', done);
        });

        it('should select route B', function (done) {
            request(app)
                .get('/')
                .set('ab-random', 0.42)
                .expect(200)
                .expect('variantB', done);
        });
    });

    describe('fallthrough', function () {
        var abTest = ab.test('fallthrough-test');

        app.get('/fallthrough', skipRouteMiddleware, setReqVarMiddleware, abTest(null, 0.5), function (req, res) {
            res.send('variantA');
        });

        app.get('/fallthrough', setReqVarMiddleware, abTest(null, 0.5), function (req, res) {
            res.send('variantB');
        });

        it('should fallthrough if first is skipped', function (done) {
            request(app)
                .get('/fallthrough')
                .set('ab-random', 0.42)
                .expect(200)
                .expect('variantB', done);
        });
    });
});<|endoftext|>


<commit_before>function introScreen(url) {
	$("#gameBorder").hide();
	$("
", {
		id: "introScreen"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		overflow: "hidden",
		"text-align": "center",
		display: "none",
	}).appendTo("body")
	.html("");
	$("#introScreenImg").load(function() {
		$("#introScreen").fadeIn(4000);
		setTimeout(function() {
			finishIntroScreen();
		}, 7500);
	});
}

function finishIntroScreen() {
	$("#gameBorder").show();
	$("#introScreen").fadeOut(7000, function() {
		$("#introScreen").remove();
	});
}

function loadEndingScreen(url) {
	$("
", {
		id: "endingScreen"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		overflow: "hidden",
		"text-align": "center",
		display: "none",
	}).appendTo("body")
	.html("");
}

function showEndingScreen() {
	$("#gameBorder").fadeOut(10000);
	setTimeout(function() {
		$("#endingScreen").fadeIn(10000);
	}, 6000);
	setTimeout(function() {
		$("#endingScreen").fadeOut(60000);
	}, 24000);
}

function scrollFix() {
	setTimeout(function() {
		$("body").scrollTop(0);
	}, 100);
}

function act0Clear() {
	$("#divOutput").effect("drop", {direction: "up"}, 1000);
	setTimeout(function() {
		EndOutputSection ("intro")
		HideOutputSection ("intro")
		HideOutputSection ("title")
		ASLEvent("FinishAct0Clear", "");
	}, 1500);
}

function reshowOutput() {
	$("#divOutput").show();
}

function endAct0() {
	$("#divOutput").effect("drop", 1000);
	setTimeout(function() {
		EndOutputSection ("act01")
		HideOutputSection ("act01")
		ASLEvent("StartAct1", "");
	}, 1500);
}

function startAct1() {
	$("#divOutput").show();
}

var _heatherTextCount = 0;

function heatherText() {
	$("
", {
		id: "heatherText"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		overflow: "hidden"
	}).appendTo("body");
	doHeatherText();
}

function doHeatherText() {
	_heatherTextCount++;
	if (_heatherTextCount < 150) {
		setTimeout(function() {
			doHeatherText();
		}, 20);
	}
	else {
		$("#heatherText").fadeOut(2000, function() {
			$(this).remove();
		});
		setTimeout(function() {
			ASLEvent("JSFinish_HeatherText", "");
		}, 500);
	}
	var minLeft = -100;
	var minTop = -100;
	var maxLeft = $(window).width();
	var maxTop = $(window).height();
	for (var i = 0; i < 3; i++) {
		$("
", {
			text: "Heather"
		}).css({
			position: "absolute",
			left: getRandomInt(minLeft, maxLeft),
			top: getRandomInt(minTop, maxTop),
			"font-size": getRandomInt(8, 100) + "px",
			"font-family": "Georgia, serif",
			color: getRandomGrey(),
			opacity: Math.random(),
		}).appendTo("#heatherText");
	}
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomGrey() {
	var hex = Math.floor(Math.random() * 256).toString(16);
	return "#" + hex + hex + hex;
}

function blackout() {
	setTimeout(function() {
		$("
", {
			id: "blackout"
		}).css({
			position: "fixed",
			top: 0,
			left: 0,
			width: "100%",
			height: "100%",
			background: "black",
			display: "none"
		}).appendTo("body");
		$("#blackout").fadeIn({
			duration: 10000,
			easing: "easeInQuad",
		});
		speckles();
		setTimeout(function () {
			$("#speckles").remove();
			ASLEvent("JSFinish_Blackout", "");
		}, 11000);
		setTimeout(function () {
			$("#blackout").fadeOut({
				duration: 10000,
				easing: "easeInQuad",
				complete: function() {
					console.log("remove");
					$(this).remove();
				}
			});
		}, 12000);
	}, 1000);
}

function speckles() {
	$("
", {
		id: "speckles"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		overflow: "hidden"
	}).appendTo("body");
	doSpeckles();
}

var _speckleCount = 0;
var _speckleChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

function doSpeckles() {
	_speckleCount++;
	if (_speckleCount < 150) {
		setTimeout(function() {
			doSpeckles();
		}, 50);
	}
	var minLeft = -10;
	var minTop = -10;
	var maxLeft = $(window).width();
	var maxTop = $(window).height();
	for (var i = 0; i < 20; i++) {
		$("
", {
			text: _speckleChars.charAt(Math.floor(Math.random() * _speckleChars.length))
		}).css({
			position: "absolute",
			left: getRandomInt(minLeft, maxLeft),
			top: getRandomInt(minTop, maxTop),
			"font-size": getRandomInt(4, 10 + _speckleCount) + "px",
			"font-family": "Georgia, serif"
		}).appendTo("#speckles");
	}
}

function heatherTube() {
	setTimeout(function () {
		$("body").css("overflow-x", "hidden");
		$("
", {
			id: "heathertube",
			text: "HEATHER"
		}).css({
			position: "relative",
			left: "1200px",
			top: "0px",
			"font-size": "36pt",
			"font-family": "Georgia, serif"
		}).appendTo(getCurrentDiv());
		animateHeatherTube(200);
	}, 2000);
}

function animateHeatherTube(duration) {
	if (duration >= 2000) {
		$("#heathertube").animate({
			left: "0px"
		}, duration, "swing", function () {
			$("body").css("overflow-x", "inherit");
			$("#heathertube").fadeOut(3000, function() {
				ASLEvent("JSFinish_HeatherTube", "");
			});
		});
	}
	else {
		$("#heathertube").animate({
			left: "-1200px"
		}, duration, "linear", function () {
			$("#heathertube").css("left", "1200px");
			duration = duration * 1.5;
			animateHeatherTube(duration);
		});
	}
}

function act4Clear() {
	$("#divOutput").css({
		position: "relative"
	});
	$("body").css("overflow-x", "hidden");
	$("
", {
		id: "act4Fade"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		background: "white",
		display: "none"
	}).appendTo("body");
	$("#divOutput").animate({
		left: -($(window).width()/2 + $("#divOutput").width()/2)
	}, 2000, "swing", function() {
		animateAct4Clear(3000, 0);
	});
}

function animateAct4Clear(duration, count) {
	$("#divOutput").css({
		left: ($(window).width()/2 + $("#divOutput").width()/2)
	});
	$("#divOutput").animate({
		left: -($(window).width()/2 + $("#divOutput").width()/2)
	}, duration, "linear", function() {
		if (count == 0) {
			duration = duration / 1.2;
			if (duration < 500) {
				count = 1;
				$("#act4Fade").fadeIn(10000, function() {
				});
			}
			animateAct4Clear(duration, count);
		}
		else {
			count++;
			if (count > 20) {
				ASLEvent("JSFinish_Act4Clear", "");
			}
			else {
				animateAct4Clear(duration, count);
			}
		}
	});
}

function showEpilogue() {
	$("#divOutput").css({
		left: "1200px"
	});
	$("#act4Fade").remove();
	$("#divOutput").animate({
		left: "0px"
	}, 2000, "swing", function() {
		$("body").css("overflow-x", "inherit");
	});
}

function doScreenClear() {
	setTimeout(function() {
		ASLEvent("JSFinish_Clear", "");
	}, 1000);
}<commit_msg>Fix scrollFix...<commit_after>function introScreen(url) {
	$("#gameBorder").hide();
	$("
", {
		id: "introScreen"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		overflow: "hidden",
		"text-align": "center",
		display: "none",
	}).appendTo("body")
	.html("");
	$("#introScreenImg").load(function() {
		$("#introScreen").fadeIn(4000);
		setTimeout(function() {
			finishIntroScreen();
		}, 7500);
	});
}

function finishIntroScreen() {
	$("#gameBorder").show();
	$("#introScreen").fadeOut(7000, function() {
		$("#introScreen").remove();
	});
}

function loadEndingScreen(url) {
	$("
", {
		id: "endingScreen"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		overflow: "hidden",
		"text-align": "center",
		display: "none",
	}).appendTo("body")
	.html("");
}

function showEndingScreen() {
	$("#gameBorder").fadeOut(10000);
	setTimeout(function() {
		$("#endingScreen").fadeIn(10000);
	}, 6000);
	setTimeout(function() {
		$("#endingScreen").fadeOut(60000);
	}, 24000);
}

function scrollFix() {
	setTimeout(function() {
		$("html,body").scrollTop(0);
	}, 100);
}

function act0Clear() {
	$("#divOutput").effect("drop", {direction: "up"}, 1000);
	setTimeout(function() {
		EndOutputSection ("intro")
		HideOutputSection ("intro")
		HideOutputSection ("title")
		ASLEvent("FinishAct0Clear", "");
	}, 1500);
}

function reshowOutput() {
	$("#divOutput").show();
}

function endAct0() {
	$("#divOutput").effect("drop", 1000);
	setTimeout(function() {
		EndOutputSection ("act01")
		HideOutputSection ("act01")
		ASLEvent("StartAct1", "");
	}, 1500);
}

function startAct1() {
	$("#divOutput").show();
}

var _heatherTextCount = 0;

function heatherText() {
	$("
", {
		id: "heatherText"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		overflow: "hidden"
	}).appendTo("body");
	doHeatherText();
}

function doHeatherText() {
	_heatherTextCount++;
	if (_heatherTextCount < 150) {
		setTimeout(function() {
			doHeatherText();
		}, 20);
	}
	else {
		$("#heatherText").fadeOut(2000, function() {
			$(this).remove();
		});
		setTimeout(function() {
			ASLEvent("JSFinish_HeatherText", "");
		}, 500);
	}
	var minLeft = -100;
	var minTop = -100;
	var maxLeft = $(window).width();
	var maxTop = $(window).height();
	for (var i = 0; i < 3; i++) {
		$("
", {
			text: "Heather"
		}).css({
			position: "absolute",
			left: getRandomInt(minLeft, maxLeft),
			top: getRandomInt(minTop, maxTop),
			"font-size": getRandomInt(8, 100) + "px",
			"font-family": "Georgia, serif",
			color: getRandomGrey(),
			opacity: Math.random(),
		}).appendTo("#heatherText");
	}
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomGrey() {
	var hex = Math.floor(Math.random() * 256).toString(16);
	return "#" + hex + hex + hex;
}

function blackout() {
	setTimeout(function() {
		$("
", {
			id: "blackout"
		}).css({
			position: "fixed",
			top: 0,
			left: 0,
			width: "100%",
			height: "100%",
			background: "black",
			display: "none"
		}).appendTo("body");
		$("#blackout").fadeIn({
			duration: 10000,
			easing: "easeInQuad",
		});
		speckles();
		setTimeout(function () {
			$("#speckles").remove();
			ASLEvent("JSFinish_Blackout", "");
		}, 11000);
		setTimeout(function () {
			$("#blackout").fadeOut({
				duration: 10000,
				easing: "easeInQuad",
				complete: function() {
					console.log("remove");
					$(this).remove();
				}
			});
		}, 12000);
	}, 1000);
}

function speckles() {
	$("
", {
		id: "speckles"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		overflow: "hidden"
	}).appendTo("body");
	doSpeckles();
}

var _speckleCount = 0;
var _speckleChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

function doSpeckles() {
	_speckleCount++;
	if (_speckleCount < 150) {
		setTimeout(function() {
			doSpeckles();
		}, 50);
	}
	var minLeft = -10;
	var minTop = -10;
	var maxLeft = $(window).width();
	var maxTop = $(window).height();
	for (var i = 0; i < 20; i++) {
		$("
", {
			text: _speckleChars.charAt(Math.floor(Math.random() * _speckleChars.length))
		}).css({
			position: "absolute",
			left: getRandomInt(minLeft, maxLeft),
			top: getRandomInt(minTop, maxTop),
			"font-size": getRandomInt(4, 10 + _speckleCount) + "px",
			"font-family": "Georgia, serif"
		}).appendTo("#speckles");
	}
}

function heatherTube() {
	setTimeout(function () {
		$("body").css("overflow-x", "hidden");
		$("
", {
			id: "heathertube",
			text: "HEATHER"
		}).css({
			position: "relative",
			left: "1200px",
			top: "0px",
			"font-size": "36pt",
			"font-family": "Georgia, serif"
		}).appendTo(getCurrentDiv());
		animateHeatherTube(200);
	}, 2000);
}

function animateHeatherTube(duration) {
	if (duration >= 2000) {
		$("#heathertube").animate({
			left: "0px"
		}, duration, "swing", function () {
			$("body").css("overflow-x", "inherit");
			$("#heathertube").fadeOut(3000, function() {
				ASLEvent("JSFinish_HeatherTube", "");
			});
		});
	}
	else {
		$("#heathertube").animate({
			left: "-1200px"
		}, duration, "linear", function () {
			$("#heathertube").css("left", "1200px");
			duration = duration * 1.5;
			animateHeatherTube(duration);
		});
	}
}

function act4Clear() {
	$("#divOutput").css({
		position: "relative"
	});
	$("body").css("overflow-x", "hidden");
	$("
", {
		id: "act4Fade"
	}).css({
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		background: "white",
		display: "none"
	}).appendTo("body");
	$("#divOutput").animate({
		left: -($(window).width()/2 + $("#divOutput").width()/2)
	}, 2000, "swing", function() {
		animateAct4Clear(3000, 0);
	});
}

function animateAct4Clear(duration, count) {
	$("#divOutput").css({
		left: ($(window).width()/2 + $("#divOutput").width()/2)
	});
	$("#divOutput").animate({
		left: -($(window).width()/2 + $("#divOutput").width()/2)
	}, duration, "linear", function() {
		if (count == 0) {
			duration = duration / 1.2;
			if (duration < 500) {
				count = 1;
				$("#act4Fade").fadeIn(10000, function() {
				});
			}
			animateAct4Clear(duration, count);
		}
		else {
			count++;
			if (count > 20) {
				ASLEvent("JSFinish_Act4Clear", "");
			}
			else {
				animateAct4Clear(duration, count);
			}
		}
	});
}

function showEpilogue() {
	$("#divOutput").css({
		left: "1200px"
	});
	$("#act4Fade").remove();
	$("#divOutput").animate({
		left: "0px"
	}, 2000, "swing", function() {
		$("body").css("overflow-x", "inherit");
	});
}

function doScreenClear() {
	setTimeout(function() {
		ASLEvent("JSFinish_Clear", "");
	}, 1000);
}<|endoftext|>


<commit_before>import findTabbable from "../helpers/tabbable";

const focusLaterElements = [];
let modalElement = null;
let needToFocus = false;

export function handleBlur() {
  needToFocus = true;
}

export function handleFocus() {
  if (needToFocus) {
    needToFocus = false;
    if (!modalElement) {
      return;
    }
    // need to see how jQuery shims document.on('focusin') so we don't need the
    // setTimeout, firefox doesn't support focusin, if it did, we could focus
    // the element outside of a setTimeout. Side-effect of this implementation
    // is that the document.body gets focus, and then we focus our element right
    // after, seems fine.
    setTimeout(() => {
      if (modalElement.contains(document.activeElement)) {
        return;
      }
      const el = findTabbable(modalElement)[0] || modalElement;
      el.focus();
    }, 0);
  }
}

export function markForFocusLater() {
  focusLaterElements.push(document.activeElement);
}

/* eslint-disable no-console */
export function returnFocus() {
  let toFocus = null;
  try {
    toFocus = focusLaterElements.pop();
    toFocus.focus();
    return;
  } catch (e) {
    console.warn(
      [
        "You tried to return focus to",
        toFocus,
        "but it is not in the DOM anymore"
      ].join(" ")
    );
  }
}
/* eslint-enable no-console */

export function popWithoutFocus() {
  focusLaterElements.length > 0 && focusLaterElements.pop();
}

export function setupScopedFocus(element) {
  modalElement = element;

  if (window.addEventListener) {
    window.addEventListener("blur", handleBlur, false);
    document.addEventListener("focus", handleFocus, true);
  } else {
    window.attachEvent("onBlur", handleBlur);
    document.attachEvent("onFocus", handleFocus);
  }
}

export function teardownScopedFocus() {
  modalElement = null;

  if (window.addEventListener) {
    window.removeEventListener("blur", handleBlur);
    document.removeEventListener("focus", handleFocus);
  } else {
    window.detachEvent("onBlur", handleBlur);
    document.detachEvent("onFocus", handleFocus);
  }
}
<commit_msg>[fixed] check if focusLaterElements is empty before popping<commit_after>import findTabbable from "../helpers/tabbable";

const focusLaterElements = [];
let modalElement = null;
let needToFocus = false;

export function handleBlur() {
  needToFocus = true;
}

export function handleFocus() {
  if (needToFocus) {
    needToFocus = false;
    if (!modalElement) {
      return;
    }
    // need to see how jQuery shims document.on('focusin') so we don't need the
    // setTimeout, firefox doesn't support focusin, if it did, we could focus
    // the element outside of a setTimeout. Side-effect of this implementation
    // is that the document.body gets focus, and then we focus our element right
    // after, seems fine.
    setTimeout(() => {
      if (modalElement.contains(document.activeElement)) {
        return;
      }
      const el = findTabbable(modalElement)[0] || modalElement;
      el.focus();
    }, 0);
  }
}

export function markForFocusLater() {
  focusLaterElements.push(document.activeElement);
}

/* eslint-disable no-console */
export function returnFocus() {
  let toFocus = null;
  try {
    if (focusLaterElements.length !== 0) {
      toFocus = focusLaterElements.pop();
      toFocus.focus();
    }
    return;
  } catch (e) {
    console.warn(
      [
        "You tried to return focus to",
        toFocus,
        "but it is not in the DOM anymore"
      ].join(" ")
    );
  }
}
/* eslint-enable no-console */

export function popWithoutFocus() {
  focusLaterElements.length > 0 && focusLaterElements.pop();
}

export function setupScopedFocus(element) {
  modalElement = element;

  if (window.addEventListener) {
    window.addEventListener("blur", handleBlur, false);
    document.addEventListener("focus", handleFocus, true);
  } else {
    window.attachEvent("onBlur", handleBlur);
    document.attachEvent("onFocus", handleFocus);
  }
}

export function teardownScopedFocus() {
  modalElement = null;

  if (window.addEventListener) {
    window.removeEventListener("blur", handleBlur);
    document.removeEventListener("focus", handleFocus);
  } else {
    window.detachEvent("onBlur", handleBlur);
    document.detachEvent("onFocus", handleFocus);
  }
}
<|endoftext|>


<commit_before>require("ehr/triggers").initScript(this);
var WNPRC = require("wnprc_ehr/WNPRC").WNPRC;
let allowUsersMap = null;

function onInit(event, helper){
    helper.setScriptOptions({
        allowFutureDates: true,
        allowDatesInDistantPast: true
    });
    //TODO: query the allow user table
    //columns: allowuserid and project
    //define mapping and populate

}

function onBeforeUpdate(row, oldRow, scriptErrors){
    //TODO: query allowUserMap

    let waterAdmin = false;

    if (row && row.project){
        let currentUser = LABKEY.Security.currentUser.id;

    }
    // if user not found
    scriptErrors = " not have permissions";

}

function onUpsert(helper, scriptErrors, row, oldRow){

    if (row.Id){
        EHR.Server.Utils.findDemographics({
            participant: row.Id,
            helper: helper,
            scope: this,
            callback: function(data){
                if(data){
                    if(!row.project){
                        EHR.Server.Utils.addError(scriptErrors, 'project', 'Must enter a project for all center animals.', 'WARN');

                    }
                }
            }
        });
        var animalRestricted = {};
        animalRestricted = WNPRC.Utils.getJavaHelper().checkIfAnimalInCondition(row.Id, row.date);
        //console.log (animalRestricted);
        if (!animalRestricted && !row.skipWaterRegulationCheck){
            EHR.Server.Utils.addError(scriptErrors,'Id', 'Animal not assigned to water restriction protocol or is already in ' + row.waterSource + ' condition.', 'ERROR');
        }

    }

    var today = new Date();
    //console.log("Value of date " + row.date);
    //console.log("Value of start date " + row.startdate);
    today.setHours(0,0,0,0);

    var rowDate = new Date(row.date);
    rowDate.setHours(0,0,0,0);
    EHR.Server.Utils.removeTimeFromDate(row,scriptErrors,"date");

    //console.log("Value of date " + rowDate + " "+ rowDate.getTime());
    //console.log("Value of start date " + row.startdate);
    //console.log("Value of today "+ today+ " "+ today.getTime());

    //TODO: allow updates of existing records.
    if(!(rowDate.getTime() >= today.getTime()) && (oldRow.objectid != row.objectid)){
        EHR.Server.Utils.addError(scriptErrors, 'date', 'Only Dates in the Future Allow', 'ERROR');
    }

    var endDate = new Date(row.enddate);
    endDate.setHours(0,0,0,0);

    //This does not get checked when the dataset if updated, only when using Ext4 form
    if (rowDate.getTime() > endDate.getTime()){
        EHR.Server.Utils.addError(scriptErrors,'endDate', 'EndDate cannot be before StartDate', 'ERROR');
    }

    if (!row.frequency && row.waterSource == 'regulated'){
        EHR.Server.Utils.addError(scriptErrors, 'frequency', 'Frequency is required when entering regulated water orders.', 'ERROR');
    }
    if (!row.volume && row.waterSource == 'regulated'){
        //console.log ("water vol "+ row.volume);
        EHR.Server.Utils.addError(scriptErrors, 'volume', 'Volume is required when entering regulated water orders.', 'ERROR');
    }

    if (!row.assignedTo && row.waterSource == 'regulated'){
        EHR.Server.Utils.addError(scriptErrors, 'assignedTo', 'Assigned To is required when entering regulated water orders.', 'ERROR');
    }

    if (!row.waterSource){
        EHR.Server.Utils.addError(scriptErrors, 'waterSource', 'Water Source is required when entering new orders.', 'ERROR');
    }

    //console.log ("value of ObjectId "+oldRow.objectid + " Value of new objectId "+ row.objectid);
   //console.log ('skipWaterRegulation '+ row.skipWaterRegulationCheck);
   // if (oldRow && row.date && row.Id && row.frequency && (oldRow.objectid != row.objectid)) {
    if (row.project && row.objectid && row.Id && row.date && row.frequency && row.assignedTo && row.waterSource != 'lixit' && !row.skipWaterRegulationCheck) {
        console.log('value of row: frequency ' + row.frequency + ' value of waterSource ' + row.waterSource);
        let jsonArray = WNPRC.Utils.getJavaHelper().checkWaterRegulation(row.id, row.date, row.enddate ? row.enddate : null, row.frequency, row.waterSource, row.objectid, row.project, this.extraContext);
        if (jsonArray != null) {
            for (var i = 0; i < jsonArray.length; i++) {
                var errorObject = JSON.parse(jsonArray[i]);
                EHR.Server.Utils.addError(scriptErrors, errorObject.field, errorObject.message, errorObject.severity);
            }
        }
        row.date = rowDate;
    }

    //if (oldRow && oldRow.waterSource == 'regulated' && row.waterSource == 'lixit'){
    //TODO: by pass water regulation to change water order to lixit and also chnage the water regulated animals data
    if ( row.waterSource == 'lixit' && !row.skipWaterRegulationCheck && !oldRow){

        let jsonArray = WNPRC.Utils.getJavaHelper().changeWaterScheduled(row.id,row.date,row.waterSource, row.project, row.objectid,this.extraContext);
        let jsonExtraContext = this.extraContext.extraContextArray;

        if (jsonArray != null){
            for (var i=0; i < jsonArray.length; i++){
                let errorObject = JSON.parse(jsonArray[i]);
                EHR.Server.Utils.addError(scriptErrors,errorObject.field, errorObject.message, errorObject.severity);

            }
            console.log(" Printing Extra Context" + jsonExtraContext);
            if (jsonExtraContext != null){
                for (var i = 0; i < jsonExtraContext.length; i++){
                    let extraContextObject = jsonExtraContext[i];
                    let date =  extraContextObject.date;
                    let dateOnly = new Date(date.getTime());
                    dateOnly = dateOnly.getFullYear()+ "-" +dateOnly.getMonth()+ "-" + dateOnly.getDate();
                    let infoMessage = "Water Order for "+ row.Id + " started on " + dateOnly + " with frequency of " + extraContextObject.frequency + " and volume of " + extraContextObject.volume + "ml will close.";
                    //console.log(infoMessage);
                    EHR.Server.Utils.addError(scriptErrors,"waterSource",infoMessage,"INFO")

                }

            }

        }
    }

}
<commit_msg>Implementing waterOrder permissions based on watermonitoring_access table<commit_after>require("ehr/triggers").initScript(this);
var WNPRC = require("wnprc_ehr/WNPRC").WNPRC;
let allowUsersMap = {};

function onInit(event, helper){
    helper.setScriptOptions({
        allowFutureDates: true,
        allowDatesInDistantPast: true
    });
    LABKEY.Query.selectRows({
        requiredVersion: 9.1,
        schemaName: 'wnprc',
        queryName: 'watermonitoring_access',
        columns:['alloweduser/UserId,project'],
        scope: this,
        success: function(results) {
            var rows = results.rows;
            for(var i=0; i<rows.length; i++){
                var row = rows[i];
                if (allowUsersMap[row["alloweduser/UserId"]["value"]] === undefined){
                    let projectArray = [row["project"]["value"]];
                    allowUsersMap[row["alloweduser/UserId"]["value"]]=projectArray;
                }else{
                    var tempItem = allowUsersMap[row["alloweduser/UserId"]["value"]];
                    tempItem.push(row["project"]["value"]);
                    allowUsersMap[row["alloweduser/UserId"]["value"]]=tempItem;
                }
            }
        },
        failure: function (error) {
            console.log("Error getting data from wnprc.watermonitoring_access while uploading water orders data: " + error);
        }
    });
}

function onUpsert(helper, scriptErrors, row, oldRow){

    if (row.Id){
        EHR.Server.Utils.findDemographics({
            participant: row.Id,
            helper: helper,
            scope: this,
            callback: function(data){
                if(data){
                    if(!row.project){
                        EHR.Server.Utils.addError(scriptErrors, 'project', 'Must enter a project for all center animals.', 'WARN');

                    }
                }
            }
        });
        var animalRestricted = {};
        animalRestricted = WNPRC.Utils.getJavaHelper().checkIfAnimalInCondition(row.Id, row.date);
        //console.log (animalRestricted);
        if (!animalRestricted && !row.skipWaterRegulationCheck){
            EHR.Server.Utils.addError(scriptErrors,'Id', 'Animal not assigned to water restriction protocol or is already in ' + row.waterSource + ' condition.', 'ERROR');
        }

    }

    var today = new Date();
    today.setHours(0,0,0,0);

    var rowDate = new Date(row.date);
    rowDate.setHours(0,0,0,0);
    EHR.Server.Utils.removeTimeFromDate(row,scriptErrors,"date");

    //TODO: allow updates of existing records.
    if(!(rowDate.getTime() >= today.getTime()) && (oldRow.objectid != row.objectid)){
        EHR.Server.Utils.addError(scriptErrors, 'date', 'Only Dates in the Future Allow', 'ERROR');
    }

    var endDate = new Date(row.enddate);
    endDate.setHours(0,0,0,0);

    //This does not get checked when the dataset if updated, only when using Ext4 form
    if (rowDate.getTime() > endDate.getTime()){
        EHR.Server.Utils.addError(scriptErrors,'endDate', 'EndDate cannot be before StartDate', 'ERROR');
    }

    if (!row.frequency && row.waterSource == 'regulated'){
        EHR.Server.Utils.addError(scriptErrors, 'frequency', 'Frequency is required when entering regulated water orders.', 'ERROR');
    }
    if (!row.volume && row.waterSource == 'regulated'){
        //console.log ("water vol "+ row.volume);
        EHR.Server.Utils.addError(scriptErrors, 'volume', 'Volume is required when entering regulated water orders.', 'ERROR');
    }

    if (!row.assignedTo && row.waterSource == 'regulated'){
        EHR.Server.Utils.addError(scriptErrors, 'assignedTo', 'Assigned To is required when entering regulated water orders.', 'ERROR');
    }

    if (!row.waterSource){
        EHR.Server.Utils.addError(scriptErrors, 'waterSource', 'Water Source is required when entering new orders.', 'ERROR');
    }

    //console.log ("value of ObjectId "+oldRow.objectid + " Value of new objectId "+ row.objectid);
   //console.log ('skipWaterRegulation '+ row.skipWaterRegulationCheck);
   // if (oldRow && row.date && row.Id && row.frequency && (oldRow.objectid != row.objectid)) {
    if (row.project && row.objectid && row.Id && row.date && row.frequency && row.assignedTo && row.waterSource != 'lixit' && !row.skipWaterRegulationCheck) {
        console.log('value of row: frequency ' + row.frequency + ' value of waterSource ' + row.waterSource);
        let jsonArray = WNPRC.Utils.getJavaHelper().checkWaterRegulation(row.id, row.date, row.enddate ? row.enddate : null, row.frequency, row.waterSource, row.objectid, row.project, this.extraContext);
        if (jsonArray != null) {
            for (var i = 0; i < jsonArray.length; i++) {
                var errorObject = JSON.parse(jsonArray[i]);
                EHR.Server.Utils.addError(scriptErrors, errorObject.field, errorObject.message, errorObject.severity);
            }
        }
        row.date = rowDate;
    }

    //if (oldRow && oldRow.waterSource == 'regulated' && row.waterSource == 'lixit'){
    //TODO: by pass water regulation to change water order to lixit and also chnage the water regulated animals data
    if ( row.waterSource == 'lixit' && !row.skipWaterRegulationCheck && !oldRow){

        let jsonArray = WNPRC.Utils.getJavaHelper().changeWaterScheduled(row.id,row.date,row.waterSource, row.project, row.objectid,this.extraContext);
        let jsonExtraContext = this.extraContext.extraContextArray;

        if (jsonArray != null){
            for (var i=0; i < jsonArray.length; i++){
                let errorObject = JSON.parse(jsonArray[i]);
                EHR.Server.Utils.addError(scriptErrors,errorObject.field, errorObject.message, errorObject.severity);

            }
            console.log(" Printing Extra Context" + jsonExtraContext);
            if (jsonExtraContext != null){
                for (var i = 0; i < jsonExtraContext.length; i++){
                    let extraContextObject = jsonExtraContext[i];
                    let date =  extraContextObject.date;
                    let dateOnly = new Date(date.getTime());
                    dateOnly = dateOnly.getFullYear()+ "-" +dateOnly.getMonth()+ "-" + dateOnly.getDate();
                    let infoMessage = "Water Order for "+ row.Id + " started on " + dateOnly + " with frequency of " + extraContextObject.frequency + " and volume of " + extraContextObject.volume + "ml will close.";
                    //console.log(infoMessage);
                    EHR.Server.Utils.addError(scriptErrors,"waterSource",infoMessage,"INFO")

                }

            }

        }
    }

}

function onUpdate(helper, scriptErrors, row, oldRow){

    let waterOrdersAdmin = false;

    if (row && row.project){
        let currentUser = LABKEY.Security.currentUser.id;
        let allowProjects = allowUsersMap[currentUser];
        allowProjects.forEach(function (project){
            if (row.project === project){
                waterOrdersAdmin = true;
            }
        })
        console.log(waterOrdersAdmin);
        if (!waterOrdersAdmin){
            EHR.Server.Utils.addError(scriptErrors,'project','User does not have permission to edit water order','ERROR')
        }
    }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import MessageListItem from './MessageListItem'
import { insert_anchor } from '../utils/transform'

class MessageList extends Component {

  arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
      return false;
    for(var i = arr1.length; i--;) {
      if(arr1[i] !== arr2[i])
        return false;
    }
    return true;
  }

  shouldComponentUpdate(nextProps, nextState) {
    const newMessages = nextProps.messages
    const messages = this.props.messages
    const shouldUpdate = !this.arraysEqual(newMessages, messages)
    return shouldUpdate
  }

  componentDidUpdate(prevProps, prevState) {
    this.scrollToBottom()
  }

  componentDidMount() {
    this.scrollToBottom()
  }

  scrollToBottom = () => {
    this.messagesEnd.scrollIntoView()
  }

  generateTextComponentFromMessage = (m) => {
    return insert_anchor(m.text, m.id)
  }

  render() {
    const { currentUserId, userIds, messages, authorId } = this.props
    const renderForParticipants = userIds.indexOf(currentUserId) > -1
    return (

          {messages.map(m => {
            const isAuthor = m.createdByUserId === authorId
            const renderMessageRightSide = !renderForParticipants ? isAuthor : m.createdByUserId === currentUserId

            // show plato face on public message or the other user
            const showPlatoFace = !renderForParticipants || !renderMessageRightSide
            return (

                <MessageListItem
                  mid={m.id}
                  isAuthorStyle={isAuthor}
                  showPlatoFace={showPlatoFace}
                  text={m.text}
                  subText={moment(m.createdAt).fromNow()}
                />

            )
          })}

        {this.props.isClosed &&

...End of chat...

        }

 { this.messagesEnd = el; }}>

    );
  }
}

MessageList.propTypes = {
  userIds: PropTypes.array.isRequired,
  authorId: PropTypes.string.isRequired,
  messages: PropTypes.array.isRequired,
  currentUserId: PropTypes.string,
  isClosed: PropTypes.bool.isRequired,
}

export default MessageList
<commit_msg>Remove unused class<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import MessageListItem from './MessageListItem'
import { insert_anchor } from '../utils/transform'

class MessageList extends Component {

  arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
      return false;
    for(var i = arr1.length; i--;) {
      if(arr1[i] !== arr2[i])
        return false;
    }
    return true;
  }

  shouldComponentUpdate(nextProps, nextState) {
    const newMessages = nextProps.messages
    const messages = this.props.messages
    const shouldUpdate = !this.arraysEqual(newMessages, messages)
    return shouldUpdate
  }

  componentDidUpdate(prevProps, prevState) {
    this.scrollToBottom()
  }

  componentDidMount() {
    this.scrollToBottom()
  }

  scrollToBottom = () => {
    this.messagesEnd.scrollIntoView()
  }

  generateTextComponentFromMessage = (m) => {
    return insert_anchor(m.text, m.id)
  }

  render() {
    const { currentUserId, userIds, messages, authorId } = this.props
    const renderForParticipants = userIds.indexOf(currentUserId) > -1
    return (

          {messages.map(m => {
            const isAuthor = m.createdByUserId === authorId
            const renderMessageRightSide = !renderForParticipants ? isAuthor : m.createdByUserId === currentUserId

            // show plato face on public message or the other user
            const showPlatoFace = !renderForParticipants || !renderMessageRightSide
            return (

                <MessageListItem
                  mid={m.id}
                  isAuthorStyle={isAuthor}
                  showPlatoFace={showPlatoFace}
                  text={m.text}
                  subText={moment(m.createdAt).fromNow()}
                />

            )
          })}

        {this.props.isClosed &&

...End of chat...

        }

 { this.messagesEnd = el; }}>

    );
  }
}

MessageList.propTypes = {
  userIds: PropTypes.array.isRequired,
  authorId: PropTypes.string.isRequired,
  messages: PropTypes.array.isRequired,
  currentUserId: PropTypes.string,
  isClosed: PropTypes.bool.isRequired,
}

export default MessageList
<|endoftext|>