<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

///////////////////////////////////////////////////////////////////////////////
// OptionsPage class:

/**
 * Base class for options page.
 * @constructor
 * @param {string} name Options page name, also defines id of the div element
 *     containing the options view and the name of options page navigation bar
 *     item as name+'PageNav'.
 * @param {string} title Options page title, used for navigation bar
 * @extends {EventTarget}
 */
function OptionsPage(name, title, pageDivName) {
  this.name = name;
  this.title = title;
  this.pageDivName = pageDivName;
  this.pageDiv = $(this.pageDivName);
  this.tab = null;
}

OptionsPage.registeredPages_ = {};

/**
 * Pages which are meant to have an entry in the nav, but
 * not have a permanent entry.
 */
OptionsPage.registeredSubPages_ = {};

/**
 * Pages which are meant to behave like model dialogs.
 */
OptionsPage.registeredOverlayPages_ = {};

/**
 * Shows a registered page.
 * @param {string} pageName Page name.
 */
OptionsPage.showPageByName = function(pageName) {
  for (var name in OptionsPage.registeredPages_) {
    var page = OptionsPage.registeredPages_[name];
    page.visible = name == pageName;
  }
};

/**
 * Shows a registered Overlay page.
 * @param {string} overlayName Page name.
 */
OptionsPage.showOverlay = function(overlayName) {
  if (OptionsPage.registeredOverlayPages_[overlayName]) {
    OptionsPage.registeredOverlayPages_[overlayName].visible = true;
  }
};

OptionsPage.clearOverlays = function() {
   for (var name in OptionsPage.registeredOverlayPages_) {
     var page = OptionsPage.registeredOverlayPages_[name];
     page.visible = false;
   }
};

/**
 * Registers new options page.
 * @param {OptionsPage} page Page to register.
 */
OptionsPage.register = function(page) {
  OptionsPage.registeredPages_[page.name] = page;
  // Create and add new page <li> element to navbar.
  var pageNav = document.createElement('li');
  pageNav.id = page.name + 'PageNav';
  pageNav.className = 'navbar-item';
  pageNav.setAttribute('pageName', page.name);
  pageNav.textContent = page.title;
  pageNav.onclick = function(event) {
    OptionsPage.showPageByName(this.getAttribute('pageName'));
  };
  var navbar = $('navbar');
  navbar.appendChild(pageNav);
  page.tab = pageNav;
  page.initializePage();
};

/**
 * Registers a new Sub tab page.
 * @param {OptionsPage} page Page to register.
 */
OptionsPage.registerSubPage = function(page) {
  OptionsPage.registeredPages_[page.name] = page;
  var pageNav = document.createElement('li');
  pageNav.id = page.name + 'PageNav';
  pageNav.className = 'navbar-item hidden';
  pageNav.setAttribute('pageName', page.name);
  pageNav.textContent = page.title;
  var subpagesnav = $('subpagesnav');
  subpagesnav.appendChild(pageNav);
  page.tab = pageNav;
  page.initializePage();
};

/**
 * Registers a new Overlay page.
 * @param {OptionsPage} page Page to register, must be a class derviced from
 * OptionsPage.
 */
OptionsPage.registerOverlay = function(page) {
  OptionsPage.registeredOverlayPages_[page.name] = page;
  page.tab = undefined;
  page.isOverlay = true;
  page.initializePage();
};

/**
 * Initializes the complete options page.  This will cause
 * all C++ handlers to be invoked to do final setup.
 */
OptionsPage.initialize = function() {
  chrome.send('coreOptionsInitialize');
};

OptionsPage.prototype = {
  __proto__: cr.EventTarget.prototype,

  /**
   * Initializes page content.
   */
  initializePage: function() {},

  /**
   * Gets page visibility state.
   */
  get visible() {
    var page = $(this.pageDivName);
    return page.ownerDocument.defaultView.getComputedStyle(
        page).display == 'block';
  },

  /**
   * Sets page visibility.
   */
  set visible(visible) {
    if ((this.visible && visible) || (!this.visible && !visible))
      return;

    if (visible) {
      this.pageDiv.style.display = 'block';
      if (this.isOverlay) {
        var overlay = $('overlay');
        overlay.classList.remove('hidden');
      } else {
        window.history.pushState({pageName: this.name},
                                 this.title,
                                 '/' + this.name);
      }
      if (this.tab) {
        this.tab.classList.add('navbar-item-selected');
        if (this.tab.parentNode && this.tab.parentNode.id == 'subpagesnav')
          this.tab.classList.remove('hidden');
      }
    } else {
      if (this.isOverlay) {
        var overlay = $('overlay');
        overlay.classList.add('hidden');
      }
      this.pageDiv.style.display = 'none';
      if (this.tab) {
        this.tab.classList.remove('navbar-item-selected');
        if (this.tab.parentNode && this.tab.parentNode.id == 'subpagesnav')
          this.tab.classList.add('hidden');
      }
    }

    cr.dispatchPropertyChange(this, 'visible', visible, !visible);
  }
};
<commit_msg>Avoid js exception in history.pushState by not changing url.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

///////////////////////////////////////////////////////////////////////////////
// OptionsPage class:

/**
 * Base class for options page.
 * @constructor
 * @param {string} name Options page name, also defines id of the div element
 *     containing the options view and the name of options page navigation bar
 *     item as name+'PageNav'.
 * @param {string} title Options page title, used for navigation bar
 * @extends {EventTarget}
 */
function OptionsPage(name, title, pageDivName) {
  this.name = name;
  this.title = title;
  this.pageDivName = pageDivName;
  this.pageDiv = $(this.pageDivName);
  this.tab = null;
}

OptionsPage.registeredPages_ = {};

/**
 * Pages which are meant to have an entry in the nav, but
 * not have a permanent entry.
 */
OptionsPage.registeredSubPages_ = {};

/**
 * Pages which are meant to behave like model dialogs.
 */
OptionsPage.registeredOverlayPages_ = {};

/**
 * Shows a registered page.
 * @param {string} pageName Page name.
 */
OptionsPage.showPageByName = function(pageName) {
  for (var name in OptionsPage.registeredPages_) {
    var page = OptionsPage.registeredPages_[name];
    page.visible = name == pageName;
  }
};

/**
 * Shows a registered Overlay page.
 * @param {string} overlayName Page name.
 */
OptionsPage.showOverlay = function(overlayName) {
  if (OptionsPage.registeredOverlayPages_[overlayName]) {
    OptionsPage.registeredOverlayPages_[overlayName].visible = true;
  }
};

OptionsPage.clearOverlays = function() {
   for (var name in OptionsPage.registeredOverlayPages_) {
     var page = OptionsPage.registeredOverlayPages_[name];
     page.visible = false;
   }
};

/**
 * Registers new options page.
 * @param {OptionsPage} page Page to register.
 */
OptionsPage.register = function(page) {
  OptionsPage.registeredPages_[page.name] = page;
  // Create and add new page <li> element to navbar.
  var pageNav = document.createElement('li');
  pageNav.id = page.name + 'PageNav';
  pageNav.className = 'navbar-item';
  pageNav.setAttribute('pageName', page.name);
  pageNav.textContent = page.title;
  pageNav.onclick = function(event) {
    OptionsPage.showPageByName(this.getAttribute('pageName'));
  };
  var navbar = $('navbar');
  navbar.appendChild(pageNav);
  page.tab = pageNav;
  page.initializePage();
};

/**
 * Registers a new Sub tab page.
 * @param {OptionsPage} page Page to register.
 */
OptionsPage.registerSubPage = function(page) {
  OptionsPage.registeredPages_[page.name] = page;
  var pageNav = document.createElement('li');
  pageNav.id = page.name + 'PageNav';
  pageNav.className = 'navbar-item hidden';
  pageNav.setAttribute('pageName', page.name);
  pageNav.textContent = page.title;
  var subpagesnav = $('subpagesnav');
  subpagesnav.appendChild(pageNav);
  page.tab = pageNav;
  page.initializePage();
};

/**
 * Registers a new Overlay page.
 * @param {OptionsPage} page Page to register, must be a class derviced from
 * OptionsPage.
 */
OptionsPage.registerOverlay = function(page) {
  OptionsPage.registeredOverlayPages_[page.name] = page;
  page.tab = undefined;
  page.isOverlay = true;
  page.initializePage();
};

/**
 * Callback for window.onpopstate.
 * @param {Object} data State data pushed into history.
 */
OptionsPage.setState = function(data) {
  if (data && data.pageName) {
    OptionsPage.showPageByName(data.pageName);
  }
};

/**
 * Initializes the complete options page.  This will cause
 * all C++ handlers to be invoked to do final setup.
 */
OptionsPage.initialize = function() {
  chrome.send('coreOptionsInitialize');
};

OptionsPage.prototype = {
  __proto__: cr.EventTarget.prototype,

  /**
   * Initializes page content.
   */
  initializePage: function() {},

  /**
   * Gets page visibility state.
   */
  get visible() {
    var page = $(this.pageDivName);
    return page.ownerDocument.defaultView.getComputedStyle(
        page).display == 'block';
  },

  /**
   * Sets page visibility.
   */
  set visible(visible) {
    if ((this.visible && visible) || (!this.visible && !visible))
      return;

    if (visible) {
      this.pageDiv.style.display = 'block';
      if (this.isOverlay) {
        var overlay = $('overlay');
        overlay.classList.remove('hidden');
      } else {
        // Recent webkit change no longer allows url change from "chrome://".
        window.history.pushState({pageName: this.name},
                                 this.title);
      }
      if (this.tab) {
        this.tab.classList.add('navbar-item-selected');
        if (this.tab.parentNode && this.tab.parentNode.id == 'subpagesnav')
          this.tab.classList.remove('hidden');
      }
    } else {
      if (this.isOverlay) {
        var overlay = $('overlay');
        overlay.classList.add('hidden');
      }
      this.pageDiv.style.display = 'none';
      if (this.tab) {
        this.tab.classList.remove('navbar-item-selected');
        if (this.tab.parentNode && this.tab.parentNode.id == 'subpagesnav')
          this.tab.classList.add('hidden');
      }
    }

    cr.dispatchPropertyChange(this, 'visible', visible, !visible);
  }
};
<|endoftext|>


