<commit_before>var Util, DOM, CloudFunc, CloudCmd;

(function (Util, DOM, CloudFunc, CloudCmd) {
    'use strict';

     CloudCmd.Listeners = new ListenersProto(Util, DOM, CloudFunc, CloudCmd);

     function ListenersProto(Util, DOM, CloudFunc, CloudCmd) {
        var Info                = DOM.CurrentInfo,
            Storage             = DOM.Storage,
            Events              = DOM.Events,
            Files               = DOM.Files,
            EventsFiles         = {
                'mousedown'     : Util.exec.with(execIfNotUL, setCurrentFileByEvent),
                'contextmenu'   : onContextMenu,
                'click'         : onClick,
                'dragstart'     : Util.exec.with(execIfNotUL, onDragStart),
                'dblclick'      : Util.exec.with(execIfNotUL, onDblClick),
                'touchstart'    : Util.exec.with(execIfNotUL, onTouch)
            };

        this.init = function () {
            appStorage();
            contextMenu();
            dragndrop();
            unload();
            pop();
            online();
            mousemove();
        };

        this.initKeysPanel          = function() {
            var keysElement     = DOM.getById('js-keyspanel');

            if (keysElement)
                Events.addClick(keysElement, function(event) {
                    var element = event.target,
                        id      = element.id,

                        clickFuncs      = {
                            'f1'        : CloudCmd.Help.show,
                            'f3'        : CloudCmd.View.show,
                            'f4'        : CloudCmd.Edit.show,
                            'f9'        : CloudCmd.Menu.show,
                            'f10'       : CloudCmd.Config.show,
                            '~'         : CloudCmd.Konsole.show,
                            'contact'   : CloudCmd.Contact.show,

                            'f2'        : DOM.renameCurrent,
                            'f5'        : DOM.copyFiles,
                            'f6'        : DOM.moveFiles,
                            'f7'        : DOM.promptNewDir,
                            'f8'        : DOM.promptDelete
                        },

                        func    = clickFuncs[id];

                    Util.exec(func);

                });
        };

        this.setOnPanel             = function(panelId) {
            var panel           = DOM.getById(panelId),
                filesElement    = DOM.getByDataName('js-files', panel),
                pathElement     = DOM.getByDataName('js-path', panel);

            /* ставим загрузку гифа на клик*/
            Events.addClick(pathElement, onPathElementClick);
            Events.add(filesElement, EventsFiles);
        };

        function onPathElementClick(event) {
            var link, href, url,
                element     = event.target,
                attr        = element.getAttribute('data-name');

            switch (attr) {
            case 'js-clear-storage':
                Storage.clear();
                break;

            case 'js-refresh':
                CloudCmd.refresh();
                event.preventDefault();
                break;

            case 'js-path-link':
                url         = CloudCmd.HOST;
                href        = element.href;
                link        = Util.rmStr(href, url);
                /*
                 * browser do not replace % -> %25%
                 * do it for him
                 */
                link        = Util.replaceStr(link, '%%', '%25%');
                link        = decodeURI(link);
                link        = Util.rmStrOnce(link, CloudFunc.FS) || '/';

                CloudCmd.loadDir({
                    path        : link,
                    isRefresh   : false
                });

                event.preventDefault();
            }
        }

        function mousemove() {
            DOM.Events.add('mousemove', function(event) {
                var position    = CloudCmd.MousePosition,
                    x           = event.clientX,
                    y           = event.clientY;

                position.x      = x;
                position.y      = y;
            });
        }

        function execIfNotUL(callback, event) {
            var element = event.target,
                tag     = element.tagName;

            if (tag !== 'UL')
                Util.exec(callback, event);
        }

        function onClick(event) {
            var ctrl    = event.ctrlKey;

            if (!ctrl)
                Events.preventDefault(event);

            changePanel(event.target);
        }

        function changePanel(element) {
            var panel   = Info.panel,
                files   = DOM.getByDataName('js-files', panel),
                ul      = getULElement(element);

            if (ul !== files)
                DOM.changePanel();
        }

        function onDblClick(event) {
            var current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current),
                path        = DOM.getCurrentPath(current);

            path    = CloudFunc.rmLastSlash(path);

            if (isDir) {
                CloudCmd.loadDir({
                    path: path
                });

                Events.preventDefault(event);
            }
        }

        function onTouch(event) {
            var isCurrent,
                current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current);

            if (isDir) {
                isCurrent   = DOM.isCurrentFile(current);

                if (isCurrent) {
                    CloudCmd.loadDir({
                        path: DOM.getCurrentPath(current)
                    });

                    Events.preventDefault(event);
                }
            }
        }

        function onContextMenu(event) {
            var element = event.target,
                tag     = element.tagName,
                isUL    = tag === 'UL';

            if (!isUL) {
                element     = getLIElement(event.target);
                DOM.setCurrentFile(element);
            }

            Util.exec(CloudCmd.Menu, {
                x: event.clientX,
                y: event.clientY
            });

            changePanel(element);
        }

         /*
          * download file from browser to desktop
          * in Chrome (HTML5)
          */
        function onDragStart(event) {
            var element     = getLIElement(event.target),
                EXT         = 'json',
                isDir       = Info.isDir,
                link        = DOM.getCurrentLink(element),
                name        = DOM.getCurrentName(element);

            /* if it's directory - adding json extension */
            if (isDir) {
                name       += '.' + EXT;
                link       += '?' + EXT;
            }

            event.dataTransfer.setData('DownloadURL',
                'application/octet-stream'  + ':' +
                name                        + ':' +
                link);
        }

        function getLIElement(element) {
            if (element)
                while (element.tagName !== 'LI')
                    element = element.parentElement;

            return element;
        }

        function getULElement(element) {
            while (element.tagName !== 'UL')
                element     = element.parentElement;

            return element;
        }

        function setCurrentFileByEvent(event) {
            var element = getLIElement(event.target);
            DOM.setCurrentFile(element);
        }

        function appStorage() {
            Files.get('config', function(error, config) {
                var isAppStorage  = config.appStorage,
                    appStorage    = window.applicationStorage;

                if (isAppStorage && appStorage)
                    Events.add('updateready', appStorage, function() {
                        var ret = confirm('An update is available. Reload now?');

                        if (ret)
                            location.reload();

                    });
                });
        }

        function contextMenu() {
            Events.addContextMenu(document, function(event) {
                CloudCmd.Menu.ENABLED || Events.preventDefault(event);
            });
        }

        function dragndrop() {
            var panels          = DOM.getByClassAll('panel'),
                preventDefault  = function (event) {
                    event.preventDefault();
                },
                toggle          = function () {
                    Util.forEach(panels, function(panel) {
                        DOM.toggleClass(panel, 'selected-panel');
                    });
                },
                onDrop          = function (event) {
                    var files   = event.dataTransfer.files;

                    preventDefault(event);
                    DOM.uploadFiles(files);
                };

            Events.add(['dragenter', 'dragleave', 'drop'], toggle);

            Util.forEach(panels, function(panel) {
                Events.add('dragover', panel, preventDefault)
                      .add('drop', panel, onDrop);
            });
        }

        function unload() {
            DOM.Events.add(['unload', 'beforeunload'], function (event) {
                var ret,
                    Key     = CloudCmd.Key,
                    isBind  = Key && Key.isBind();

                if (!isBind) {
                    Events.preventDefault(event);
                    ret = 'Please make sure that you saved all work.';
                }

                return ret;
            });
        }

        function pop() {
            Events.add('popstate', function(event) {
                var path    = event.state;

                path        = Util.rmStrOnce(path, CloudFunc.FS);

                if (path)
                    CloudCmd.loadDir({
                        path        : path,
                        history     : false
                    });
                else
                    CloudCmd.route(location.hash);
            });
        }

        function online() {
            var cssSet = DOM.load.style.bind(null, {
                    id      :'local-droids-font',
                    element : document.head,
                    inner   :   '@font-face {font-family: "Droid Sans Mono";'           +
                                'font-style: normal;font-weight: normal;'               +
                                'src: local("Droid Sans Mono"), local("DroidSansMono"),'+
                                ' url("/font/DroidSansMono.woff") format("woff");}'
                });

            if (navigator.onLine)
                Events.addOnce('offline', cssSet);
            else
                cssSet();
        }

     }

})(Util, DOM, CloudFunc, CloudCmd);
<commit_msg>refactor(listeners) execIfNotUL: Util.exec -> callback<commit_after>var Util, DOM, CloudFunc, CloudCmd;