<commit_before>import { select, event } from 'd3-selection';
import { scaleIdentity } from 'd3-scale';
import { seriesSvgLine } from '@d3fc/d3fc-series';
import { axisBottom, axisRight, axisLeft, axisTop } from '@d3fc/d3fc-axis';
import { dataJoin } from '@d3fc/d3fc-data-join';
import { rebindAll, exclude, prefix, includeMap } from '@d3fc/d3fc-rebind';

const functor = (v) =>
  typeof v === 'function' ? v : () => v;

export default (d3fcElementType, plotAreaDrawFunction) =>
    (xScale = scaleIdentity(), yScale = scaleIdentity()) => {

        let yLabel = functor('');
        let xLabel = functor('');
        let yOrient = functor('right');
        let xOrient = functor('bottom');
        let chartLabel = functor('');
        let plotArea = seriesSvgLine();
        let xTickFormat = null;
        let xTicks;
        let xTickArguments;
        let xTickSize;
        let xTickSizeInner;
        let xTickSizeOuter;
        let xTickValues;
        let xTickPadding;
        let xDecorate = () => {};
        let yTickFormat = null;
        let yTicks;
        let yTickArguments;
        let yTickSize;
        let yTickSizeInner;
        let yTickSizeOuter;
        let yTickValues;
        let yTickPadding;
        let yDecorate = () => {};
        let decorate = () => {};

        const axisForOrient = (orient) => {
            switch (orient) {
            case 'bottom':
                return axisBottom();
            case 'top':
                return axisTop();
            case 'left':
                return axisLeft();
            case 'right':
                return axisRight();
            case 'none':
                return null;
            }
        };

        const xMargin = (yOrient) => {
            switch (yOrient) {
            case 'left':
                return 'margin-left: 4em';
            case 'right':
                return 'margin-right: 4em';
            default:
                return '';
            }
        };

        const xPadding = (yOrient) => {
            switch (yOrient) {
            case 'left':
                return 'padding-right: 1em';
            case 'right':
                return 'padding-left: 1em';
            case 'none':
                return 'padding-left: 1em; padding-right: 1em';
            default:
                return '';
            }
        };

        const colFlexDirection = (xOrient) => {
            switch (xOrient) {
            case 'bottom':
                return 'flex-direction: column';
            default:
                return 'flex-direction: column-reverse';
            }
        };

        const rowFlexDirection = (yOrient) => {
            switch (yOrient) {
            case 'right':
                return 'flex-direction: row';
            default:
                return 'flex-direction: row-reverse';
            }
        };

        const containerDataJoin = dataJoin('d3fc-group', 'cartesian-chart');

        const propagateTransition = maybeTransition => selection =>
            maybeTransition.selection ? selection.transition(maybeTransition) : selection;

        const cartesian = (selection) => {

            const transitionPropagator = propagateTransition(selection);

            selection.each((data, index, group) => {
                const container = containerDataJoin(select(group[index]), [data]);

                const xOrientValue = xOrient(data);
                const yOrientValue = yOrient(data);
                const xAxis = axisForOrient(xOrientValue);
                const yAxis = axisForOrient(yOrientValue);

                const xAxisMarkup = xAxis
                  ? `<d3fc-svg class='x-axis' style='height: 2em; ${xMargin(yOrientValue)}'></d3fc-svg>

`
                  : '';
                const yAxisMarkup = yAxis
                  ? `<d3fc-svg class='y-axis' style='width: 3em'></d3fc-svg>

`
                  : '';

                container.enter()
                    .attr('style', 'display: flex; height: 100%; width: 100%; flex-direction: column; overflow: hidden')
                    .attr('auto-resize', '')
                    .html(`

                                  <${d3fcElementType} class='plot-area' style='flex: 1'></${d3fcElementType}>
                                  ${yAxisMarkup}

                              ${xAxisMarkup}

`);

                container.select('.y-axis-label')
                    .text(yLabel(data));

                container.select('.x-axis-label')
                    .text(xLabel(data));

                container.select('.chart-label')
                    .text(chartLabel(data));

                container.select('.y-axis')
                    .on('measure', (d, i, nodes) => {
                        if (yOrientValue === 'left') {
                            const { width, height } = event.detail;
                            select(nodes[i])
                              .select('svg')
                              .attr('viewBox', `${-width} 0 ${width} ${height}`);
                        }
                    })
                    .on('draw', (d, i, nodes) => {
                        yAxis.tickFormat(yTickFormat)
                          .decorate(yDecorate);
                        if (yTicks) {
                            yAxis.ticks(...yTicks);
                        }
                        if (yTickArguments) {
                            yAxis.tickArguments(yTickArguments);
                        }
                        if (yTickSize) {
                            yAxis.tickSize(yTickSize);
                        }
                        if (yTickSizeInner) {
                            yAxis.tickSizeInner(yTickSizeInner);
                        }
                        if (yTickSizeOuter) {
                            yAxis.tickSizeOuter(yTickSizeOuter);
                        }
                        if (yTickValues) {
                            yAxis.tickValues(yTickValues);
                        }
                        if (yTickPadding) {
                            yAxis.tickPadding(yTickPadding);
                        }
                        transitionPropagator(select(nodes[i]))
                          .select('svg')
                          .call(yAxis.scale(yScale));
                    });

                container.select('.x-axis')
                    .on('measure', (d, i, nodes) => {
                        if (xOrientValue === 'top') {
                            const { width, height } = event.detail;
                            select(nodes[i])
                              .select('svg')
                              .attr('viewBox', `0 ${-height} ${width} ${height}`);
                        }
                    })
                    .on('draw', (d, i, nodes) => {
                        xAxis.tickFormat(xTickFormat)
                          .decorate(xDecorate);
                        if (xTicks) {
                            xAxis.ticks(...xTicks);
                        }
                        if (xTickArguments) {
                            xAxis.tickArguments(xTickArguments);
                        }
                        if (xTickSize) {
                            xAxis.tickSize(xTickSize);
                        }
                        if (xTickSizeInner) {
                            xAxis.tickSizeInner(xTickSizeInner);
                        }
                        if (xTickSizeOuter) {
                            xAxis.tickSizeOuter(xTickSizeOuter);
                        }
                        if (xTickValues) {
                            xAxis.tickValues(xTickValues);
                        }
                        if (xTickPadding) {
                            xAxis.tickPadding(xTickPadding);
                        }
                        transitionPropagator(select(nodes[i]))
                          .select('svg')
                          .call(xAxis.scale(xScale));
                    });

                container.select('.plot-area')
                    .on('measure', () => {
                        const { width, height } = event.detail;
                        xScale.range([0, width]);
                        yScale.range([height, 0]);
                    })
                    .on('draw', (d, i, nodes) => {
                        plotArea.xScale(xScale)
                          .yScale(yScale);
                        plotAreaDrawFunction(d, nodes[i], plotArea, transitionPropagator);
                    });

                container.each((_, index, group) => group[index].requestRedraw());

                decorate(container, data, index);
            });
        };

        const scaleExclusions = exclude(
            /range\w*/,   // the scale range is set via the component layout
            /tickFormat/  // use axis.tickFormat instead (only present on linear scales)
        );
        rebindAll(cartesian, xScale, scaleExclusions, prefix('x'));
        rebindAll(cartesian, yScale, scaleExclusions, prefix('y'));

        cartesian.xTickFormat = (...args) => {
            if (!args.length) {
                return xTickFormat;
            }
            xTickFormat = args[0];
            return cartesian;
        };
        cartesian.xTicks = (...args) => {
            if (!args.length) {
                return xTicks;
            }
            xTicks = args;
            return cartesian;
        };
        cartesian.xTickArguments = (...args) => {
            if (!args.length) {
                return xTickArguments;
            }
            xTickArguments = args[0];
            return cartesian;
        };
        cartesian.xTickSize = (...args) => {
            if (!args.length) {
                return xTickSize;
            }
            xTickSize = args[0];
            return cartesian;
        };
        cartesian.xTickSizeInner = (...args) => {
            if (!args.length) {
                return xTickSizeInner;
            }
            xTickSizeInner = args[0];
            return cartesian;
        };
        cartesian.xTickSizeOuter = (...args) => {
            if (!args.length) {
                return xTickSizeOuter;
            }
            xTickSizeOuter = args[0];
            return cartesian;
        };
        cartesian.xTickValues = (...args) => {
            if (!args.length) {
                return xTickValues;
            }
            xTickValues = args[0];
            return cartesian;
        };
        cartesian.xTickPadding = (...args) => {
            if (!args.length) {
                return xTickPadding;
            }
            xTickPadding = args[0];
            return cartesian;
        };
        cartesian.xDecorate = (...args) => {
            if (!args.length) {
                return xDecorate;
            }
            xDecorate = args[0];
            return cartesian;
        };
        cartesian.yTickFormat = (...args) => {
            if (!args.length) {
                return yTickFormat;
            }
            yTickFormat = args[0];
            return cartesian;
        };
        cartesian.yTicks = (...args) => {
            if (!args.length) {
                return yTicks;
            }
            yTicks = args;
            return cartesian;
        };
        cartesian.yTickArguments = (...args) => {
            if (!args.length) {
                return yTickArguments;
            }
            yTickArguments = args[0];
            return cartesian;
        };
        cartesian.yTickSize = (...args) => {
            if (!args.length) {
                return yTickSize;
            }
            yTickSize = args[0];
            return cartesian;
        };
        cartesian.yTickSizeInner = (...args) => {
            if (!args.length) {
                return yTickSizeInner;
            }
            yTickSizeInner = args[0];
            return cartesian;
        };
        cartesian.yTickSizeOuter = (...args) => {
            if (!args.length) {
                return yTickSizeOuter;
            }
            yTickSizeOuter = args[0];
            return cartesian;
        };
        cartesian.yTickValues = (...args) => {
            if (!args.length) {
                return yTickValues;
            }
            yTickValues = args[0];
            return cartesian;
        };
        cartesian.yTickPadding = (...args) => {
            if (!args.length) {
                return yTickPadding;
            }
            yTickPadding = args[0];
            return cartesian;
        };
        cartesian.yDecorate = (...args) => {
            if (!args.length) {
                return yDecorate;
            }
            yDecorate = args[0];
            return cartesian;
        };
        cartesian.yOrient = (...args) => {
            if (!args.length) {
                return yOrient;
            }
            yOrient = functor(args[0]);
            return cartesian;
        };
        cartesian.xOrient = (...args) => {
            if (!args.length) {
                return xOrient;
            }
            xOrient = functor(args[0]);
            return cartesian;
        };
        cartesian.chartLabel = (...args) => {
            if (!args.length) {
                return chartLabel;
            }
            chartLabel = functor(args[0]);
            return cartesian;
        };
        cartesian.plotArea = (...args) => {
            if (!args.length) {
                return plotArea;
            }
            plotArea = args[0];
            return cartesian;
        };
        cartesian.xLabel = (...args) => {
            if (!args.length) {
                return xLabel;
            }
            xLabel = functor(args[0]);
            return cartesian;
        };
        cartesian.yLabel = (...args) => {
            if (!args.length) {
                return yLabel;
            }
            yLabel = functor(args[0]);
            return cartesian;
        };
        cartesian.decorate = (...args) => {
            if (!args.length) {
                return decorate;
            }
            decorate = args[0];
            return cartesian;
        };

        return cartesian;

    };
<commit_msg>fix: add overflow hidden to plot-area<commit_after>import { select, event } from 'd3-selection';
import { scaleIdentity } from 'd3-scale';
import { seriesSvgLine } from '@d3fc/d3fc-series';
import { axisBottom, axisRight, axisLeft, axisTop } from '@d3fc/d3fc-axis';
import { dataJoin } from '@d3fc/d3fc-data-join';
import { rebindAll, exclude, prefix, includeMap } from '@d3fc/d3fc-rebind';

const functor = (v) =>
  typeof v === 'function' ? v : () => v;

export default (d3fcElementType, plotAreaDrawFunction) =>
    (xScale = scaleIdentity(), yScale = scaleIdentity()) => {

        let yLabel = functor('');
        let xLabel = functor('');
        let yOrient = functor('right');
        let xOrient = functor('bottom');
        let chartLabel = functor('');
        let plotArea = seriesSvgLine();
        let xTickFormat = null;
        let xTicks;
        let xTickArguments;
        let xTickSize;
        let xTickSizeInner;
        let xTickSizeOuter;
        let xTickValues;
        let xTickPadding;
        let xDecorate = () => {};
        let yTickFormat = null;
        let yTicks;
        let yTickArguments;
        let yTickSize;
        let yTickSizeInner;
        let yTickSizeOuter;
        let yTickValues;
        let yTickPadding;
        let yDecorate = () => {};
        let decorate = () => {};

        const axisForOrient = (orient) => {
            switch (orient) {
            case 'bottom':
                return axisBottom();
            case 'top':
                return axisTop();
            case 'left':
                return axisLeft();
            case 'right':
                return axisRight();
            case 'none':
                return null;
            }
        };

        const xMargin = (yOrient) => {
            switch (yOrient) {
            case 'left':
                return 'margin-left: 4em';
            case 'right':
                return 'margin-right: 4em';
            default:
                return '';
            }
        };

        const xPadding = (yOrient) => {
            switch (yOrient) {
            case 'left':
                return 'padding-right: 1em';
            case 'right':
                return 'padding-left: 1em';
            case 'none':
                return 'padding-left: 1em; padding-right: 1em';
            default:
                return '';
            }
        };

        const colFlexDirection = (xOrient) => {
            switch (xOrient) {
            case 'bottom':
                return 'flex-direction: column';
            default:
                return 'flex-direction: column-reverse';
            }
        };

        const rowFlexDirection = (yOrient) => {
            switch (yOrient) {
            case 'right':
                return 'flex-direction: row';
            default:
                return 'flex-direction: row-reverse';
            }
        };

        const containerDataJoin = dataJoin('d3fc-group', 'cartesian-chart');

        const propagateTransition = maybeTransition => selection =>
            maybeTransition.selection ? selection.transition(maybeTransition) : selection;

        const cartesian = (selection) => {

            const transitionPropagator = propagateTransition(selection);

            selection.each((data, index, group) => {
                const container = containerDataJoin(select(group[index]), [data]);

                const xOrientValue = xOrient(data);
                const yOrientValue = yOrient(data);
                const xAxis = axisForOrient(xOrientValue);
                const yAxis = axisForOrient(yOrientValue);

                const xAxisMarkup = xAxis
                  ? `<d3fc-svg class='x-axis' style='height: 2em; ${xMargin(yOrientValue)}'></d3fc-svg>

`
                  : '';
                const yAxisMarkup = yAxis
                  ? `<d3fc-svg class='y-axis' style='width: 3em'></d3fc-svg>

`
                  : '';

                container.enter()
                    .attr('style', 'display: flex; height: 100%; width: 100%; flex-direction: column; overflow: hidden')
                    .attr('auto-resize', '')
                    .html(`

                                  <${d3fcElementType} class='plot-area' style='flex: 1; overflow: hidden'></${d3fcElementType}>
                                  ${yAxisMarkup}

                              ${xAxisMarkup}

`);

                container.select('.y-axis-label')
                    .text(yLabel(data));

                container.select('.x-axis-label')
                    .text(xLabel(data));

                container.select('.chart-label')
                    .text(chartLabel(data));

                container.select('.y-axis')
                    .on('measure', (d, i, nodes) => {
                        if (yOrientValue === 'left') {
                            const { width, height } = event.detail;
                            select(nodes[i])
                              .select('svg')
                              .attr('viewBox', `${-width} 0 ${width} ${height}`);
                        }
                    })
                    .on('draw', (d, i, nodes) => {
                        yAxis.tickFormat(yTickFormat)
                          .decorate(yDecorate);
                        if (yTicks) {
                            yAxis.ticks(...yTicks);
                        }
                        if (yTickArguments) {
                            yAxis.tickArguments(yTickArguments);
                        }
                        if (yTickSize) {
                            yAxis.tickSize(yTickSize);
                        }
                        if (yTickSizeInner) {
                            yAxis.tickSizeInner(yTickSizeInner);
                        }
                        if (yTickSizeOuter) {
                            yAxis.tickSizeOuter(yTickSizeOuter);
                        }
                        if (yTickValues) {
                            yAxis.tickValues(yTickValues);
                        }
                        if (yTickPadding) {
                            yAxis.tickPadding(yTickPadding);
                        }
                        transitionPropagator(select(nodes[i]))
                          .select('svg')
                          .call(yAxis.scale(yScale));
                    });

                container.select('.x-axis')
                    .on('measure', (d, i, nodes) => {
                        if (xOrientValue === 'top') {
                            const { width, height } = event.detail;
                            select(nodes[i])
                              .select('svg')
                              .attr('viewBox', `0 ${-height} ${width} ${height}`);
                        }
                    })
                    .on('draw', (d, i, nodes) => {
                        xAxis.tickFormat(xTickFormat)
                          .decorate(xDecorate);
                        if (xTicks) {
                            xAxis.ticks(...xTicks);
                        }
                        if (xTickArguments) {
                            xAxis.tickArguments(xTickArguments);
                        }
                        if (xTickSize) {
                            xAxis.tickSize(xTickSize);
                        }
                        if (xTickSizeInner) {
                            xAxis.tickSizeInner(xTickSizeInner);
                        }
                        if (xTickSizeOuter) {
                            xAxis.tickSizeOuter(xTickSizeOuter);
                        }
                        if (xTickValues) {
                            xAxis.tickValues(xTickValues);
                        }
                        if (xTickPadding) {
                            xAxis.tickPadding(xTickPadding);
                        }
                        transitionPropagator(select(nodes[i]))
                          .select('svg')
                          .call(xAxis.scale(xScale));
                    });

                container.select('.plot-area')
                    .on('measure', () => {
                        const { width, height } = event.detail;
                        xScale.range([0, width]);
                        yScale.range([height, 0]);
                    })
                    .on('draw', (d, i, nodes) => {
                        plotArea.xScale(xScale)
                          .yScale(yScale);
                        plotAreaDrawFunction(d, nodes[i], plotArea, transitionPropagator);
                    });

                container.each((_, index, group) => group[index].requestRedraw());

                decorate(container, data, index);
            });
        };

        const scaleExclusions = exclude(
            /range\w*/,   // the scale range is set via the component layout
            /tickFormat/  // use axis.tickFormat instead (only present on linear scales)
        );
        rebindAll(cartesian, xScale, scaleExclusions, prefix('x'));
        rebindAll(cartesian, yScale, scaleExclusions, prefix('y'));

        cartesian.xTickFormat = (...args) => {
            if (!args.length) {
                return xTickFormat;
            }
            xTickFormat = args[0];
            return cartesian;
        };
        cartesian.xTicks = (...args) => {
            if (!args.length) {
                return xTicks;
            }
            xTicks = args;
            return cartesian;
        };
        cartesian.xTickArguments = (...args) => {
            if (!args.length) {
                return xTickArguments;
            }
            xTickArguments = args[0];
            return cartesian;
        };
        cartesian.xTickSize = (...args) => {
            if (!args.length) {
                return xTickSize;
            }
            xTickSize = args[0];
            return cartesian;
        };
        cartesian.xTickSizeInner = (...args) => {
            if (!args.length) {
                return xTickSizeInner;
            }
            xTickSizeInner = args[0];
            return cartesian;
        };
        cartesian.xTickSizeOuter = (...args) => {
            if (!args.length) {
                return xTickSizeOuter;
            }
            xTickSizeOuter = args[0];
            return cartesian;
        };
        cartesian.xTickValues = (...args) => {
            if (!args.length) {
                return xTickValues;
            }
            xTickValues = args[0];
            return cartesian;
        };
        cartesian.xTickPadding = (...args) => {
            if (!args.length) {
                return xTickPadding;
            }
            xTickPadding = args[0];
            return cartesian;
        };
        cartesian.xDecorate = (...args) => {
            if (!args.length) {
                return xDecorate;
            }
            xDecorate = args[0];
            return cartesian;
        };
        cartesian.yTickFormat = (...args) => {
            if (!args.length) {
                return yTickFormat;
            }
            yTickFormat = args[0];
            return cartesian;
        };
        cartesian.yTicks = (...args) => {
            if (!args.length) {
                return yTicks;
            }
            yTicks = args;
            return cartesian;
        };
        cartesian.yTickArguments = (...args) => {
            if (!args.length) {
                return yTickArguments;
            }
            yTickArguments = args[0];
            return cartesian;
        };
        cartesian.yTickSize = (...args) => {
            if (!args.length) {
                return yTickSize;
            }
            yTickSize = args[0];
            return cartesian;
        };
        cartesian.yTickSizeInner = (...args) => {
            if (!args.length) {
                return yTickSizeInner;
            }
            yTickSizeInner = args[0];
            return cartesian;
        };
        cartesian.yTickSizeOuter = (...args) => {
            if (!args.length) {
                return yTickSizeOuter;
            }
            yTickSizeOuter = args[0];
            return cartesian;
        };
        cartesian.yTickValues = (...args) => {
            if (!args.length) {
                return yTickValues;
            }
            yTickValues = args[0];
            return cartesian;
        };
        cartesian.yTickPadding = (...args) => {
            if (!args.length) {
                return yTickPadding;
            }
            yTickPadding = args[0];
            return cartesian;
        };
        cartesian.yDecorate = (...args) => {
            if (!args.length) {
                return yDecorate;
            }
            yDecorate = args[0];
            return cartesian;
        };
        cartesian.yOrient = (...args) => {
            if (!args.length) {
                return yOrient;
            }
            yOrient = functor(args[0]);
            return cartesian;
        };
        cartesian.xOrient = (...args) => {
            if (!args.length) {
                return xOrient;
            }
            xOrient = functor(args[0]);
            return cartesian;
        };
        cartesian.chartLabel = (...args) => {
            if (!args.length) {
                return chartLabel;
            }
            chartLabel = functor(args[0]);
            return cartesian;
        };
        cartesian.plotArea = (...args) => {
            if (!args.length) {
                return plotArea;
            }
            plotArea = args[0];
            return cartesian;
        };
        cartesian.xLabel = (...args) => {
            if (!args.length) {
                return xLabel;
            }
            xLabel = functor(args[0]);
            return cartesian;
        };
        cartesian.yLabel = (...args) => {
            if (!args.length) {
                return yLabel;
            }
            yLabel = functor(args[0]);
            return cartesian;
        };
        cartesian.decorate = (...args) => {
            if (!args.length) {
                return decorate;
            }
            decorate = args[0];
            return cartesian;
        };

        return cartesian;

    };