(function (Util, DOM, CloudFunc, CloudCmd) {
    'use strict';

     CloudCmd.Listeners = new ListenersProto(Util, DOM, CloudFunc, CloudCmd);

     function ListenersProto(Util, DOM, CloudFunc, CloudCmd) {
        var Info                = DOM.CurrentInfo,
            Storage             = DOM.Storage,
            Events              = DOM.Events,
            Files               = DOM.Files,
            EventsFiles         = {
                'mousedown'     : Util.exec.with(execIfNotUL, setCurrentFileByEvent),
                'contextmenu'   : onContextMenu,
                'click'         : onClick,
                'dragstart'     : Util.exec.with(execIfNotUL, onDragStart),
                'dblclick'      : Util.exec.with(execIfNotUL, onDblClick),
                'touchstart'    : Util.exec.with(execIfNotUL, onTouch)
            };

        this.init = function () {
            appStorage();
            contextMenu();
            dragndrop();
            unload();
            pop();
            online();
            mousemove();
        };

        this.initKeysPanel          = function() {
            var keysElement     = DOM.getById('js-keyspanel');

            if (keysElement)
                Events.addClick(keysElement, function(event) {
                    var element = event.target,
                        id      = element.id,

                        clickFuncs      = {
                            'f1'        : CloudCmd.Help.show,
                            'f3'        : CloudCmd.View.show,
                            'f4'        : CloudCmd.Edit.show,
                            'f9'        : CloudCmd.Menu.show,
                            'f10'       : CloudCmd.Config.show,
                            '~'         : CloudCmd.Konsole.show,
                            'contact'   : CloudCmd.Contact.show,

                            'f2'        : DOM.renameCurrent,
                            'f5'        : DOM.copyFiles,
                            'f6'        : DOM.moveFiles,
                            'f7'        : DOM.promptNewDir,
                            'f8'        : DOM.promptDelete
                        },

                        func    = clickFuncs[id];

                    Util.exec(func);

                });
        };

        this.setOnPanel             = function(panelId) {
            var panel           = DOM.getById(panelId),
                filesElement    = DOM.getByDataName('js-files', panel),
                pathElement     = DOM.getByDataName('js-path', panel);

            /* ставим загрузку гифа на клик*/
            Events.addClick(pathElement, onPathElementClick);
            Events.add(filesElement, EventsFiles);
        };

        function onPathElementClick(event) {
            var link, href, url,
                element     = event.target,
                attr        = element.getAttribute('data-name');

            switch (attr) {
            case 'js-clear-storage':
                Storage.clear();
                break;

            case 'js-refresh':
                CloudCmd.refresh();
                event.preventDefault();
                break;

            case 'js-path-link':
                url         = CloudCmd.HOST;
                href        = element.href;
                link        = Util.rmStr(href, url);
                /*
                 * browser do not replace % -> %25%
                 * do it for him
                 */
                link        = Util.replaceStr(link, '%%', '%25%');
                link        = decodeURI(link);
                link        = Util.rmStrOnce(link, CloudFunc.FS) || '/';

                CloudCmd.loadDir({
                    path        : link,
                    isRefresh   : false
                });

                event.preventDefault();
            }
        }

        function mousemove() {
            DOM.Events.add('mousemove', function(event) {
                var position    = CloudCmd.MousePosition,
                    x           = event.clientX,
                    y           = event.clientY;

                position.x      = x;
                position.y      = y;
            });
        }

        function execIfNotUL(callback, event) {
            var element = event.target,
                tag     = element.tagName;

            if (tag !== 'UL')
                callback(event);
        }

        function onClick(event) {
            var ctrl    = event.ctrlKey;

            if (!ctrl)
                Events.preventDefault(event);

            changePanel(event.target);
        }

        function changePanel(element) {
            var panel   = Info.panel,
                files   = DOM.getByDataName('js-files', panel),
                ul      = getULElement(element);

            if (ul !== files)
                DOM.changePanel();
        }

        function onDblClick(event) {
            var current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current),
                path        = DOM.getCurrentPath(current);

            path    = CloudFunc.rmLastSlash(path);

            if (isDir) {
                CloudCmd.loadDir({
                    path: path
                });

                Events.preventDefault(event);
            }
        }

        function onTouch(event) {
            var isCurrent,
                current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current);

            if (isDir) {
                isCurrent   = DOM.isCurrentFile(current);

                if (isCurrent) {
                    CloudCmd.loadDir({
                        path: DOM.getCurrentPath(current)
                    });

                    Events.preventDefault(event);
                }
            }
        }

        function onContextMenu(event) {
            var element = event.target,
                tag     = element.tagName,
                isUL    = tag === 'UL';

            if (!isUL) {
                element     = getLIElement(event.target);
                DOM.setCurrentFile(element);
            }

            Util.exec(CloudCmd.Menu, {
                x: event.clientX,
                y: event.clientY
            });

            changePanel(element);
        }

         /*
          * download file from browser to desktop
          * in Chrome (HTML5)
          */
        function onDragStart(event) {
            var element     = getLIElement(event.target),
                EXT         = 'json',
                isDir       = Info.isDir,
                link        = DOM.getCurrentLink(element),
                name        = DOM.getCurrentName(element);

            /* if it's directory - adding json extension */
            if (isDir) {
                name       += '.' + EXT;
                link       += '?' + EXT;
            }

            event.dataTransfer.setData('DownloadURL',
                'application/octet-stream'  + ':' +
                name                        + ':' +
                link);
        }

        function getLIElement(element) {
            if (element)
                while (element.tagName !== 'LI')
                    element = element.parentElement;

            return element;
        }

        function getULElement(element) {
            while (element.tagName !== 'UL')
                element     = element.parentElement;

            return element;
        }

        function setCurrentFileByEvent(event) {
            var element = getLIElement(event.target);
            DOM.setCurrentFile(element);
        }

        function appStorage() {
            Files.get('config', function(error, config) {
                var isAppStorage  = config.appStorage,
                    appStorage    = window.applicationStorage;

                if (isAppStorage && appStorage)
                    Events.add('updateready', appStorage, function() {
                        var ret = confirm('An update is available. Reload now?');

                        if (ret)
                            location.reload();

                    });
                });
        }

        function contextMenu() {
            Events.addContextMenu(document, function(event) {
                CloudCmd.Menu.ENABLED || Events.preventDefault(event);
            });
        }

        function dragndrop() {
            var panels          = DOM.getByClassAll('panel'),
                preventDefault  = function (event) {
                    event.preventDefault();
                },
                toggle          = function () {
                    Util.forEach(panels, function(panel) {
                        DOM.toggleClass(panel, 'selected-panel');
                    });
                },
                onDrop          = function (event) {
                    var files   = event.dataTransfer.files;

                    preventDefault(event);
                    DOM.uploadFiles(files);
                };

            Events.add(['dragenter', 'dragleave', 'drop'], toggle);

            Util.forEach(panels, function(panel) {
                Events.add('dragover', panel, preventDefault)
                      .add('drop', panel, onDrop);
            });
        }

        function unload() {
            DOM.Events.add(['unload', 'beforeunload'], function (event) {
                var ret,
                    Key     = CloudCmd.Key,
                    isBind  = Key && Key.isBind();

                if (!isBind) {
                    Events.preventDefault(event);
                    ret = 'Please make sure that you saved all work.';
                }

                return ret;
            });
        }

        function pop() {
            Events.add('popstate', function(event) {
                var path    = event.state;

                path        = Util.rmStrOnce(path, CloudFunc.FS);

                if (path)
                    CloudCmd.loadDir({
                        path        : path,
                        history     : false
                    });
                else
                    CloudCmd.route(location.hash);
            });
        }

        function online() {
            var cssSet = DOM.load.style.bind(null, {
                    id      :'local-droids-font',
                    element : document.head,
                    inner   :   '@font-face {font-family: "Droid Sans Mono";'           +
                                'font-style: normal;font-weight: normal;'               +
                                'src: local("Droid Sans Mono"), local("DroidSansMono"),'+
                                ' url("/font/DroidSansMono.woff") format("woff");}'
                });

            if (navigator.onLine)
                Events.addOnce('offline', cssSet);
            else
                cssSet();
        }

     }

})(Util, DOM, CloudFunc, CloudCmd);
<|endoftext|>


<commit_before>/*!
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/* global $ */

import getMetaValue from './meta_value';

const isWrapped = getMetaValue('wrapped');