<|endoftext|>


<commit_before>var Gu = require('gu')
  , guParams = require('../')
  , sulfur = require('sulfur');

exports.response = function (t) {
  var clvr = new Gu(guParams.scriptdir, guParams.files, { noReload: true });
  sulfur.absorb(clvr.log, 'gu');
  var xs = [
    {user: '#chan:clux', name: 'clux', message: 'hi clvr'},
  ];
  xs.forEach(function (x) {
    clvr.write(x);
  });

  clvr.addListener('readable', function () {
    var resp = clvr.read();
    t.ok(resp, 'got a response');
    t.done();
  });
};
<commit_msg>better test notes<commit_after>var Gu = require('gu')
  , guParams = require('../')
  , sulfur = require('sulfur');

exports.response = function (t) {
  var clvr = new Gu(guParams.scriptdir, guParams.files, { noReload: true });
  sulfur.absorb(clvr.log, 'gu');
  var xs = [
    {user: '#chan:clux', name: 'clux', message: 'hi clvr'},
  ];
  xs.forEach(function (x) {
    clvr.write(x);
  });

  clvr.on('readable', function () {
    var resp = clvr.read();
    t.ok(resp, 'got a response');
    t.equal(resp.user, '#chan:clux', 'addressed to me');
    // TODO: if it starts failing - create a test to ensure
    // resp is not equal to "<html>"" or whatever it returns when permissions fail
    t.done();
  });
};
<|endoftext|>


<commit_before>/*jshint browser: true */
/*jshint unused: false */
/*global require, window, exports, Backbone, EJS, $, templateEngine, arangoHelper, Joi*/

(function() {
  "use strict";

  window.CollectionListItemView = Backbone.View.extend({

    tagName: "div",
    className: "tile",
    template: templateEngine.createTemplate("collectionsItemView.ejs"),

    initialize: function () {
      this.collectionsView = this.options.collectionsView;
    },
    events: {
      'click .iconSet.icon_arangodb_settings2': 'createEditPropertiesModal',
      'click .pull-left' : 'noop',
      'click .icon_arangodb_settings2' : 'editProperties',
//      'click #editCollection' : 'editProperties',
      'click .spanInfo' : 'showProperties',
      'click': 'selectCollection'
    },

    render: function () {
      $(this.el).html(this.template.render({
        model: this.model
      }));
      $(this.el).attr('id', 'collection_' + this.model.get('name'));
      return this;
    },

    editProperties: function (event) {
      event.stopPropagation();
      this.createEditPropertiesModal();
    },

    showProperties: function(event) {
      event.stopPropagation();
      this.createInfoModal();
/*
      window.App.navigate(
        "collectionInfo/" + encodeURIComponent(this.model.get("id")), {trigger: true}
      );
*/
    },

    selectCollection: function(event) {

      //check if event was fired from disabled button
      if ($(event.target).hasClass("disabled")) {
        return 0;
      }

      window.App.navigate(
        "collection/" + encodeURIComponent(this.model.get("name")) + "/documents/1", {trigger: true}
      );
    },

    noop: function(event) {
      event.stopPropagation();
    },

    unloadCollection: function () {
      this.model.unloadCollection();
      this.render();
      window.modalView.hide();
    },

    loadCollection: function () {
      this.model.loadCollection();
      this.render();
      window.modalView.hide();
    },

    deleteCollection: function () {
      this.model.destroy(
        {
          error: function() {
            arangoHelper.arangoError('Could not delete collection.');
          },
          success: function() {
            window.modalView.hide();
          }
        }
      );
      this.collectionsView.render();
    },

    saveModifiedCollection: function() {
      var newname;
      if (window.isCoordinator()) {
        newname = this.model.get('name');
      }
      else {
        newname = $('#change-collection-name').val();
      }

      var status = this.model.get('status');

      if (status === 'loaded') {
        var result;
        if (this.model.get('name') !== newname) {
          result = this.model.renameCollection(newname);
        }

        var wfs = $('#change-collection-sync').val();
        var journalSize;
        try {
          journalSize = JSON.parse($('#change-collection-size').val() * 1024 * 1024);
        }
        catch (e) {
          arangoHelper.arangoError('Please enter a valid number');
          return 0;
        }
        var changeResult = this.model.changeCollection(wfs, journalSize);

        if (result !== true) {
          if (result !== undefined) {
            arangoHelper.arangoError("Collection error: " + result);
            return 0;
          }
        }

        if (changeResult !== true) {
          arangoHelper.arangoNotification("Collection error", changeResult);
          return 0;
        }

        if (changeResult === true) {
          this.collectionsView.render();
          window.modalView.hide();
        }
      }
      else if (status === 'unloaded') {
        if (this.model.get('name') !== newname) {
          var result2 = this.model.renameCollection(newname);
          if (result2 === true) {
            this.collectionsView.render();
            window.modalView.hide();
          }
          else {
            arangoHelper.arangoError("Collection error: " + result2);
          }
        }
        else {
          window.modalView.hide();
        }
      }
    },

    //modal dialogs

    createEditPropertiesModal: function() {

      var collectionIsLoaded = false;

      if (this.model.get('status') === "loaded") {
        collectionIsLoaded = true;
      }

      var buttons = [],
        tableContent = [];

      if (! window.isCoordinator()) {
        tableContent.push(
          window.modalView.createTextEntry(
            "change-collection-name",
            "Name",
            this.model.get('name'),
            false,
            "",
            true,
            [
              {
                rule: Joi.string().regex(/^[a-zA-Z]/),
                msg: "Collection name must always start with a letter."
              },
              {
                rule: Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),
                msg: 'Only Symbols "_" and "-" are allowed.'
              },
              {
                rule: Joi.string().required(),
                msg: "No collection name given."
              }
            ]
          )
        );
      }

      if (collectionIsLoaded) {
        // needs to be refactored. move getProperties into model
        var journalSize = this.model.getProperties().journalSize;
        journalSize = journalSize/(1024*1024);

        tableContent.push(
          window.modalView.createTextEntry(
            "change-collection-size",
            "Journal size",
            journalSize,
            "The maximal size of a journal or datafile (in MB). Must be at least 1.",
            "",
            true,
            [
              {
                rule: Joi.string().required(),
                msg: "No journal size given."
              },
              {
                rule: Joi.string().regex(/^[0-9]*$/),
                msg: "Must be a number."
              }
            ]
          )
        );
      }

      if(collectionIsLoaded) {
        // prevent "unexpected sync method error"
                var wfs = this.model.getProperties().waitForSync;
                tableContent.push(
          window.modalView.createSelectEntry(
            "change-collection-sync",
            "Wait for sync",
            wfs,
            "Synchronise to disk before returning from a create or update of a document.",
            [{value: false, label: "No"}, {value: true, label: "Yes"}]        )
        );
      }

      tableContent.push(
        window.modalView.createReadOnlyEntry(
          "change-collection-id", "ID", this.model.get('id'), ""
        )
      );
      tableContent.push(
        window.modalView.createReadOnlyEntry(
          "change-collection-type", "Type", this.model.get('type'), ""
        )
      );
      tableContent.push(
        window.modalView.createReadOnlyEntry(
          "change-collection-status", "Status", this.model.get('status'), ""
        )
      );
      if(collectionIsLoaded) {
        buttons.push(
          window.modalView.createNotificationButton(
            "Unload",
            this.unloadCollection.bind(this)
          )
        );
      } else {
        buttons.push(
          window.modalView.createNotificationButton(
            "Load",
            this.loadCollection.bind(this)
          )
        );
      }

      buttons.push(
        window.modalView.createDeleteButton(
          "Delete",
          this.deleteCollection.bind(this)
        )
      );
      buttons.push(
        window.modalView.createSuccessButton(
          "Save",
          this.saveModifiedCollection.bind(this)
        )
      );

      window.modalView.show(
        "modalTable.ejs",
        "Modify Collection",
        buttons,
        tableContent
      );
    },

    createInfoModal: function() {
      var buttons = [],
        tableContent = this.model;
      window.modalView.show(
        "modalCollectionInfo.ejs",
        "Collection: " + this.model.get('name'),
        buttons,
        tableContent
      );

    }

  });
}());
<commit_msg>added feature for truncating a collection<commit_after>/*jshint browser: true */
/*jshint unused: false */
/*global require, window, exports, Backbone, EJS, $, templateEngine, arangoHelper, Joi*/

(function() {
  "use strict";

  window.CollectionListItemView = Backbone.View.extend({

    tagName: "div",
    className: "tile",
    template: templateEngine.createTemplate("collectionsItemView.ejs"),

    initialize: function () {
      this.collectionsView = this.options.collectionsView;
    },
    events: {
      'click .iconSet.icon_arangodb_settings2': 'createEditPropertiesModal',
      'click .pull-left' : 'noop',
      'click .icon_arangodb_settings2' : 'editProperties',
//      'click #editCollection' : 'editProperties',
      'click .spanInfo' : 'showProperties',
      'click': 'selectCollection'
    },

    render: function () {
      $(this.el).html(this.template.render({
        model: this.model
      }));
      $(this.el).attr('id', 'collection_' + this.model.get('name'));
      return this;
    },

    editProperties: function (event) {
      event.stopPropagation();
      this.createEditPropertiesModal();
    },

    showProperties: function(event) {
      event.stopPropagation();
      this.createInfoModal();
/*
      window.App.navigate(
        "collectionInfo/" + encodeURIComponent(this.model.get("id")), {trigger: true}
      );
*/
    },

    selectCollection: function(event) {

      //check if event was fired from disabled button
      if ($(event.target).hasClass("disabled")) {
        return 0;
      }

      window.App.navigate(
        "collection/" + encodeURIComponent(this.model.get("name")) + "/documents/1", {trigger: true}
      );
    },

    noop: function(event) {
      event.stopPropagation();
    },

    unloadCollection: function () {
      this.model.unloadCollection();
      this.render();
      window.modalView.hide();
    },

    loadCollection: function () {
      this.model.loadCollection();
      this.render();
      window.modalView.hide();
    },

    truncateCollection: function () {
      this.model.truncateCollection();
      this.render();
      window.modalView.hide();
    },

    deleteCollection: function () {
      this.model.destroy(
        {
          error: function() {
            arangoHelper.arangoError('Could not delete collection.');
          },
          success: function() {
            window.modalView.hide();
          }
        }
      );
      this.collectionsView.render();
    },

    saveModifiedCollection: function() {
      var newname;
      if (window.isCoordinator()) {
        newname = this.model.get('name');
      }
      else {
        newname = $('#change-collection-name').val();
      }

      var status = this.model.get('status');

      if (status === 'loaded') {
        var result;
        if (this.model.get('name') !== newname) {
          result = this.model.renameCollection(newname);
        }

        var wfs = $('#change-collection-sync').val();
        var journalSize;
        try {
          journalSize = JSON.parse($('#change-collection-size').val() * 1024 * 1024);
        }
        catch (e) {
          arangoHelper.arangoError('Please enter a valid number');
          return 0;
        }
        var changeResult = this.model.changeCollection(wfs, journalSize);

        if (result !== true) {
          if (result !== undefined) {
            arangoHelper.arangoError("Collection error: " + result);
            return 0;
          }
        }

        if (changeResult !== true) {
          arangoHelper.arangoNotification("Collection error", changeResult);
          return 0;
        }

        if (changeResult === true) {
          this.collectionsView.render();
          window.modalView.hide();
        }
      }
      else if (status === 'unloaded') {
        if (this.model.get('name') !== newname) {
          var result2 = this.model.renameCollection(newname);
          if (result2 === true) {
            this.collectionsView.render();
            window.modalView.hide();
          }
          else {
            arangoHelper.arangoError("Collection error: " + result2);
          }
        }
        else {
          window.modalView.hide();
        }
      }
    },

    //modal dialogs

    createEditPropertiesModal: function() {

      var collectionIsLoaded = false;

      if (this.model.get('status') === "loaded") {
        collectionIsLoaded = true;
      }

      var buttons = [],
        tableContent = [];

      if (! window.isCoordinator()) {
        tableContent.push(
          window.modalView.createTextEntry(
            "change-collection-name",
            "Name",
            this.model.get('name'),
            false,
            "",
            true,
            [
              {
                rule: Joi.string().regex(/^[a-zA-Z]/),
                msg: "Collection name must always start with a letter."
              },
              {
                rule: Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),
                msg: 'Only Symbols "_" and "-" are allowed.'
              },
              {
                rule: Joi.string().required(),
                msg: "No collection name given."
              }
            ]
          )
        );
      }

      if (collectionIsLoaded) {
        // needs to be refactored. move getProperties into model
        var journalSize = this.model.getProperties().journalSize;
        journalSize = journalSize/(1024*1024);

        tableContent.push(
          window.modalView.createTextEntry(
            "change-collection-size",
            "Journal size",
            journalSize,
            "The maximal size of a journal or datafile (in MB). Must be at least 1.",
            "",
            true,
            [
              {
                rule: Joi.string().required(),
                msg: "No journal size given."
              },
              {
                rule: Joi.string().regex(/^[0-9]*$/),
                msg: "Must be a number."
              }
            ]
          )
        );
      }

      if(collectionIsLoaded) {
        // prevent "unexpected sync method error"
                var wfs = this.model.getProperties().waitForSync;
                tableContent.push(
          window.modalView.createSelectEntry(
            "change-collection-sync",
            "Wait for sync",
            wfs,
            "Synchronise to disk before returning from a create or update of a document.",
            [{value: false, label: "No"}, {value: true, label: "Yes"}]        )
        );
      }

      tableContent.push(
        window.modalView.createReadOnlyEntry(
          "change-collection-id", "ID", this.model.get('id'), ""
        )
      );
      tableContent.push(
        window.modalView.createReadOnlyEntry(
          "change-collection-type", "Type", this.model.get('type'), ""
        )
      );
      tableContent.push(
        window.modalView.createReadOnlyEntry(
          "change-collection-status", "Status", this.model.get('status'), ""
        )
      );
      buttons.push(
        window.modalView.createDeleteButton(
          "Delete",
          this.deleteCollection.bind(this)
        )
      );
      buttons.push(
        window.modalView.createDeleteButton(
          "Truncate",
          this.truncateCollection.bind(this)
        )
      );
      if(collectionIsLoaded) {
        buttons.push(
          window.modalView.createNotificationButton(
            "Unload",
            this.unloadCollection.bind(this)
          )
        );
      } else {
        buttons.push(
          window.modalView.createNotificationButton(
            "Load",
            this.loadCollection.bind(this)
          )
        );
      }

      buttons.push(
        window.modalView.createSuccessButton(
          "Save",
          this.saveModifiedCollection.bind(this)
        )
      );

      window.modalView.show(
        "modalTable.ejs",
        "Modify Collection",
        buttons,
        tableContent
      );
    },

    createInfoModal: function() {
      var buttons = [],
        tableContent = this.model;
      window.modalView.show(
        "modalCollectionInfo.ejs",
        "Collection: " + this.model.get('name'),
        buttons,
        tableContent
      );

    }

  });
}());
<|endoftext|>


<commit_before>export default class CoreFeature{

	constructor(table){
		this.table = table;
	}

	//////////////////////////////////////////
	/////////////// DataLoad /////////////////
	//////////////////////////////////////////

	reloadData(data, silent){
		return this.table.dataLoader.load(data, undefined, undefined, undefined, silent);
	}

	//////////////////////////////////////////
	///////////// Localization ///////////////
	//////////////////////////////////////////

	langText(){
		return this.table.modules.localize.getText(...arguments);
	}

	langBind(){
		return this.table.modules.localize.bind(...arguments);
	}

	langLocale(){
		return this.table.modules.localize.getLocale(...arguments);
	}

	//////////////////////////////////////////
	////////// Inter Table Comms /////////////
	//////////////////////////////////////////

	commsConnections(){
		return this.table.modules.comms.getConnections(...arguments);
	}

	commsSend(){
		return this.table.modules.comms.send(...arguments);
	}

	//////////////////////////////////////////
	//////////////// Layout  /////////////////
	//////////////////////////////////////////

	layoutMode(){
		return this.table.modules.layout.getMode();
	}

	layoutRefresh(){
		return this.table.modules.layout.layout();
	}

	//////////////////////////////////////////
	/////////////// Event Bus ////////////////
	//////////////////////////////////////////

	subscribe(){
		this.table.eventBus.subscribe(...arguments);
	}

	unsubscribe(){
		this.table.eventBus.unsubscribe(...arguments);
	}

	subscribed(key){
		this.table.eventBus.subscribed(key);
	}

	subscriptionChange(){
		this.table.eventBus.subscriptionChange(...arguments);
	}

	dispatch(){
		this.table.eventBus.dispatch(...arguments);
	}

	chain(){
		return this.table.eventBus.chain(...arguments);
	}

	confirm(){
		return this.table.eventBus.confirm(...arguments);
	}

	dispatchExternal(){
		this.table.externalEvents.dispatch(...arguments);
	}

	subscribedExternal(key){
		this.table.externalEvents.subscribed(key);
	}

	subscriptionChangeExternal(){
		this.table.externalEvents.subscriptionChange(...arguments);
	}

	//////////////////////////////////////////
	//////////////// Options /////////////////
	//////////////////////////////////////////

	options(key, value){
		if(typeof value !== "undefined"){
			this.table.options[key] = value;
		}

		return this.table.options[key];
	}

	setOption(key, value){
		if(typeof value !== "undefined"){
			this.table.options[key] = value;
		}

		return this.table.options[key];
	}

	//////////////////////////////////////////
	//////////////// Modules /////////////////
	//////////////////////////////////////////

	module(key){
		return this.table.module(key);
	}
}<commit_msg>ensure coreFreature base class returns results of function calls<commit_after>export default class CoreFeature{

	constructor(table){
		this.table = table;
	}

	//////////////////////////////////////////
	/////////////// DataLoad /////////////////
	//////////////////////////////////////////

	reloadData(data, silent){
		return this.table.dataLoader.load(data, undefined, undefined, undefined, silent);
	}

	//////////////////////////////////////////
	///////////// Localization ///////////////
	//////////////////////////////////////////

	langText(){
		return this.table.modules.localize.getText(...arguments);
	}

	langBind(){
		return this.table.modules.localize.bind(...arguments);
	}

	langLocale(){
		return this.table.modules.localize.getLocale(...arguments);
	}

	//////////////////////////////////////////
	////////// Inter Table Comms /////////////
	//////////////////////////////////////////

	commsConnections(){
		return this.table.modules.comms.getConnections(...arguments);
	}

	commsSend(){
		return this.table.modules.comms.send(...arguments);
	}

	//////////////////////////////////////////
	//////////////// Layout  /////////////////
	//////////////////////////////////////////

	layoutMode(){
		return this.table.modules.layout.getMode();
	}

	layoutRefresh(){
		return this.table.modules.layout.layout();
	}

	//////////////////////////////////////////
	/////////////// Event Bus ////////////////
	//////////////////////////////////////////

	subscribe(){
		return this.table.eventBus.subscribe(...arguments);
	}

	unsubscribe(){
		return this.table.eventBus.unsubscribe(...arguments);
	}

	subscribed(key){
		return this.table.eventBus.subscribed(key);
	}

	subscriptionChange(){
		return this.table.eventBus.subscriptionChange(...arguments);
	}

	dispatch(){
		return this.table.eventBus.dispatch(...arguments);
	}

	chain(){
		return this.table.eventBus.chain(...arguments);
	}

	confirm(){
		return this.table.eventBus.confirm(...arguments);
	}

	dispatchExternal(){
		return this.table.externalEvents.dispatch(...arguments);
	}

	subscribedExternal(key){
		return this.table.externalEvents.subscribed(key);
	}

	subscriptionChangeExternal(){
		return this.table.externalEvents.subscriptionChange(...arguments);
	}

	//////////////////////////////////////////
	//////////////// Options /////////////////
	//////////////////////////////////////////

	options(key, value){
		if(typeof value !== "undefined"){
			this.table.options[key] = value;
		}

		return this.table.options[key];
	}

	setOption(key, value){
		if(typeof value !== "undefined"){
			this.table.options[key] = value;
		}

		return this.table.options[key];
	}

	//////////////////////////////////////////
	//////////////// Modules /////////////////
	//////////////////////////////////////////

	module(key){
		return this.table.module(key);
	}
}<|endoftext|>