// pygments generates the HTML so set wrap toggle via js
if (isWrapped) {
  $('.code pre').toggleClass('wrap');
}
<commit_msg>Fix Toggle Wrap on DAG code page (#19211)<commit_after>/*!
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/* global window, $ */

import getMetaValue from './meta_value';

function toggleWrap() {
  $('.code pre').toggleClass('wrap');
}

const isWrapped = getMetaValue('wrapped');

// pygments generates the HTML so set wrap toggle via js
if (isWrapped === 'True') {
  toggleWrap();
}

window.toggleWrap = toggleWrap;
<|endoftext|>


<commit_before>angular.module('ngWig')
  .directive('ngWigEditable', function ($document) {
    function init(scope, $element, attrs, ngModelController) {

      $element.attr('contenteditable', true);

      //model --> view
      ngModelController.$render = function () {
        $element.html(ngModelController.$viewValue || '');
      };

      //view --> model
      function viewToModel() {
        ngModelController.$setViewValue($element.html());
      }

      if (angular.isFunction(scope.onPaste)) {
        $element.on('paste', function(e) {
          scope.onPaste(e, $element.html()).then(function(val) {
            $element.html(val);
          })
        });
      }

      $element.bind('blur keyup change focus click', function() {
        viewToModel();
        scope.$applyAsync();
      });

      scope.isEditorActive = function () {
        return $element[0] === $document[0].activeElement;
      };

      scope.$on('execCommand', function (event, params) {
        $element[0].focus();

        var ieStyleTextSelection = $document[0].selection,
          command = params.command,
          options = params.options;

        if (ieStyleTextSelection) {
          var textRange = ieStyleTextSelection.createRange();
        }

        if ($document[0].queryCommandSupported && !$document[0].queryCommandSupported(command)) {
          throw 'The command "' + command + '" is not supported';
        }

        $document[0].execCommand(command, false, options);

        if (ieStyleTextSelection) {
          textRange.collapse(false);
          textRange.select();
        }

        viewToModel();
      });
    }

    return {
      restrict: 'A',
      require: 'ngModel',
      replace: true,
      link: init
    }
  }
);
<commit_msg>bind on paste event when no callback is given<commit_after>angular.module('ngWig')
  .directive('ngWigEditable', function ($document) {
    function init(scope, $element, attrs, ngModelController) {

      $element.attr('contenteditable', true);

      //model --> view
      ngModelController.$render = function () {
        $element.html(ngModelController.$viewValue || '');
      };

      //view --> model
      function viewToModel() {
        ngModelController.$setViewValue($element.html());
      }

      var eventsToBind = [
        'blur',
        'keyup',
        'change',
        'focus',
        'click'
      ];

      if (angular.isFunction(scope.onPaste)) {
        $element.on('paste', function(e) {
          scope.onPaste(e, $element.html()).then(function(val) {
            $element.html(val);
          })
        });
      }else{
        eventsToBind.push('paste');
      }

      $element.bind(eventsToBind.join(' '), function() {
        viewToModel();
        scope.$applyAsync();
      });

      scope.isEditorActive = function () {
        return $element[0] === $document[0].activeElement;
      };

      scope.$on('execCommand', function (event, params) {
        $element[0].focus();

        var ieStyleTextSelection = $document[0].selection,
          command = params.command,
          options = params.options;

        if (ieStyleTextSelection) {
          var textRange = ieStyleTextSelection.createRange();
        }

        if ($document[0].queryCommandSupported && !$document[0].queryCommandSupported(command)) {
          throw 'The command "' + command + '" is not supported';
        }

        $document[0].execCommand(command, false, options);

        if (ieStyleTextSelection) {
          textRange.collapse(false);
          textRange.select();
        }

        viewToModel();
      });
    }

    return {
      restrict: 'A',
      require: 'ngModel',
      replace: true,
      link: init
    }
  }
);
<|endoftext|>


<commit_before>;(function(){
	var threadManager = {
		seed: 0,
		current: 0,
		threads: [],
		start: function() {
			if (this.current) {
				return;
			}
			(function(){
				for (var i = 0; i < threadManager.threads.length; i++ ) {
					if (threadManager.threads[i].run() === false ) {
						threadManager.threads[i].stop(true);
						threadManager.threads.splice(i,1);
						i--;
					}
				}
				threadManager.current = setTimeout(arguments.callee, 0);
			})();
		},
		stop: function() {
			clearTimeout(this.current);
			this.current = 0;
		},
		add: function(thread) {
			thread.__threadID = this.seed++;
			this.threads.push(thread);
			this.start();
			return thread.__threadID;
		},
		remove: function(threadID) {
			for (var i = 0; i < threadManager.threads.length; i++) {
				if (threadManager.threads[i].__threadID == threadID) {
					threadManager.threads.splice(i,1);
				}
			}
		}
	};

	this.SimpleThread = function(workFn,params) {
		var that = this;
		var autoStart = !!(params && params.autoStart);
		var workArgs = (params && params.workArgs) || [];
		var _log = (params && params.log !== null) || false;
		var workFn = workFn;
		var threadID = null;
		var _callee = arguments.callee;

		var log = function(msg) {
			if (_log && window.console) {
				console.log("SimpleThread #" + threadID + ": " + msg);
			}
		}

		// Control functions
		this.start = function() {
			if (!this.isRunning()) {
				threadID = threadManager.add(that);
				log("started");
			}
		};
		this.stop = function(skipThreadManager) {
			if (!skipThreadManager) {
				threadManager.remove(threadID);
			}
			if (that.isRunning()) {
				log("stopped");
				threadID = null;
			}
		};
		this.isRunning = function() {
			return threadID !== null;
		};
		this.run = function() {
			return workFn.apply(_callee,workArgs);
		};

		// Getters/Setters
		this.getBatchSize	= function()	{ return batchSize; };
		this.setBatchSize	= function(n)	{ batchSize = n; };
		this.getWorkFn		= function() 	{ return workFn; };
		this.setWorkFn		= function(fn)	{ workFn = fn; };
		this.getWorkArgs	= function()	{ return workArgs; };
		this.setWorkArgs	= function(args){ workArgs = args; };
		this.getThreadID	= function()	{ return threadID; };

		if (autoStart) {
			this.start();
		}
	};
})();

<commit_msg>fixed stupid default log code for simplethreading<commit_after>;(function(){
	var threadManager = {
		seed: 0,
		current: 0,
		threads: [],
		start: function() {
			if (this.current) {
				return;
			}
			(function(){
				for (var i = 0; i < threadManager.threads.length; i++ ) {
					if (threadManager.threads[i].run() === false ) {
						threadManager.threads[i].stop(true);
						threadManager.threads.splice(i,1);
						i--;
					}
				}
				threadManager.current = setTimeout(arguments.callee, 0);
			})();
		},
		stop: function() {
			clearTimeout(this.current);
			this.current = 0;
		},
		add: function(thread) {
			thread.__threadID = this.seed++;
			this.threads.push(thread);
			this.start();
			return thread.__threadID;
		},
		remove: function(threadID) {
			for (var i = 0; i < threadManager.threads.length; i++) {
				if (threadManager.threads[i].__threadID == threadID) {
					threadManager.threads.splice(i,1);
				}
			}
		}
	};

	this.SimpleThread = function(workFn,params) {
		var that = this;
		var autoStart = !!(params && params.autoStart);
		var workArgs = (params && params.workArgs) || [];
		var _log = (params && params.log !== undefined) || false;
		var workFn = workFn;
		var threadID = null;
		var _callee = arguments.callee;

		var log = function(msg) {
			if (_log && window.console) {
				console.log("SimpleThread #" + threadID + ": " + msg);
			}
		}

		// Control functions
		this.start = function() {
			if (!this.isRunning()) {
				threadID = threadManager.add(that);
				log("started");
			}
		};
		this.stop = function(skipThreadManager) {
			if (!skipThreadManager) {
				threadManager.remove(threadID);
			}
			if (that.isRunning()) {
				log("stopped");
				threadID = null;
			}
		};
		this.isRunning = function() {
			return threadID !== null;
		};
		this.run = function() {
			return workFn.apply(_callee,workArgs);
		};

		// Getters/Setters
		this.getBatchSize	= function()	{ return batchSize; };
		this.setBatchSize	= function(n)	{ batchSize = n; };
		this.getWorkFn		= function() 	{ return workFn; };
		this.setWorkFn		= function(fn)	{ workFn = fn; };
		this.getWorkArgs	= function()	{ return workArgs; };
		this.setWorkArgs	= function(args){ workArgs = args; };
		this.getThreadID	= function()	{ return threadID; };

		if (autoStart) {
			this.start();
		}
	};
})();

<|endoftext|>


<commit_before>/**********************************************************************
 CasperJS tests for Freeciv-web.
***********************************************************************/

casper.options.waitTimeout = 20000;
casper.options.viewportSize = {width: 1024, height: 768};

casper.on('remote.message', function(message) {
    this.echo('JavaScript console: ' + message);
});

casper.test.begin('Test of Tomcat8 running on localhost port 8080.', 2, function suite(test) {
    casper.start("http://localhost:8080/", function() {
        test.assertHttpStatus(200);
        test.assertTitleMatch(/Freeciv-web/, 'Freeciv-web title is present');
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test of Freeciv-proxy on port 7001.', 2, function suite(test) {
    casper.start("http://localhost:7001/status", function() {
        test.assertHttpStatus(200);
        test.assertTextExists('Freeciv WebSocket Proxy Status',
                              'Test that Freeciv-proxy contains expected text.');
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test of Freeciv-web frontpage on localhost port 80 (nginx).', 3, function suite(test) {
    casper.start("http://localhost", function() {});

    casper.waitForText("Freeciv-web", function() {
       test.assertHttpStatus(200);
       test.assertTitleMatch(/Freeciv-web/, 'Freeciv-web title is present');
       test.assertExists('#single-button');
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test that game list is responding.', 4, function suite(test) {
    casper.start("http://localhost/game/list", function() {
        test.assertHttpStatus(200);
        test.assertExists('#single-player-tab', 'Test that game-list contains expected tabs.');
        test.assertExists('#multi-player-tab', 'Test that game-list contains expected tabs.');
        test.assertExists('#play-by-email-tab', 'Test that game-list contains expected tabs.');
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test of Freeciv-web frontpage', 3, function suite(test) {
    casper.start("http://localhost", function() {
      casper.wait(5000, function() {
        test.assertHttpStatus(200);
        test.assertTitleMatch(/Freeciv-web/, 'Freeciv-web title is present');
        test.assertExists('#single-button');
      });
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test starting new Freeciv-web game', 10, function suite(test) {
    casper.start("http://localhost/webclient/?action=new", function() {
        test.assertHttpStatus(200);
        test.assertTitleMatch(/Freeciv-web/, 'Freeciv-web title is present');
    });

    casper.waitForSelector('#username_req', function() {
        this.echo("Captured screenshot to be saved as screenshot-1.png");
        this.capture('screenshot-1.png', undefined, {
          format: 'png',
          quality: 100
        });

    });

    casper.then(function() {
      this.echo("Filling in username in new game dialog.");
      this.sendKeys('#username_req', 'CasperJS', {reset : true});
    });

    casper.thenEvaluate(function() {
      /* Starting new game automatically from Javascript.*/
      dialog_close_trigger = "button";
      if (validate_username()) {
        $("#dialog").dialog('close');
        setTimeout("pregame_start_game();", 3000);
      }
    });

    casper.waitForText("World map", function() {
      this.echo("Captured screenshot to be saved as screenshot-2.png");
      this.capture('screenshot-2.png', undefined, {
        format: 'png',
        quality: 100
      });
     });

    casper.then(function() {
      this.echo("Checking that JavaScript objects in browser memory are as expected.");

      test.assertEval(function() {
            return tileset['u.settlers'].length == 5 && tileset['f.shield.england'].length == 5;
      }, "Checks that tileset contains settlers and english flag.");

      test.assertEval(function() {
            return map['xsize'] > 0
            && map['ysize'] > 0
            && tiles[5]['x'] >= 0
            && tiles[5]['y'] >= 0
            && tiles[5]['terrain'] != null;
      }, "Checks properties of map and tiles.");

      test.assertEval(function() {
            return techs[1] != null
            && techs[1]['name'] != null
            && techs[1]['name'].length > 0
            && techs[1]['num_reqs'] > 0
            && techs[1]['req'].length == 2
            && techs[1]['req'][0] > 0
            && techs[1]['req'][1] > 0;
      }, "Checks some properties of the tech object.");

      test.assertEval(function() {
            return players[0] != null && players[0]['name'].length > 0
            && players[0]['username'].length > 0
            && players[0]['playerno'] >= 0
            && nations[players[0]['nation']]
            && players[0]['love'].length > 0
            && players[0]['is_ready'] == true
      }, "Checks some properties of the player object.");

      test.assertEval(function() {
            return game_info['turn'] == 1
            && game_info['year'] == -4000
            && game_info['timeout'] == 0
            && game_info['gold'] > 0
            && game_info['aifill'] > 0;
      }, "Checks some properties of the game_info object.");

      test.assertEval(function() {
            return server_settings['size']['val'] > 0;
      }, "Checking some server settings.");

      test.assertEval(function() {
            return unit_types[0]['name'].length > 0
                   && unit_types[0]['helptext'].length > 0
                   && unit_types[0]['graphic_str'].length > 0
      }, "Checks some properties of the unit_types object.");

      test.assertEval(function() {
            return nations[0]['adjective'].length > 0
            && nations[0]['graphic_str'].length > 0;
      }, "Checks some properties of the nations object.");

    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test webperimental', 1, function suite(test) {
  casper.start("http://localhost/webclient/?action=new");

  casper.waitForSelector('#username_req', function() {
    this.echo("Filling in username in new game dialog.");
    this.sendKeys('#username_req', 'CasperJS');

    this.echo("Selecting to customize game in new game dialog.");
    this.clickLabel("Customize Game");
  });

  casper.waitForSelector('#pregame_settings_button', function() {
    this.echo("Opening pre game settings dialog.");
    this.click('#pregame_settings_button');
  });

  casper.waitForSelector('#ruleset', function() {
    this.echo("Loading webperimental.");
  });

  casper.thenEvaluate(function() {
    /* Change to webperimental. */
    $('#ruleset').val('webperimental').change();
  });

  casper.waitFor(
        function() {
          return this.evaluate(function() {
            return "Webperimental" == ruleset_control['name'];
          });
        },
        function() {
          test.pass("Loaded webperimental.");
        });

  casper.run(function() {
    test.done();
  });
});

casper.test.begin('Test auto generated manual text extraction.',
                  1, function suite(test) {
  casper.start("http://localhost/man/classic7.html", function() {
    test.assertHttpStatus(200);
  });

  casper.run(function() {
    test.done();
  });
});
<commit_msg>Test the full pregame settings ruleset switcher.<commit_after>/**********************************************************************
 CasperJS tests for Freeciv-web.
***********************************************************************/

casper.options.waitTimeout = 20000;
casper.options.viewportSize = {width: 1024, height: 768};

casper.on('remote.message', function(message) {
    this.echo('JavaScript console: ' + message);
});

casper.test.begin('Test of Tomcat8 running on localhost port 8080.', 2, function suite(test) {
    casper.start("http://localhost:8080/", function() {
        test.assertHttpStatus(200);
        test.assertTitleMatch(/Freeciv-web/, 'Freeciv-web title is present');
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test of Freeciv-proxy on port 7001.', 2, function suite(test) {
    casper.start("http://localhost:7001/status", function() {
        test.assertHttpStatus(200);
        test.assertTextExists('Freeciv WebSocket Proxy Status',
                              'Test that Freeciv-proxy contains expected text.');
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test of Freeciv-web frontpage on localhost port 80 (nginx).', 3, function suite(test) {
    casper.start("http://localhost", function() {});

    casper.waitForText("Freeciv-web", function() {
       test.assertHttpStatus(200);
       test.assertTitleMatch(/Freeciv-web/, 'Freeciv-web title is present');
       test.assertExists('#single-button');
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test that game list is responding.', 4, function suite(test) {
    casper.start("http://localhost/game/list", function() {
        test.assertHttpStatus(200);
        test.assertExists('#single-player-tab', 'Test that game-list contains expected tabs.');
        test.assertExists('#multi-player-tab', 'Test that game-list contains expected tabs.');
        test.assertExists('#play-by-email-tab', 'Test that game-list contains expected tabs.');
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test of Freeciv-web frontpage', 3, function suite(test) {
    casper.start("http://localhost", function() {
      casper.wait(5000, function() {
        test.assertHttpStatus(200);
        test.assertTitleMatch(/Freeciv-web/, 'Freeciv-web title is present');
        test.assertExists('#single-button');
      });
    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test starting new Freeciv-web game', 10, function suite(test) {
    casper.start("http://localhost/webclient/?action=new", function() {
        test.assertHttpStatus(200);
        test.assertTitleMatch(/Freeciv-web/, 'Freeciv-web title is present');
    });

    casper.waitForSelector('#username_req', function() {
        this.echo("Captured screenshot to be saved as screenshot-1.png");
        this.capture('screenshot-1.png', undefined, {
          format: 'png',
          quality: 100
        });

    });

    casper.then(function() {
      this.echo("Filling in username in new game dialog.");
      this.sendKeys('#username_req', 'CasperJS', {reset : true});
    });

    casper.thenEvaluate(function() {
      /* Starting new game automatically from Javascript.*/
      dialog_close_trigger = "button";
      if (validate_username()) {
        $("#dialog").dialog('close');
        setTimeout("pregame_start_game();", 3000);
      }
    });

    casper.waitForText("World map", function() {
      this.echo("Captured screenshot to be saved as screenshot-2.png");
      this.capture('screenshot-2.png', undefined, {
        format: 'png',
        quality: 100
      });
     });

    casper.then(function() {
      this.echo("Checking that JavaScript objects in browser memory are as expected.");

      test.assertEval(function() {
            return tileset['u.settlers'].length == 5 && tileset['f.shield.england'].length == 5;
      }, "Checks that tileset contains settlers and english flag.");

      test.assertEval(function() {
            return map['xsize'] > 0
            && map['ysize'] > 0
            && tiles[5]['x'] >= 0
            && tiles[5]['y'] >= 0
            && tiles[5]['terrain'] != null;
      }, "Checks properties of map and tiles.");

      test.assertEval(function() {
            return techs[1] != null
            && techs[1]['name'] != null
            && techs[1]['name'].length > 0
            && techs[1]['num_reqs'] > 0
            && techs[1]['req'].length == 2
            && techs[1]['req'][0] > 0
            && techs[1]['req'][1] > 0;
      }, "Checks some properties of the tech object.");

      test.assertEval(function() {
            return players[0] != null && players[0]['name'].length > 0
            && players[0]['username'].length > 0
            && players[0]['playerno'] >= 0
            && nations[players[0]['nation']]
            && players[0]['love'].length > 0
            && players[0]['is_ready'] == true
      }, "Checks some properties of the player object.");

      test.assertEval(function() {
            return game_info['turn'] == 1
            && game_info['year'] == -4000
            && game_info['timeout'] == 0
            && game_info['gold'] > 0
            && game_info['aifill'] > 0;
      }, "Checks some properties of the game_info object.");

      test.assertEval(function() {
            return server_settings['size']['val'] > 0;
      }, "Checking some server settings.");

      test.assertEval(function() {
            return unit_types[0]['name'].length > 0
                   && unit_types[0]['helptext'].length > 0
                   && unit_types[0]['graphic_str'].length > 0
      }, "Checks some properties of the unit_types object.");

      test.assertEval(function() {
            return nations[0]['adjective'].length > 0
            && nations[0]['graphic_str'].length > 0;
      }, "Checks some properties of the nations object.");

    });

    casper.run(function() {
        test.done();
    });
});

casper.test.begin('Test pregame settings dialog ruleset switcher',
                  3, function suite(test) {
  casper.start("http://localhost/webclient/?action=new");

  casper.waitForSelector('#username_req', function() {
    this.echo("Filling in username in new game dialog.");
    this.sendKeys('#username_req', 'CasperJS');

    this.echo("Selecting to customize game in new game dialog.");
    this.clickLabel("Customize Game");
  });

  casper.waitForSelector('#pregame_settings_button', function() {
    this.echo("Opening pre game settings dialog.");
    this.click('#pregame_settings_button');
  });

  casper.waitForSelector('#ruleset', function() {
    this.echo("Loading webperimental.");
  });

  casper.thenEvaluate(function() {
    /* Change to webperimental. */
    $('#ruleset').val('webperimental').change();
  });

  casper.waitFor(
        function() {
          return this.evaluate(function() {
            return "Webperimental" == ruleset_control['name'];
          });
        },
        function() {
          test.pass("Loaded webperimental.");
        });

  casper.wait(1000, function() {
    this.echo("Loading civ2civ3.");
  });

  casper.thenEvaluate(function() {
    /* Change to civ2civ3. */
    $('#ruleset').val('civ2civ3').change();
  });

  casper.waitFor(
        function() {
          return this.evaluate(function() {
            return "Civ2Civ3 ruleset" == ruleset_control['name'];
          });
        },
        function() {
          test.pass("Loaded civ2civ3.");
        });

  casper.wait(1000, function() {
    this.echo("Loading classic.");
  });

  casper.thenEvaluate(function() {
    /* Change to classic. */
    $('#ruleset').val('classic').change();
  });

  casper.waitFor(
        function() {
          return this.evaluate(function() {
            return "Classic ruleset" == ruleset_control['name'];
          });
        },
        function() {
          test.pass("Loaded classic.");
        });

  casper.run(function() {
    test.done();
  });
});

casper.test.begin('Test auto generated manual text extraction.',
                  1, function suite(test) {
  casper.start("http://localhost/man/classic7.html", function() {
    test.assertHttpStatus(200);
  });

  casper.run(function() {
    test.done();
  });
});
<|endoftext|>


<commit_before>cuadro = {};

var socket = io();

if (screenfull) {
  screenfull.request();
}

// preload images that will be used as background
var queue = new createjs.LoadQueue(useXHR = false);
//The queue emits fileload event for
// files queued with loadFile
queue.on("fileload", function(event) {
  flipit(event.item.src);
}, this);

socket.on("photo", function(photo) {
  // queue the photo till it fires the fileload event
  queue.loadFile(photo.url_l);
})

function flipit(url) {
  $("html").css({
    "background": "url(" + url + ") no-repeat center center fixed",
    "-webkit-background-size": "cover",
    "-moz-background-size": "cover",
    "-o-background-size": "cover",
    "background-size": "cover"
  });

}<commit_msg>added fullscreen toggle on click<commit_after>cuadro = {};

var socket = io();

if (screenfull) {
  $("html").click(function() {
    screenfull.toggle();
  });
}

// preload images that will be used as background
var queue = new createjs.LoadQueue(useXHR = false);
//The queue emits fileload event for
// files queued with loadFile
queue.on("fileload", function(event) {
  flipit(event.item.src);
}, this);

socket.on("photo", function(photo) {
  // queue the photo till it fires the fileload event
  queue.loadFile(photo.url_l);
})

function flipit(url) {
  $("html").css({
    "background": "url(" + url + ") no-repeat center center fixed",
    "-webkit-background-size": "cover",
    "-moz-background-size": "cover",
    "-o-background-size": "cover",
    "background-size": "cover"
  });

}<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */
import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { View } from 'react-native';

import { ToggleBar, DataTablePageView, SearchBar, PageButton } from '../widgets';
import { DataTable, DataTableRow, DataTableHeaderRow } from '../widgets/DataTable';
import { PatientHistoryModal } from '../widgets/modals/PatientHistory';
import { FormControl } from '../widgets/FormControl';
import { ModalContainer } from '../widgets/modals/ModalContainer';

import { recordKeyExtractor, getItemLayout } from './dataTableUtilities';
import { createPrescription } from '../navigation/actions';

import { UIDatabase } from '../database';
import { getFormInputConfig } from '../utilities/formInputConfigs';

import { PatientActions } from '../actions/PatientActions';
import { PrescriberActions } from '../actions/PrescriberActions';
import { InsuranceActions } from '../actions/InsuranceActions';
import { DispensaryActions } from '../actions/DispensaryActions';

import { selectDataSetInUse, selectSortedData } from '../selectors/dispensary';
import { selectPrescriberModalOpen } from '../selectors/prescriber';
import { selectInsuranceModalOpen } from '../selectors/insurance';
import { selectPatientModalOpen } from '../selectors/patient';

import globalStyles from '../globalStyles';
import { dispensingStrings } from '../localization';

const Dispensing = ({
  data,
  columns,
  isAscending,
  sortKey,
  searchTerm,
  usingPatientsDataSet,
  usingPrescribersDataSet,
  // Misc. Callbacks
  filter,
  sort,
  gotoPrescription,
  switchDataset,

  // Patient variable
  patientEditModalOpen,
  currentPatient,
  patientHistoryModalOpen,
  // Patient callback
  editPatient,
  createPatient,
  cancelPatientEdit,
  savePatient,
  viewPatientHistory,

  // Prescriber variables
  currentPrescriber,
  prescriberModalOpen,
  // Prescriber callbacks
  editPrescriber,
  createPrescriber,
  cancelPrescriberEdit,
  savePrescriber,

  // Insurance variables
  insuranceModalOpen,
  selectedInsurancePolicy,
  isCreatingInsurancePolicy,
  // Insurance callbacks
  cancelInsuranceEdit,
  saveInsurancePolicy,
}) => {
  const getCellCallbacks = colKey => {
    switch (colKey) {
      case 'dispense':
        return gotoPrescription;
      case 'patientHistory':
        return viewPatientHistory;
      case 'patientEdit':
        return editPatient;
      case 'prescriberEdit':
        return editPrescriber;
      default:
        return null;
    }
  };

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = recordKeyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowKey={rowKey}
          getCallback={getCellCallbacks}
          columns={columns}
          rowIndex={index}
        />
      );
    },
    [data]
  );

  const renderHeader = useCallback(
    () => (
      <DataTableHeaderRow
        columns={columns}
        isAscending={isAscending}
        sortKey={sortKey}
        onPress={sort}
      />
    ),
    [sortKey, isAscending, columns]
  );

  const toggles = useMemo(
    () => [
      {
        text: dispensingStrings.patients,
        onPress: switchDataset,
        isOn: usingPatientsDataSet,
      },
      {
        text: dispensingStrings.prescribers,
        onPress: switchDataset,
        isOn: usingPrescribersDataSet,
      },
    ],
    [usingPatientsDataSet, usingPrescribersDataSet, switchDataset]
  );

  const { pageTopSectionContainer } = globalStyles;
  return (
    <>
      <DataTablePageView>
        <View style={pageTopSectionContainer}>
          <ToggleBar toggles={toggles} />
          <SearchBar
            onChangeText={filter}
            value={searchTerm}
            viewStyle={localStyles.searchBar}
            placeholder={dispensingStrings.search_by_last_name_first_name}
          />
          <PageButton
            text={
              usingPatientsDataSet
                ? `${dispensingStrings.new} ${dispensingStrings.patient}`
                : `${dispensingStrings.new} ${dispensingStrings.prescriber}`
            }
            onPress={usingPatientsDataSet ? createPatient : createPrescriber}
          />
        </View>
        <DataTable
          data={data}
          renderRow={renderRow}
          renderHeader={renderHeader}
          keyExtractor={recordKeyExtractor}
          getItemLayout={getItemLayout}
        />
      </DataTablePageView>
      <ModalContainer
        title={`${dispensingStrings.patient_detail}`}
        noCancel
        fullScreen
        isVisible={patientEditModalOpen}
      >
        <FormControl
          onSave={savePatient}
          onCancel={cancelPatientEdit}
          inputConfig={getFormInputConfig('patient', currentPatient)}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.prescriber} ${dispensingStrings.details}`}
        noCancel
        fullScreen
        isVisible={prescriberModalOpen}
      >
        <FormControl
          onSave={savePrescriber}
          onCancel={cancelPrescriberEdit}
          inputConfig={getFormInputConfig('prescriber', currentPrescriber)}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.insurance_policy}`}
        noCancel
        fullScreen
        isVisible={insuranceModalOpen}
      >
        <FormControl
          onSave={saveInsurancePolicy}
          onCancel={cancelInsuranceEdit}
          inputConfig={getFormInputConfig(
            'insurancePolicy',
            isCreatingInsurancePolicy ? null : selectedInsurancePolicy
          )}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.patient} ${dispensingStrings.history} - ${currentPatient?.name}`}
        onClose={cancelPatientEdit}
        fullScreen
        isVisible={patientHistoryModalOpen}
      >
        <PatientHistoryModal />
      </ModalContainer>
    </>
  );
};

const localStyles = {
  searchBar: {
    borderBottomWidth: 1,
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 5,
    flex: 1,
    flexGrow: 1,
  },
};

const mapStateToProps = state => {
  const { patient, prescriber, insurance, dispensary } = state;
  const { sortKey, isAscending, searchTerm, columns } = dispensary;

  const { currentPatient } = patient;
  const { currentPrescriber } = prescriber;
  const { isCreatingInsurancePolicy, selectedInsurancePolicy } = insurance;

  const prescriberModalOpen = selectPrescriberModalOpen(state);
  const [patientEditModalOpen, patientHistoryModalOpen] = selectPatientModalOpen(state);
  const insuranceModalOpen = selectInsuranceModalOpen(state);
  const data = selectSortedData(state);

  const [usingPatientsDataSet, usingPrescribersDataSet] = selectDataSetInUse(state);

  return {
    usingPatientsDataSet,
    usingPrescribersDataSet,
    data,
    sortKey,
    isAscending,
    searchTerm,
    columns,
    // Patient
    patientEditModalOpen,
    currentPatient,
    patientHistoryModalOpen,
    // Prescriber
    currentPrescriber,
    prescriberModalOpen,
    // Insurance
    insuranceModalOpen,
    selectedInsurancePolicy,
    isCreatingInsurancePolicy,
  };
};

const mapDispatchToProps = dispatch => ({
  gotoPrescription: patientID => dispatch(createPrescription(patientID)),

  filter: searchTerm => dispatch(DispensaryActions.filter(searchTerm)),
  sort: sortKey => dispatch(DispensaryActions.sort(sortKey)),
  switchDataset: () => dispatch(DispensaryActions.switchDataSet()),

  editPatient: patient => dispatch(PatientActions.editPatient(UIDatabase.get('Name', patient))),
  createPatient: () => dispatch(PatientActions.createPatient()),
  cancelPatientEdit: () => dispatch(PatientActions.closeModal()),
  savePatient: patientDetails => dispatch(PatientActions.patientUpdate(patientDetails)),
  viewPatientHistory: rowKey =>
    dispatch(PatientActions.viewPatientHistory(UIDatabase.get('Name', rowKey))),

  editPrescriber: prescriber =>
    dispatch(PrescriberActions.editPrescriber(UIDatabase.get('Prescriber', prescriber))),
  createPrescriber: () => dispatch(PrescriberActions.createPrescriber()),
  cancelPrescriberEdit: () => dispatch(PrescriberActions.closeModal()),
  savePrescriber: prescriberDetails =>
    dispatch(PrescriberActions.updatePrescriber(prescriberDetails)),

  cancelInsuranceEdit: () => dispatch(InsuranceActions.cancel()),
  saveInsurancePolicy: policyDetails => dispatch(InsuranceActions.update(policyDetails)),
});

export const DispensingPage = connect(mapStateToProps, mapDispatchToProps)(Dispensing);

Dispensing.defaultProps = {
  currentPatient: null,
  currentPrescriber: null,
  selectedInsurancePolicy: null,
};

Dispensing.propTypes = {
  data: PropTypes.object.isRequired,
  columns: PropTypes.array.isRequired,
  isAscending: PropTypes.bool.isRequired,
  sortKey: PropTypes.string.isRequired,
  sort: PropTypes.func.isRequired,
  searchTerm: PropTypes.string.isRequired,
  filter: PropTypes.func.isRequired,
  switchDataset: PropTypes.func.isRequired,
  gotoPrescription: PropTypes.func.isRequired,
  editPatient: PropTypes.func.isRequired,
  patientEditModalOpen: PropTypes.bool.isRequired,
  createPatient: PropTypes.func.isRequired,
  savePatient: PropTypes.func.isRequired,
  cancelPatientEdit: PropTypes.func.isRequired,
  currentPatient: PropTypes.object,
  currentPrescriber: PropTypes.object,
  editPrescriber: PropTypes.func.isRequired,
  createPrescriber: PropTypes.func.isRequired,
  cancelPrescriberEdit: PropTypes.func.isRequired,
  savePrescriber: PropTypes.func.isRequired,
  prescriberModalOpen: PropTypes.bool.isRequired,
  usingPatientsDataSet: PropTypes.bool.isRequired,
  usingPrescribersDataSet: PropTypes.bool.isRequired,
  patientHistoryModalOpen: PropTypes.bool.isRequired,
  selectedInsurancePolicy: PropTypes.object,
  insuranceModalOpen: PropTypes.bool.isRequired,
  cancelInsuranceEdit: PropTypes.func.isRequired,
  isCreatingInsurancePolicy: PropTypes.bool.isRequired,
  saveInsurancePolicy: PropTypes.func.isRequired,
  viewPatientHistory: PropTypes.func.isRequired,
};
<commit_msg>Add use of translations<commit_after>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */
import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { View } from 'react-native';

import { ToggleBar, DataTablePageView, SearchBar, PageButton } from '../widgets';
import { DataTable, DataTableRow, DataTableHeaderRow } from '../widgets/DataTable';
import { PatientHistoryModal } from '../widgets/modals/PatientHistory';
import { FormControl } from '../widgets/FormControl';
import { ModalContainer } from '../widgets/modals/ModalContainer';

import { recordKeyExtractor, getItemLayout } from './dataTableUtilities';
import { createPrescription } from '../navigation/actions';

import { UIDatabase } from '../database';
import { getFormInputConfig } from '../utilities/formInputConfigs';

import { PatientActions } from '../actions/PatientActions';
import { PrescriberActions } from '../actions/PrescriberActions';
import { InsuranceActions } from '../actions/InsuranceActions';
import { DispensaryActions } from '../actions/DispensaryActions';

import { selectDataSetInUse, selectSortedData } from '../selectors/dispensary';
import { selectPrescriberModalOpen } from '../selectors/prescriber';
import { selectInsuranceModalOpen } from '../selectors/insurance';
import { selectPatientModalOpen } from '../selectors/patient';

import globalStyles from '../globalStyles';
import { dispensingStrings } from '../localization';

const Dispensing = ({
  data,
  columns,
  isAscending,
  sortKey,
  searchTerm,
  usingPatientsDataSet,
  usingPrescribersDataSet,
  // Misc. Callbacks
  filter,
  sort,
  gotoPrescription,
  switchDataset,

  // Patient variable
  patientEditModalOpen,
  currentPatient,
  patientHistoryModalOpen,
  // Patient callback
  editPatient,
  createPatient,
  cancelPatientEdit,
  savePatient,
  viewPatientHistory,

  // Prescriber variables
  currentPrescriber,
  prescriberModalOpen,
  // Prescriber callbacks
  editPrescriber,
  createPrescriber,
  cancelPrescriberEdit,
  savePrescriber,

  // Insurance variables
  insuranceModalOpen,
  selectedInsurancePolicy,
  isCreatingInsurancePolicy,
  // Insurance callbacks
  cancelInsuranceEdit,
  saveInsurancePolicy,
}) => {
  const getCellCallbacks = colKey => {
    switch (colKey) {
      case 'dispense':
        return gotoPrescription;
      case 'patientHistory':
        return viewPatientHistory;
      case 'patientEdit':
        return editPatient;
      case 'prescriberEdit':
        return editPrescriber;
      default:
        return null;
    }
  };

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = recordKeyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowKey={rowKey}
          getCallback={getCellCallbacks}
          columns={columns}
          rowIndex={index}
        />
      );
    },
    [data]
  );

  const renderHeader = useCallback(
    () => (
      <DataTableHeaderRow
        columns={columns}
        isAscending={isAscending}
        sortKey={sortKey}
        onPress={sort}
      />
    ),
    [sortKey, isAscending, columns]
  );

  const toggles = useMemo(
    () => [
      {
        text: dispensingStrings.patients,
        onPress: switchDataset,
        isOn: usingPatientsDataSet,
      },
      {
        text: dispensingStrings.prescribers,
        onPress: switchDataset,
        isOn: usingPrescribersDataSet,
      },
    ],
    [usingPatientsDataSet, usingPrescribersDataSet, switchDataset]
  );

  const { pageTopSectionContainer } = globalStyles;
  return (
    <>
      <DataTablePageView>
        <View style={pageTopSectionContainer}>
          <ToggleBar toggles={toggles} />
          <SearchBar
            onChangeText={filter}
            value={searchTerm}
            viewStyle={localStyles.searchBar}
            placeholder={dispensingStrings.search_by_last_name_first_name}
          />
          <PageButton
            text={
              usingPatientsDataSet
                ? `${dispensingStrings.new_patient}`
                : `${dispensingStrings.new} ${dispensingStrings.prescriber}`
            }
            onPress={usingPatientsDataSet ? createPatient : createPrescriber}
          />
        </View>
        <DataTable
          data={data}
          renderRow={renderRow}
          renderHeader={renderHeader}
          keyExtractor={recordKeyExtractor}
          getItemLayout={getItemLayout}
        />
      </DataTablePageView>
      <ModalContainer
        title={`${dispensingStrings.patient_detail}`}
        noCancel
        fullScreen
        isVisible={patientEditModalOpen}
      >
        <FormControl
          onSave={savePatient}
          onCancel={cancelPatientEdit}
          inputConfig={getFormInputConfig('patient', currentPatient)}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.prescriber} ${dispensingStrings.details}`}
        noCancel
        fullScreen
        isVisible={prescriberModalOpen}
      >
        <FormControl
          onSave={savePrescriber}
          onCancel={cancelPrescriberEdit}
          inputConfig={getFormInputConfig('prescriber', currentPrescriber)}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.insurance_policy}`}
        noCancel
        fullScreen
        isVisible={insuranceModalOpen}
      >
        <FormControl
          onSave={saveInsurancePolicy}
          onCancel={cancelInsuranceEdit}
          inputConfig={getFormInputConfig(
            'insurancePolicy',
            isCreatingInsurancePolicy ? null : selectedInsurancePolicy
          )}
        />
      </ModalContainer>
      <ModalContainer
        title={`${dispensingStrings.patient} ${dispensingStrings.history} - ${currentPatient?.name}`}
        onClose={cancelPatientEdit}
        fullScreen
        isVisible={patientHistoryModalOpen}
      >
        <PatientHistoryModal />
      </ModalContainer>
    </>
  );
};

const localStyles = {
  searchBar: {
    borderBottomWidth: 1,
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 5,
    flex: 1,
    flexGrow: 1,
  },
};

const mapStateToProps = state => {
  const { patient, prescriber, insurance, dispensary } = state;
  const { sortKey, isAscending, searchTerm, columns } = dispensary;

  const { currentPatient } = patient;
  const { currentPrescriber } = prescriber;
  const { isCreatingInsurancePolicy, selectedInsurancePolicy } = insurance;

  const prescriberModalOpen = selectPrescriberModalOpen(state);
  const [patientEditModalOpen, patientHistoryModalOpen] = selectPatientModalOpen(state);
  const insuranceModalOpen = selectInsuranceModalOpen(state);
  const data = selectSortedData(state);

  const [usingPatientsDataSet, usingPrescribersDataSet] = selectDataSetInUse(state);

  return {
    usingPatientsDataSet,
    usingPrescribersDataSet,
    data,
    sortKey,
    isAscending,
    searchTerm,
    columns,
    // Patient
    patientEditModalOpen,
    currentPatient,
    patientHistoryModalOpen,
    // Prescriber
    currentPrescriber,
    prescriberModalOpen,
    // Insurance
    insuranceModalOpen,
    selectedInsurancePolicy,
    isCreatingInsurancePolicy,
  };
};

const mapDispatchToProps = dispatch => ({
  gotoPrescription: patientID => dispatch(createPrescription(patientID)),

  filter: searchTerm => dispatch(DispensaryActions.filter(searchTerm)),
  sort: sortKey => dispatch(DispensaryActions.sort(sortKey)),
  switchDataset: () => dispatch(DispensaryActions.switchDataSet()),

  editPatient: patient => dispatch(PatientActions.editPatient(UIDatabase.get('Name', patient))),
  createPatient: () => dispatch(PatientActions.createPatient()),
  cancelPatientEdit: () => dispatch(PatientActions.closeModal()),
  savePatient: patientDetails => dispatch(PatientActions.patientUpdate(patientDetails)),
  viewPatientHistory: rowKey =>
    dispatch(PatientActions.viewPatientHistory(UIDatabase.get('Name', rowKey))),

  editPrescriber: prescriber =>
    dispatch(PrescriberActions.editPrescriber(UIDatabase.get('Prescriber', prescriber))),
  createPrescriber: () => dispatch(PrescriberActions.createPrescriber()),
  cancelPrescriberEdit: () => dispatch(PrescriberActions.closeModal()),
  savePrescriber: prescriberDetails =>
    dispatch(PrescriberActions.updatePrescriber(prescriberDetails)),

  cancelInsuranceEdit: () => dispatch(InsuranceActions.cancel()),
  saveInsurancePolicy: policyDetails => dispatch(InsuranceActions.update(policyDetails)),
});

export const DispensingPage = connect(mapStateToProps, mapDispatchToProps)(Dispensing);

Dispensing.defaultProps = {
  currentPatient: null,
  currentPrescriber: null,
  selectedInsurancePolicy: null,
};

Dispensing.propTypes = {
  data: PropTypes.object.isRequired,
  columns: PropTypes.array.isRequired,
  isAscending: PropTypes.bool.isRequired,
  sortKey: PropTypes.string.isRequired,
  sort: PropTypes.func.isRequired,
  searchTerm: PropTypes.string.isRequired,
  filter: PropTypes.func.isRequired,
  switchDataset: PropTypes.func.isRequired,
  gotoPrescription: PropTypes.func.isRequired,
  editPatient: PropTypes.func.isRequired,
  patientEditModalOpen: PropTypes.bool.isRequired,
  createPatient: PropTypes.func.isRequired,
  savePatient: PropTypes.func.isRequired,
  cancelPatientEdit: PropTypes.func.isRequired,
  currentPatient: PropTypes.object,
  currentPrescriber: PropTypes.object,
  editPrescriber: PropTypes.func.isRequired,
  createPrescriber: PropTypes.func.isRequired,
  cancelPrescriberEdit: PropTypes.func.isRequired,
  savePrescriber: PropTypes.func.isRequired,
  prescriberModalOpen: PropTypes.bool.isRequired,
  usingPatientsDataSet: PropTypes.bool.isRequired,
  usingPrescribersDataSet: PropTypes.bool.isRequired,
  patientHistoryModalOpen: PropTypes.bool.isRequired,
  selectedInsurancePolicy: PropTypes.object,
  insuranceModalOpen: PropTypes.bool.isRequired,
  cancelInsuranceEdit: PropTypes.func.isRequired,
  isCreatingInsurancePolicy: PropTypes.bool.isRequired,
  saveInsurancePolicy: PropTypes.func.isRequired,
  viewPatientHistory: PropTypes.func.isRequired,
};
<|endoftext|>


<commit_before>let { promisify } = require('util')
let writeFile = promisify(require('fs').writeFile)
let { join } = require('path')
let rimraf = promisify(require('rimraf'))

let { saveCache, getCache } = require('../cache')

const CACHE = join(__dirname, '..', '..', '.cache')

beforeAll(async () => {
  await rimraf(CACHE)
})

afterEach(async () => {
  await rimraf(CACHE)
})

it('returns false by default', async () => {
  expect(await getCache()).toBeFalsy()
})

it('writes cache', async () => {
  await saveCache(10)
  expect(await getCache()).toEqual(10)
})

it('checks version', async () => {
  await saveCache(10)
  let cache = join(__dirname, '..', '..', '.cache', 'size-limit', 'cache.json')
  await writeFile(cache, '{"version":0,"throttling":10}')
  expect(await getCache()).toBeFalsy()
})

it('works on broken JSON', async () => {
  await saveCache(10)
  let cache = join(__dirname, '..', '..', '.cache', 'size-limit', 'cache.json')
  await writeFile(cache, '{')
  expect(await getCache()).toBeFalsy()
})
<commit_msg>Clean code<commit_after>let { promisify } = require('util')
let writeFile = promisify(require('fs').writeFile)
let { join } = require('path')
let rimraf = promisify(require('rimraf'))

let { saveCache, getCache } = require('../cache')

const CACHE = join(__dirname, '..', '..', '.cache')

beforeAll(() => rimraf(CACHE))
afterEach(() => rimraf(CACHE))

it('returns false by default', async () => {
  expect(await getCache()).toBeFalsy()
})

it('writes cache', async () => {
  await saveCache(10)
  expect(await getCache()).toEqual(10)
})

it('checks version', async () => {
  await saveCache(10)
  let cache = join(__dirname, '..', '..', '.cache', 'size-limit', 'cache.json')
  await writeFile(cache, '{"version":0,"throttling":10}')
  expect(await getCache()).toBeFalsy()
})

it('works on broken JSON', async () => {
  await saveCache(10)
  let cache = join(__dirname, '..', '..', '.cache', 'size-limit', 'cache.json')
  await writeFile(cache, '{')
  expect(await getCache()).toBeFalsy()
})
<|endoftext|>


<commit_before>// Genders
// @note Can add `enum` property if `gender` is added to the schema.
reportList('legislators', '+gender', {
  '+gender': {
    '$exists': true,
    '$nin': ['Female', 'Male']
  }
});

// Office types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/person.json#L27
reportList('legislators', 'offices.type', {
  'offices': {
    '$ne': []
  },
  'offices.type': {
    '$nin': ['capitol', 'district']
  }
});

// Bill action types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/bill.json#L45
reportList('bills', 'actions.type', {
  'actions.type': {
    '$exists': true,
    '$nin': [
      'bill:introduced',
      'bill:passed',
      'bill:failed',
      'bill:withdrawn',
      'bill:substituted',
      'bill:filed',
      'bill:veto_override:passed',
      'bill:veto_override:failed',
      'governor:received',
      'governor:signed',
      'governor:vetoed',
      'governor:vetoed:line-item',
      'amendment:introduced',
      'amendment:passed',
      'amendment:failed',
      'amendment:tabled',
      'amendment:amended',
      'amendment:withdrawn',
      'committee:referred',
      'committee:failed',
      'committee:passed',
      'committee:passed:favorable',
      'committee:passed:unfavorable',
      'bill:reading:1',
      'bill:reading:2',
      'bill:reading:3',
      'other'
    ]
  }
});

// Bill action actors
reportList('bills', 'actions.actor', {
  'actions.actor': {
    '$exists': true,
    '$nin': [/^lower/, /^upper/, 'other', 'executive']
  }
}, 'bills with invalid actions.actor (e.g. "Senate" or "House")');

// Bill action related entity type
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/bill.json#L22
reportList('bills', 'actions.related_entities.type', {
  'actions.related_entities.type': {
    '$exists': true,
    '$nin': ['committee', 'legislator']
  }
});

// Bill sponsor types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/bill.json#L152
reportList('bills', 'sponsors.type', {
  'sponsors.type': {
    '$exists': true,
    '$nin': ['primary', 'cosponsor']
  }
});

// Bill MIME types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/bill.json#L190
['documents.mimetype', 'versions.mimetype'].forEach(function (field) {
  var criteria = {};
  criteria[field] = {
    '$exists': true,
    '$nin': [
      'text/html',
      'application/pdf',
      'application/msword',
      'application/rtf',
      'application/octet-stream',
      'application/vnd.wordperfect'
    ]
  };
  reportList('bills', field, criteria);
});

// Participant chamber
reportList('events', 'participants.chamber ', {
  'participants.chamber': {
    '$exists': true,
    '$nin': [
      'lower',
      'upper',
      'joint',
      'other'
    ]
  }
});

// Participant type
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/event.json#L64
reportList('events', 'participants.participant_type ', {
  'participants.participant_type': {
    '$exists': true,
    '$nin': [
      'committee',
      'legislator'
    ]
  }
});

// Participant role
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/event.json#L71
reportList('events', 'participants.type ', {
  'participants.type': {
    '$exists': true,
    '$nin': [
      'chair',
      'committee',
      'host'
    ]
  }
});

// Event types
reportList('events', 'type', {
  type: {
    '$nin': [
      'committee:hearing',
      'committee:meeting',
      'house:session',
      'joint:session',
      'senate:session',
      'floor_time',
      'other',
      'redistricting',
      'special'
    ]
  }
});

// Vote types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/vote.json#L11
reportList('votes', 'type', {
  type: {
    '$exists': true,
    '$nin': [
      'amendment',
      'other',
      'passage',
      'reading:1',
      'reading:2',
      'reading:3',
      'veto_override'
    ]
  }
});
<commit_msg>add code list checks for events<commit_after>var mimetypes = [
  'text/html',
  'application/pdf',
  'application/msword',
  'application/rtf',
  'application/octet-stream',
  'application/vnd.wordperfect'
]

// Genders
// @note Can add `enum` property if `gender` is added to the schema.
reportList('legislators', '+gender', {
  '+gender': {
    '$exists': true,
    '$nin': ['Female', 'Male']
  }
});

// Status
reportList('legislators', '+leg_status', {
  '+leg_status': {
    '$exists': true,
    '$nin': ['Active', 'Deceased', 'Resigned']
  }
});

// Office types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/person.json#L27
reportList('legislators', 'offices.type', {
  'offices': {
    '$ne': []
  },
  'offices.type': {
    '$nin': ['capitol', 'district']
  }
});

// Bill action types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/bill.json#L45
reportList('bills', 'actions.type', {
  'actions.type': {
    '$exists': true,
    '$nin': [
      'bill:introduced',
      'bill:passed',
      'bill:failed',
      'bill:withdrawn',
      'bill:substituted',
      'bill:filed',
      'bill:veto_override:passed',
      'bill:veto_override:failed',
      'governor:received',
      'governor:signed',
      'governor:vetoed',
      'governor:vetoed:line-item',
      'amendment:introduced',
      'amendment:passed',
      'amendment:failed',
      'amendment:tabled',
      'amendment:amended',
      'amendment:withdrawn',
      'committee:referred',
      'committee:failed',
      'committee:passed',
      'committee:passed:favorable',
      'committee:passed:unfavorable',
      'bill:reading:1',
      'bill:reading:2',
      'bill:reading:3',
      'other'
    ]
  }
});

// Bill action actors
reportList('bills', 'actions.actor', {
  'actions.actor': {
    '$exists': true,
    '$nin': [/^lower/, /^upper/, 'other', 'executive']
  }
}, 'bills with invalid actions.actor (e.g. "Senate" or "House")');

// Bill action related entity type
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/bill.json#L22
reportList('bills', 'actions.related_entities.type', {
  'actions.related_entities.type': {
    '$exists': true,
    '$nin': ['committee', 'legislator']
  }
});

// Bill sponsor types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/bill.json#L152
reportList('bills', 'sponsors.type', {
  'sponsors.type': {
    '$exists': true,
    '$nin': ['primary', 'cosponsor']
  }
});

// Bill MIME types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/bill.json#L190
['documents.mimetype', 'versions.mimetype'].forEach(function (field) {
  var criteria = {};
  criteria[field] = {
    '$exists': true,
    '$nin': mimetypes
  };
  reportList('bills', field, criteria);
});

// Document MIME type
reportList('events', 'documents.+mimetype', {
  'documents.+mimetype': {
    '$exists': true,
    '$nin': mimetypes
  }
});

reportList('events', 'documents.+type', {
  'documents.+type': {
    '$exists': true,
    '$nin': [
      'agenda',
      'full-text',
      'other'
    ]
  }
});

// Participant chamber
reportList('events', 'participants.chamber ', {
  'participants.chamber': {
    '$exists': true,
    '$nin': [
      'lower',
      'upper',
      'joint',
      'other'
    ]
  }
});

// Participant type
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/event.json#L64
reportList('events', 'participants.participant_type ', {
  'participants.participant_type': {
    '$exists': true,
    '$nin': [
      'committee',
      'legislator'
    ]
  }
});

// Participant role
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/event.json#L71
reportList('events', 'participants.type ', {
  'participants.type': {
    '$exists': true,
    '$nin': [
      'chair',
      'committee',
      'host'
    ]
  }
});

// Event types
reportList('events', 'type', {
  type: {
    '$nin': [
      'committee:hearing',
      'committee:meeting',
      'house:session',
      'joint:session',
      'senate:session',
      'floor_time',
      'other',
      'redistricting',
      'special'
    ]
  }
});

// Vote types
// @see https://github.com/sunlightlabs/billy/blob/master/billy/schemas/vote.json#L11
reportList('votes', 'type', {
  type: {
    '$exists': true,
    '$nin': [
      'amendment',
      'other',
      'passage',
      'reading:1',
      'reading:2',
      'reading:3',
      'veto_override'
    ]
  }
});
<|endoftext|>


<commit_before>// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from 'utils/asyncInjectors';
import postsData from 'store/posts/sagas'
import tagsData from 'store/tags/sagas'

const errorLoading = (err) => {
  console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};

const loadModule = (cb) => (componentModule) => {
  cb(null, componentModule.default);
};

export default function createRoutes(store) {
  // Create reusable async injectors using getAsyncInjectors factory
  const { injectReducer, injectSagas } = getAsyncInjectors(store); // eslint-disable-line no-unused-vars
  injectSagas(postsData);
  injectSagas(tagsData)
  return [
    {
      path: '/',
      name: 'home',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/HomePage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([component]) => {
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/blog/:slug',
      name: 'singlePost',
      getComponent(location, cb) {
        import('containers/SinglePost')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/tag/:slug',
      name: 'postsByTag',
      getComponent(location, cb) {
        import('containers/PostsByTag')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/search',
      name: 'search',
      getComponent(location, cb) {
        import('containers/Search')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/contact',
      name: 'contact',
      getComponent(location, cb) {
        import('containers/Contact')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '*',
      name: 'notfound',
      getComponent(nextState, cb) {
        import('containers/NotFoundPage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    },
  ];
}
<commit_msg>Stop RBPs code splitting by route. Unnecessary for something simple like this.<commit_after>// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from 'utils/asyncInjectors';
import postsData from 'store/posts/sagas'
import tagsData from 'store/tags/sagas'

import HomePage from 'containers/HomePage'
import SinglePost from 'containers/SinglePost'
import PostsByTag from 'containers/PostsByTag'
import Search from 'containers/Search'
import Contact from 'containers/Contact'
import NotFoundPage from 'containers/NotFoundPage'

const errorLoading = (err) => {
  console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};

const loadModule = (cb) => (componentModule) => {
  cb(null, componentModule.default);
};

export default function createRoutes(store) {
  // Create reusable async injectors using getAsyncInjectors factory
  const { injectReducer, injectSagas } = getAsyncInjectors(store); // eslint-disable-line no-unused-vars
  injectSagas(postsData);
  injectSagas(tagsData)
  return [
    {
      path: '/',
      name: 'home',
      component: HomePage,
    }, {
      path: '/blog/:slug',
      name: 'singlePost',
      component: SinglePost,
    }, {
      path: '/tag/:slug',
      name: 'postsByTag',
      component: PostsByTag,
    }, {
      path: '/search',
      name: 'search',
      component: Search,
    }, {
      path: '/contact',
      name: 'contact',
      component: Contact,
    }, {
      path: '*',
      name: 'notfound',
      component: NotFoundPage,
    },
  ];
}
<|endoftext|>