<commit_before><commit_msg>Output Numbers<commit_after><|endoftext|>


<commit_before>var dbauth = {
    user: 'akroatis_mongoadmin',
    pass: 'Ieth3ahd1c',
    db: 'akroatis',
    port: '21145',
    host: 'localhost'
};

module.exports = dbauth;<commit_msg>Delete database.js<commit_after><|endoftext|>


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

  var metas = Array.prototype.slice.call(document.querySelectorAll('meta[name][content]'));
  metas = metas.filter(util.caseInsensitiveAttributeValueFilter('name', 'viewport'));

  var score = 100;
  var offending = [];
  metas.forEach(function(meta) {
    if (meta.content.indexOf('user-scalable=no') > -1 || meta.content.indexOf('initial-scale=1.0; maximum-scale=1.0') > -1) {
      score = 0;
      offending.push(meta);
    }
  });

  return {
    id: 'neverSuppressZoom',
    title: 'Don\'t suppress pinch zoom',
    description: 'A key feature of mobile browsing is being able to zoom in to read content and out to locate content within a page. http://www.iheni.com/mobile-accessibility-tip-dont-suppress-pinch-zoom/',
    advice: score === 0 ? 'What! The page suppress zooming, you really shouldn\'t do that.' : '',
    score: score,
    weight: 8,
    offending: offending,
    tags: ['accessibility']
  };

})(util);
<commit_msg>show meta content when supressing zoom<commit_after>(function(util) {
  'use strict';

  var metas = Array.prototype.slice.call(document.querySelectorAll('meta[name][content]'));
  metas = metas.filter(util.caseInsensitiveAttributeValueFilter('name', 'viewport'));

  var score = 100;
  var offending = [];
  metas.forEach(function(meta) {
    if (meta.content.indexOf('user-scalable=no') > -1 || meta.content.indexOf('initial-scale=1.0; maximum-scale=1.0') > -1) {
      score = 0;
      offending.push(meta.content);
    }
  });

  return {
    id: 'neverSuppressZoom',
    title: 'Don\'t suppress pinch zoom',
    description: 'A key feature of mobile browsing is being able to zoom in to read content and out to locate content within a page. http://www.iheni.com/mobile-accessibility-tip-dont-suppress-pinch-zoom/',
    advice: score === 0 ? 'What! The page suppress zooming, you really shouldn\'t do that.' : '',
    score: score,
    weight: 8,
    offending: offending,
    tags: ['accessibility']
  };

})(util);
<|endoftext|>


<commit_before>var jsface = require('jsface'),
    Helpers = require('./Helpers'),
    uuid = require('node-uuid'),
    _lod = require("lodash"),
    Globals = require("./Globals"),
    _und = require('underscore');

/**
 * @name VariableProcessor
 * @namespace
 * @classdesc Helper singleton class that does the variable and environment processing for newman
 */
var VariableProcessor = jsface.Class({
    $singleton: true,

    // TODO: Make {{}} configurable
    $statics: {
        ENV_REGEX: /\{\{([a-z0-9\-._\s]+)\}\}/ig,

        FUNCTION_REGEX: /\{\{\$([a-z0-9\-._]+)\}\}/ig
    },

    // placeholders to define function variables
    getFunctionVariables: {
        guid: function () {
        },
        timestamp: _und.now(),
        randomInt: _und.random(0, 1000)
    },

    _resetFunctionVariables: function () {
        var guid = uuid.v4();
        var timestamp = _und.now();
        var randomInt = _und.random(0, 1000);
        this.getFunctionVariables.guid = guid;
        this.getFunctionVariables.randomInt = randomInt;
        this.getFunctionVariables.timestamp = timestamp;
    },

    // updates request url by the replacing it with pathVariables
    _processPathVariable: function (request) {
        if (typeof request.pathVariables !== undefined) {
            var sourceObject = request.pathVariables;
            // for each path variable - do a simple find replace
            _und.each(_und.keys(sourceObject), function (key) {
                var s = request.url;
                request.url = s.replace(":" + key, sourceObject[key]);
            }, this);
        }
    },

    // updates request properties by the replacing them with function variables
    _processFunctionVariable: function (request) {
        var properties = ["url", "headers", "form", "data", "helperAttributes"];

        request.transformed = request.transformed || {};

        _und.each(properties, function (prop) {
            // check if the prop exists
            if (request[prop] !== undefined) {
                if (typeof request[prop] === "string") {
                    // if string, use directly
                    request.transformed[prop] = this._findReplace(request[prop], this.getFunctionVariables, this.FUNCTION_REGEX);
                } else {
                    // if not string, stringify it
                    // findReplace, unstringify it and set it
                    var jsonifiedProp = JSON.stringify(request[prop]);
                    var parsedJsonProp = JSON.parse(this._findReplace(jsonifiedProp, this.getFunctionVariables, this.FUNCTION_REGEX));
                    request.transformed[prop] = parsedJsonProp;
                }
            }
        }, this);
    },

    // replaces a string based on keys in the sourceObject as matched by a regex. Supports recursive replacement
    // usage: _findReplace("{{url}}/blog/posts/{{id}}", {url: "http://localhost", id: 2}, this.ENV_REGEX)
    // Note: The regex provided should capture the key to be replaced (use parenthesis)
    _findReplace: function (stringSource, sourceObject, REGEX, recurseCount) {
        if (typeof recurseCount === "undefined") {
            recurseCount = 1;
        }
        //console.log("Limit: " + Globals.recurseLimit);
        if (recurseCount > Globals.recurseLimit) {
            return stringSource;
        }

        function getKey(match, key) {
            var fromSource = sourceObject[key];
            if (typeof fromSource === "undefined") {
                return "{{" + key + "}}";
            }
            return fromSource;
        }

        var oldString = stringSource + "";
        stringSource = stringSource.replace(REGEX, getKey);

        if (oldString === stringSource) {
            return stringSource;
        }

        if (stringSource.match(REGEX)) {
            return this._findReplace(stringSource, sourceObject, REGEX, recurseCount + 1);
        }
        return stringSource;
    },

    // transforms the request as per the environment json data passed
    _processEnvVariable: function (request, envJson) {
        var kvpairs = envJson.values;
        var oldThis = this,
            toReplace;

        request.transformed = request.transformed || {};

        var properties = ["url", "headers", "form", "data", "helperAttributes"];

        var pairObject = Helpers.transformFromKeyValue(kvpairs);
        _und.each(properties, function (prop) {
            // check if the prop exists
            if (request[prop] !== undefined) {

                // If already processed by function vars
                toReplace = request.transformed[prop] || request[prop];

                if (typeof request[prop] === "string") {
                    request.transformed[prop] = this._findReplace(toReplace, pairObject, this.ENV_REGEX);
                } else {
                    //The old option of stringify+replace+parse was removed.
                    request.transformed[prop] = _lod.cloneDeep(toReplace);
                    oldThis._traverseJson(request.transformed[prop], oldThis._processNode, pairObject);
                }
            }
        }, this);
        return true;
    },

    _processNode: function (key, value, pairObject) {
        if (typeof key === "string") {
            key = this._findReplace(key, pairObject, this.ENV_REGEX);
        }
        if (typeof value === "string") {
            value = this._findReplace(value, pairObject, this.ENV_REGEX);
        }
        return {
            "key": key,
            "value": value
        };
    },

    _traverseJson: function (o, func, pairObject) {
        if(!o) {
            return;
        }
        if (o._visited) {
            //To prevent traversing cycling objects
            return;
        }
        o._visited = true;
        for (var i in o) {
            var newData = func.apply(this, [i, o[i], pairObject]);
            delete o[i];
            o[newData.key] = newData.value;
            i = newData.key;
            if (o[i] !== null && typeof(o[i]) === "object") {
                //going on step down in the object tree!!
                this._traverseJson(o[i], func, pairObject);
            }
        }
        delete o._visited;
    },

    /**
     * Modifies request by processing all the variables
     * @param {RequestModel} request
     * @memberof VariableProcessor
     * @param {JSON} options passed to Newman runner
     */
    processRequestVariables: function (request, options) {
        this._resetFunctionVariables();
        this._processPathVariable(request);
        this._processFunctionVariable(request);
        this._processEnvVariable(request, options.envJson);
    }
});

module.exports = VariableProcessor;
<commit_msg>fixed #406<commit_after>var jsface = require('jsface'),
    Helpers = require('./Helpers'),
    uuid = require('node-uuid'),
    _lod = require("lodash"),
    Globals = require("./Globals"),
    _und = require('underscore');

/**
 * @name VariableProcessor
 * @namespace
 * @classdesc Helper singleton class that does the variable and environment processing for newman
 */
var VariableProcessor = jsface.Class({
    $singleton: true,

    // TODO: Make {{}} configurable
    $statics: {
        ENV_REGEX: /\{\{([a-z0-9\-._\s]+)\}\}/ig,

        FUNCTION_REGEX: /\{\{\$([a-z0-9\-._]+)\}\}/ig
    },

    // placeholders to define function variables
    getFunctionVariables: {
        guid: function () {
        },
        timestamp: _und.now(),
        randomInt: _und.random(0, 1000)
    },

    _resetFunctionVariables: function () {
        var guid = uuid.v4();
        var timestamp = Date.now();
        var randomInt = _und.random(0, 1000);
        this.getFunctionVariables.guid = guid;
        this.getFunctionVariables.randomInt = randomInt;
        this.getFunctionVariables.timestamp = timestamp;
    },

    // updates request url by the replacing it with pathVariables
    _processPathVariable: function (request) {
        if (typeof request.pathVariables !== undefined) {
            var sourceObject = request.pathVariables;
            // for each path variable - do a simple find replace
            _und.each(_und.keys(sourceObject), function (key) {
                var s = request.url;
                request.url = s.replace(":" + key, sourceObject[key]);
            }, this);
        }
    },

    // updates request properties by the replacing them with function variables
    _processFunctionVariable: function (request) {
        var properties = ["url", "headers", "form", "data", "helperAttributes"];

        request.transformed = request.transformed || {};

        _und.each(properties, function (prop) {
            // check if the prop exists
            if (request[prop] !== undefined) {
                if (typeof request[prop] === "string") {
                    // if string, use directly
                    request.transformed[prop] = this._findReplace(request[prop], this.getFunctionVariables, this.FUNCTION_REGEX);
                } else {
                    // if not string, stringify it
                    // findReplace, unstringify it and set it
                    var jsonifiedProp = JSON.stringify(request[prop]);
                    var parsedJsonProp = JSON.parse(this._findReplace(jsonifiedProp, this.getFunctionVariables, this.FUNCTION_REGEX));
                    request.transformed[prop] = parsedJsonProp;
                }
            }
        }, this);
    },

    // replaces a string based on keys in the sourceObject as matched by a regex. Supports recursive replacement
    // usage: _findReplace("{{url}}/blog/posts/{{id}}", {url: "http://localhost", id: 2}, this.ENV_REGEX)
    // Note: The regex provided should capture the key to be replaced (use parenthesis)
    _findReplace: function (stringSource, sourceObject, REGEX, recurseCount) {
        if (typeof recurseCount === "undefined") {
            recurseCount = 1;
        }
        //console.log("Limit: " + Globals.recurseLimit);
        if (recurseCount > Globals.recurseLimit) {
            return stringSource;
        }

        function getKey(match, key) {
            var fromSource = sourceObject[key];
            if (typeof fromSource === "undefined") {
                return "{{" + key + "}}";
            }
            return fromSource;
        }

        var oldString = stringSource + "";
        stringSource = stringSource.replace(REGEX, getKey);

        if (oldString === stringSource) {
            return stringSource;
        }

        if (stringSource.match(REGEX)) {
            return this._findReplace(stringSource, sourceObject, REGEX, recurseCount + 1);
        }
        return stringSource;
    },

    // transforms the request as per the environment json data passed
    _processEnvVariable: function (request, envJson) {
        var kvpairs = envJson.values;
        var oldThis = this,
            toReplace;

        request.transformed = request.transformed || {};

        var properties = ["url", "headers", "form", "data", "helperAttributes"];

        var pairObject = Helpers.transformFromKeyValue(kvpairs);
        _und.each(properties, function (prop) {
            // check if the prop exists
            if (request[prop] !== undefined) {

                // If already processed by function vars
                toReplace = request.transformed[prop] || request[prop];

                if (typeof request[prop] === "string") {
                    request.transformed[prop] = this._findReplace(toReplace, pairObject, this.ENV_REGEX);
                } else {
                    //The old option of stringify+replace+parse was removed.
                    request.transformed[prop] = _lod.cloneDeep(toReplace);
                    oldThis._traverseJson(request.transformed[prop], oldThis._processNode, pairObject);
                }
            }
        }, this);
        return true;
    },

    _processNode: function (key, value, pairObject) {
        if (typeof key === "string") {
            key = this._findReplace(key, pairObject, this.ENV_REGEX);
        }
        if (typeof value === "string") {
            value = this._findReplace(value, pairObject, this.ENV_REGEX);
        }
        return {
            "key": key,
            "value": value
        };
    },

    _traverseJson: function (o, func, pairObject) {
        if(!o) {
            return;
        }
        if (o._visited) {
            //To prevent traversing cycling objects
            return;
        }
        o._visited = true;
        for (var i in o) {
            var newData = func.apply(this, [i, o[i], pairObject]);
            delete o[i];
            o[newData.key] = newData.value;
            i = newData.key;
            if (o[i] !== null && typeof(o[i]) === "object") {
                //going on step down in the object tree!!
                this._traverseJson(o[i], func, pairObject);
            }
        }
        delete o._visited;
    },

    /**
     * Modifies request by processing all the variables
     * @param {RequestModel} request
     * @memberof VariableProcessor
     * @param {JSON} options passed to Newman runner
     */
    processRequestVariables: function (request, options) {
        this._resetFunctionVariables();
        this._processPathVariable(request);
        this._processFunctionVariable(request);
        this._processEnvVariable(request, options.envJson);
    }
});

module.exports = VariableProcessor;
<|endoftext|>


<commit_before>/*global MainGame*/
var UnitAI = {
	takeTurn: function(unit) {
		//console.log(MainGame.global.turn, unit.name, unit.currentIndex);
		if (unit.target === null) {
			console.log(unit.number+" @ "+unit.currentIndex+" - selecting target");
			unit.target = UnitAI.findTarget(unit);
		}

		console.log(unit.number+" @ "+unit.currentIndex+" - choosing a move");
		var newMoveIndex = UnitAI.chooseMove(unit);
		console.log(unit.number+" @ "+unit.currentIndex+" - new tile: "+newMoveIndex);
		unit.move(newMoveIndex);
		if (unit.isAttacking)
			UnitAI.attackTarget(unit);
		console.log(unit.number+" @ "+unit.currentIndex+" - done\n");
		console.log("");
	},

	findTarget: function(unit) {
		if (unit.type === Unit.Riot) {
			if(unit.currentIndex === unit.origin && MainGame.board.at(unit.currentIndex).getBuilding().name !== 'rubble'){
				console.log(unit.number+" @ "+unit.currentIndex+" - targeting origin");
				return unit.origin;
			} else {
				console.log(unit.number+" @ "+unit.currentIndex+" - targeting palace");
				return MainGame.board.findBuilding('palace',null,null,null)[0];
			}
		} else if (unit.type === Unit.Army) { // Should never call findTarget with a homeless group, but just to be sure
			var riotIndecies = MainGame.board.findUnits(Unit.Riot);
			if (riotIndecies.length > 0) {
				var palaceIndex = MainGame.board.findBuilding('palace',null,null,null)[0];
				var armyDistance = MainGame.board.distanceOf(palaceIndex, unit.currentIndex);
				var minDistance = null;
				var minIndex = null;
				for (var i = 0; i < riotIndecies.length; ++i) {
					var totalDistance = MainGame.board.distanceOf(palaceIndex,riotIndecies[i]) + armyDistance;
					if (!minDistance) {
						minDistance = totalDistance;
						minIndex = riotIndecies[i];
					} else if (totalDistance < minDistance) {
						minDistance = totalDistance;
						minIndex = riotIndecies[i];
					}
				}

				console.log(unit.number+" @ "+unit.currentIndex+" - selecting Riot @ "+minIndex);
				return MainGame.board.at(minIndex).getUnit();
			} else {
				console.log(unit.number+" @ "+unit.currentIndex+" - no target found");
				return null;
			}
		}
	},

	// Determines what index to move the unit to. Returns either a tile index adjacent to the current index, or null if no move is desired
	chooseMove: function(unit) {
		var targetIndex = null;
		if (unit.type === Unit.Army) {
			if (unit.target !== null) {
				console.log(unit.number+" @ "+unit.currentIndex+" - has a target");
				targetIndex = unit.target;
			} else {
				// If an Army unit does not have a target, then it will patrol roads
				// If it is not on a road, it will move toward the army base until it finds a road
				if (MainGame.board.at(unit.currentIndex).getBuilding().name === "road") {
					var adjacent = MainGame.board.allAdjacent(unit.currentIndex,1);
					var roads = [];
					for(var i=0; i<adjacent.length; ++i){
						if(MainGame.board.at(adjacent[i]).getBuilding().name)
							roads.push(adjacent[i]);
					}
					if(roads.length>0){
						console.log(unit.number+" @ "+unit.currentIndex+" - patrolling the road");
						return roads[Math.floor(Math.random()*roads.length)];
					}
					else{
						console.log(unit.number+" @ "+unit.currentIndex+" - no connecting roads, so targeting origin");
						targetIndex = unit.origin;
					}
				}else{
					console.log(unit.number+" @ "+unit.currentIndex+" - no connecting roads, so targeting origin");
					targetIndex = unit.origin;
				}
			}
		} else if (unit.type === Unit.Riot) {
			if (unit.currentIndex === unit.target) {
				console.log(unit.number+" @ "+unit.currentIndex+" - standing on target, so not moving");
				unit.isAttacking = true;
				console.log(unit.number+" @ "+unit.currentIndex+" - attack!");
				return null;
			}
			console.log(unit.number+" @ "+unit.currentIndex+" - has a target");
			targetIndex = unit.target;
		}

		var currentWeight = MainGame.board.distanceOf(unit.currentIndex, targetIndex);
		var adjacentTiles = MainGame.board.allAdjacent(unit.currentIndex, 1);
		var choices = [];
		for(var i = 0; i < adjacentTiles.length; ++i) {
			if(adjacentTiles[i])
			// Checking to see if the adjacent hex is the unit's target
			// if so, then the unit will immediately attack it
			if (adjacentTiles[i] === targetIndex) {
				console.log(unit.number+" @ "+unit.currentIndex+" - target is adjacent");
				if (unit.type === Unit.Army && unit.target != null) {
					unit.isAttacking = true;
					console.log(unit.number+" @ "+unit.currentIndex+" - attack!");
					return null;
				} else {
					console.log(unit.number+" @ "+unit.currentIndex+" - move to target");
					if(unit.type === Unit.Riot){
						console.log(unit.number+" @ "+unit.currentIndex+" - attack!");
						unit.isAttacking = true;
					}
					return adjacentTiles[i];
				}
			}
			choices.push({tileIndex:adjacentTiles[i],weight:0,building:""});
			var tile = MainGame.board.at(adjacentTiles[i]);
			if(tile.hasBuilding())
				choices[i].building = tile.getBuilding().name;
			if(tile.hasUnit()){
				choices[i].weight = 999;
				var adjacentUnit = tile.getUnit();
				if(unit.type === Unit.Riot && adjacentUnit.type === Unit.Riot && unit.health <= adjacentUnit.health && choices[i].weight < currentWeight){
					console.log(unit.number+" @ "+unit.currentIndex+" - merging with adjacent Riot");
					UnitAI.mergeUnits(adjacentUnit,unit);
					console.log(unit.number+" @ "+unit.currentIndex+" - remaining people stand still");
					return null;
				}
			}else if(tile.getTerrainType() !== "water" && tile.getTerrainType() !== "mountain"){
				choices[i].weight = MainGame.board.distanceOf(adjacentTiles[i],targetIndex)*100;
				if(choices[i].building === "road" || choices[i].building === "rubble")
					choices[i].weight -= Math.floor(Math.random()*50);
				else if(unit.type === Unit.Riot && choices[i].building !== "" && choices[i].weight <= currentWeight)
					choices[i].weight = Math.floor(Math.random()*choices[i].weight);
				else
					choices[i].weight += Math.floor(Math.random()*50);
			}
			console.log(choices[i].tileIndex+" "+choices[i].weight+" "+choices[i].building+" "+tile.hasUnit());
		}

		// sort choices by their weighted values
		choices.sort(function(a,b){return a.weight-b.weight;});

		// targeting nearby building
		if (unit.type === Unit.Riot) {
			if(choices[0].building !== "road" && choices[0].building !== "rubble" && choices[0].building !== ""){
				console.log(unit.number+" @ "+unit.currentIndex+" - changed target and attacking "+choices[0].building);
				unit.isAttacking = true;
				unit.target = choices[0].tileIndex;
			}
		}

		console.log(unit.number+" @ "+unit.currentIndex+" - moving to "+choices[0].tileIndex);
		return choices[0].tileIndex;
	},

	attackTarget: function(unit) {
		if (unit.type === Unit.Riot) {
			var targetTile = MainGame.board.at(unit.target);
			console.log(unit.number+" @ "+unit.currentIndex+" - health: "+unit.health+" vs. targetIntegrity: "+targetTile.getBuilding().integrity);

			// If the building is about to die...
			if(unit.health >= targetTile.getBuilding().integrity){
				unit.target = null;
				unit.isAttacking = false;
			}
			targetTile.damageBuilding(unit.health);
			console.log(unit.number+" @ "+unit.currentIndex+" - targetNewIntegrity: "+targetTile.getBuilding().integrity);
		} else if (unit.type === Unit.Army) {
			var targetUnit = unit.target;
			console.log(unit.number+" @ "+unit.currentIndex+" - health: "+unit.health+" vs. targetHealth: "+targetUnit.health);

			// If the targeted unit is about to die...
			if(unit.health >= targetUnit.health){
				unit.target = null;
				unit.isAttacking = false;
			}
			targetUnit.takeDamage(unit.health);
			console.log(unit.number+" @ "+unit.currentIndex+" - targetNewHealth: "+targetUnit.health);
		}
	},

	mergeUnits: function(unit1, unit2) {
		var transfer = Math.min(unit2.health, Unit.maxSize - unit1.health);
		console.log(unit2.number+" @ "+unit2.currentIndex+" - newhealth: "+(unit2.health-transfer));
		console.log(unit1.number+" @ "+unit1.currentIndex+" - newhealth: "+(unit1.health-transfer));
		unit1.addPeople(transfer);
		unit2.subtractPeople(transfer);
	}
};<commit_msg>removed console logs from UnitAI<commit_after>/*global MainGame*/
var UnitAI = {
	takeTurn: function(unit) {
		//console.log(MainGame.global.turn, unit.name, unit.currentIndex);
		if (unit.target === null) {
			unit.target = UnitAI.findTarget(unit);
		}

		var newMoveIndex = UnitAI.chooseMove(unit);
		unit.move(newMoveIndex);
		if (unit.isAttacking)
			UnitAI.attackTarget(unit);
		console.log("");
	},

	findTarget: function(unit) {
		if (unit.type === Unit.Riot) {
			if(unit.currentIndex === unit.origin && MainGame.board.at(unit.currentIndex).getBuilding().name !== 'rubble'){
				return unit.origin;
			} else {
				return MainGame.board.findBuilding('palace',null,null,null)[0];
			}
		} else if (unit.type === Unit.Army) { // Should never call findTarget with a homeless group, but just to be sure
			var riotIndecies = MainGame.board.findUnits(Unit.Riot);
			if (riotIndecies.length > 0) {
				var palaceIndex = MainGame.board.findBuilding('palace',null,null,null)[0];
				var armyDistance = MainGame.board.distanceOf(palaceIndex, unit.currentIndex);
				var minDistance = null;
				var minIndex = null;
				for (var i = 0; i < riotIndecies.length; ++i) {
					var totalDistance = MainGame.board.distanceOf(palaceIndex,riotIndecies[i]) + armyDistance;
					if (!minDistance) {
						minDistance = totalDistance;
						minIndex = riotIndecies[i];
					} else if (totalDistance < minDistance) {
						minDistance = totalDistance;
						minIndex = riotIndecies[i];
					}
				}

				return MainGame.board.at(minIndex).getUnit();
			} else {
				return null;
			}
		}
	},

	// Determines what index to move the unit to. Returns either a tile index adjacent to the current index, or null if no move is desired
	chooseMove: function(unit) {
		var targetIndex = null;
		if (unit.type === Unit.Army) {
			if (unit.target !== null) {
				targetIndex = unit.target;
			} else {
				// If an Army unit does not have a target, then it will patrol roads
				// If it is not on a road, it will move toward the army base until it finds a road
				if (MainGame.board.at(unit.currentIndex).getBuilding().name === "road") {
					var adjacent = MainGame.board.allAdjacent(unit.currentIndex,1);
					var roads = [];
					for(var i=0; i<adjacent.length; ++i){
						if(MainGame.board.at(adjacent[i]).getBuilding().name)
							roads.push(adjacent[i]);
					}
					if(roads.length>0){
						return roads[Math.floor(Math.random()*roads.length)];
					}
					else{
						targetIndex = unit.origin;
					}
				}else{
					targetIndex = unit.origin;
				}
			}
		} else if (unit.type === Unit.Riot) {
			if (unit.currentIndex === unit.target) {
				unit.isAttacking = true;
				return null;
			}
			targetIndex = unit.target;
		}

		var currentWeight = MainGame.board.distanceOf(unit.currentIndex, targetIndex);
		var adjacentTiles = MainGame.board.allAdjacent(unit.currentIndex, 1);
		var choices = [];
		for(var i = 0; i < adjacentTiles.length; ++i) {
			if(adjacentTiles[i])
			// Checking to see if the adjacent hex is the unit's target
			// if so, then the unit will immediately attack it
			if (adjacentTiles[i] === targetIndex) {
				if (unit.type === Unit.Army && unit.target != null) {
					unit.isAttacking = true;
					return null;
				} else {
					if(unit.type === Unit.Riot){
						unit.isAttacking = true;
					}
					return adjacentTiles[i];
				}
			}
			choices.push({tileIndex:adjacentTiles[i],weight:0,building:""});
			var tile = MainGame.board.at(adjacentTiles[i]);
			if(tile.hasBuilding())
				choices[i].building = tile.getBuilding().name;
			if(tile.hasUnit()){
				choices[i].weight = 999;
				var adjacentUnit = tile.getUnit();
				if(unit.type === Unit.Riot && adjacentUnit.type === Unit.Riot && unit.health <= adjacentUnit.health && choices[i].weight < currentWeight){
					UnitAI.mergeUnits(adjacentUnit,unit);
					return null;
				}
			}else if(tile.getTerrainType() !== "water" && tile.getTerrainType() !== "mountain"){
				choices[i].weight = MainGame.board.distanceOf(adjacentTiles[i],targetIndex)*100;
				if(choices[i].building === "road" || choices[i].building === "rubble")
					choices[i].weight -= Math.floor(Math.random()*50);
				else if(unit.type === Unit.Riot && choices[i].building !== "" && choices[i].weight <= currentWeight)
					choices[i].weight = Math.floor(Math.random()*choices[i].weight);
				else
					choices[i].weight += Math.floor(Math.random()*50);
			}
		}

		// sort choices by their weighted values
		choices.sort(function(a,b){return a.weight-b.weight;});

		// targeting nearby building
		if (unit.type === Unit.Riot) {
			if(choices[0].building !== "road" && choices[0].building !== "rubble" && choices[0].building !== ""){
				unit.isAttacking = true;
				unit.target = choices[0].tileIndex;
			}
		}

		return choices[0].tileIndex;
	},

	attackTarget: function(unit) {
		if (unit.type === Unit.Riot) {
			var targetTile = MainGame.board.at(unit.target);

			// If the building is about to die...
			if(unit.health >= targetTile.getBuilding().integrity){
				unit.target = null;
				unit.isAttacking = false;
			}
			targetTile.damageBuilding(unit.health);
		} else if (unit.type === Unit.Army) {
			var targetUnit = unit.target;

			// If the targeted unit is about to die...
			if(unit.health >= targetUnit.health){
				unit.target = null;
				unit.isAttacking = false;
			}
			targetUnit.takeDamage(unit.health);
		}
	},

	mergeUnits: function(unit1, unit2) {
		var transfer = Math.min(unit2.health, Unit.maxSize - unit1.health);
		unit1.addPeople(transfer);
		unit2.subtractPeople(transfer);
	}
};<|endoftext|>