<commit_before>var path = require('path'); // eslint-disable-line no-var
var ExtractTextPlugin = require('extract-text-webpack-plugin'); // eslint-disable-line no-var

module.exports = {
  resolve: {
    alias: {
      'draft-js-plugins-editor': path.join(__dirname, '..', 'draft-js-plugins-editor', 'src'),
      'draft-js-hashtag-plugin': path.join(__dirname, '..', 'draft-js-hashtag-plugin', 'src'),
      'draft-js-linkify-plugin': path.join(__dirname, '..', 'draft-js-linkify-plugin', 'src'),
      'draft-js-anchor-plugin': path.join(__dirname, '..', 'draft-js-anchor-plugin', 'src'),
      'draft-js-mention-plugin': path.join(__dirname, '..', 'draft-js-mention-plugin', 'src'),
      'draft-js-sticker-plugin': path.join(__dirname, '..', 'draft-js-sticker-plugin', 'src'),
      'draft-js-undo-plugin': path.join(__dirname, '..', 'draft-js-undo-plugin', 'src'),
      'draft-js-emoji-plugin': path.join(__dirname, '..', 'draft-js-emoji-plugin', 'src'),
      'draft-js-counter-plugin': path.join(__dirname, '..', 'draft-js-counter-plugin', 'src'),
      'draft-js-drag-n-drop-plugin': path.join(__dirname, '..', 'draft-js-drag-n-drop-plugin', 'src'),
      'draft-js-drag-n-drop-upload-plugin': path.join(__dirname, '..', 'draft-js-drag-n-drop-upload-plugin', 'src'),
      'draft-js-inline-toolbar-plugin': path.join(__dirname, '..', 'draft-js-inline-toolbar-plugin', 'src'),
      'draft-js-side-toolbar-plugin': path.join(__dirname, '..', 'draft-js-side-toolbar-plugin', 'src'),
      'draft-js-focus-plugin': path.join(__dirname, '..', 'draft-js-focus-plugin', 'src'),
      'draft-js-alignment-plugin': path.join(__dirname, '..', 'draft-js-alignment-plugin', 'src'),
      'draft-js-image-plugin': path.join(__dirname, '..', 'draft-js-image-plugin', 'src'),
      'draft-js-resizeable-plugin': path.join(__dirname, '..', 'draft-js-resizeable-plugin', 'src'),
      'draft-js-buttons': path.join(__dirname, '..', 'draft-js-buttons', 'src'),
      'draft-js-video-plugin': path.join(__dirname, '..', 'draft-js-video-plugin', 'src'),
      react: path.join(__dirname, 'node_modules', 'react'),
    },
    extensions: ['.js'],
  },
  module: {
    rules: [
      {
        // match all js files except example.js
        test: /^(?!.*example\.js$).*\.js$/,
        use: ['babel-loader'],
        exclude: /node_modules/,
      }, {
        test: /\.js$/,
        loader: ['babel-loader'],
        include: [
          path.join(__dirname, '..', 'draft-js-plugins-editor', 'src'),
          path.join(__dirname, '..', 'draft-js-hashtag-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-linkify-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-anchor-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-mention-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-sticker-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-undo-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-emoji-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-drag-n-drop-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-drag-n-drop-upload-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-inline-toolbar-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-side-toolbar-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-counter-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-focus-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-alignment-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-image-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-resizeable-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-buttons', 'src'),
          path.join(__dirname, '..', 'draft-js-video-plugin', 'src'),
        ],
      }, {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]!postcss-loader' }),
        include: [
          path.join(__dirname, '..', 'draft-js-plugins-editor', 'src'),
          path.join(__dirname, '..', 'draft-js-hashtag-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-linkify-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-anchor-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-mention-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-sticker-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-undo-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-emoji-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-drag-n-drop-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-drag-n-drop-upload-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-inline-toolbar-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-side-toolbar-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-counter-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-focus-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-alignment-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-image-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-resizeable-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-buttons', 'src'),
          path.join(__dirname, '..', 'draft-js-video-plugin', 'src'),
          path.join(__dirname, 'client/components'),
        ],
      }, {
        test: /\.(scss|sass)$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]!postcss-loader!sass-loader',
        }),
        include: [
          path.join(__dirname, '..', 'draft-js-emoji-plugin', 'src'),
        ],
      }, {
        test: /prism\.css$/,
        loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }),
        include: [
          path.join(__dirname, 'node_modules/prismjs/themes/'),
        ],
      }, {
        test: /\.(png|jpg|gif|ico)$/,
        use: [
          { loader: 'file-loader', options: { name: '[name].[ext]' } },
        ],
      },
    ],
  },
};
<commit_msg>include compilation of url-regex<commit_after>var path = require('path'); // eslint-disable-line no-var
var ExtractTextPlugin = require('extract-text-webpack-plugin'); // eslint-disable-line no-var

module.exports = {
  resolve: {
    alias: {
      'draft-js-plugins-editor': path.join(__dirname, '..', 'draft-js-plugins-editor', 'src'),
      'draft-js-hashtag-plugin': path.join(__dirname, '..', 'draft-js-hashtag-plugin', 'src'),
      'draft-js-linkify-plugin': path.join(__dirname, '..', 'draft-js-linkify-plugin', 'src'),
      'draft-js-anchor-plugin': path.join(__dirname, '..', 'draft-js-anchor-plugin', 'src'),
      'draft-js-mention-plugin': path.join(__dirname, '..', 'draft-js-mention-plugin', 'src'),
      'draft-js-sticker-plugin': path.join(__dirname, '..', 'draft-js-sticker-plugin', 'src'),
      'draft-js-undo-plugin': path.join(__dirname, '..', 'draft-js-undo-plugin', 'src'),
      'draft-js-emoji-plugin': path.join(__dirname, '..', 'draft-js-emoji-plugin', 'src'),
      'draft-js-counter-plugin': path.join(__dirname, '..', 'draft-js-counter-plugin', 'src'),
      'draft-js-drag-n-drop-plugin': path.join(__dirname, '..', 'draft-js-drag-n-drop-plugin', 'src'),
      'draft-js-drag-n-drop-upload-plugin': path.join(__dirname, '..', 'draft-js-drag-n-drop-upload-plugin', 'src'),
      'draft-js-inline-toolbar-plugin': path.join(__dirname, '..', 'draft-js-inline-toolbar-plugin', 'src'),
      'draft-js-side-toolbar-plugin': path.join(__dirname, '..', 'draft-js-side-toolbar-plugin', 'src'),
      'draft-js-focus-plugin': path.join(__dirname, '..', 'draft-js-focus-plugin', 'src'),
      'draft-js-alignment-plugin': path.join(__dirname, '..', 'draft-js-alignment-plugin', 'src'),
      'draft-js-image-plugin': path.join(__dirname, '..', 'draft-js-image-plugin', 'src'),
      'draft-js-resizeable-plugin': path.join(__dirname, '..', 'draft-js-resizeable-plugin', 'src'),
      'draft-js-buttons': path.join(__dirname, '..', 'draft-js-buttons', 'src'),
      'draft-js-video-plugin': path.join(__dirname, '..', 'draft-js-video-plugin', 'src'),
      react: path.join(__dirname, 'node_modules', 'react'),
    },
    extensions: ['.js'],
  },
  module: {
    rules: [
      {
        // match all js files except example.js
        test: /^(?!.*example\.js$).*\.js$/,
        use: ['babel-loader'],
        exclude: /node_modules\/(?!url-regex)/,
      }, {
        test: /\.js$/,
        loader: ['babel-loader'],
        include: [
          path.join(__dirname, '..', 'draft-js-plugins-editor', 'src'),
          path.join(__dirname, '..', 'draft-js-hashtag-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-linkify-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-anchor-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-mention-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-sticker-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-undo-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-emoji-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-drag-n-drop-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-drag-n-drop-upload-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-inline-toolbar-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-side-toolbar-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-counter-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-focus-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-alignment-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-image-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-resizeable-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-buttons', 'src'),
          path.join(__dirname, '..', 'draft-js-video-plugin', 'src'),
        ],
      }, {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]!postcss-loader' }),
        include: [
          path.join(__dirname, '..', 'draft-js-plugins-editor', 'src'),
          path.join(__dirname, '..', 'draft-js-hashtag-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-linkify-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-anchor-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-mention-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-sticker-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-undo-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-emoji-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-drag-n-drop-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-drag-n-drop-upload-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-inline-toolbar-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-side-toolbar-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-counter-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-focus-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-alignment-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-image-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-resizeable-plugin', 'src'),
          path.join(__dirname, '..', 'draft-js-buttons', 'src'),
          path.join(__dirname, '..', 'draft-js-video-plugin', 'src'),
          path.join(__dirname, 'client/components'),
        ],
      }, {
        test: /\.(scss|sass)$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]!postcss-loader!sass-loader',
        }),
        include: [
          path.join(__dirname, '..', 'draft-js-emoji-plugin', 'src'),
        ],
      }, {
        test: /prism\.css$/,
        loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }),
        include: [
          path.join(__dirname, 'node_modules/prismjs/themes/'),
        ],
      }, {
        test: /\.(png|jpg|gif|ico)$/,
        use: [
          { loader: 'file-loader', options: { name: '[name].[ext]' } },
        ],
      },
    ],
  },
};
<|endoftext|>


<commit_before>export { Base };

/**
 *
 */
class Base {

  /**
   *
   */
  constructor(
    ObjectClass,
    pfnSetAsConstructor,
  ) {
  }

  /**
   *
   */
  get_or_create( ...RestArgs ) {
  }

  /**
   * @param {Object}
   */
  recycle( object ) {
  }

}
<commit_msg>Update ObjectPool.js<commit_after>export { Base };

/**
 * A pool for recycling (re-using) objects.
 *
 * It could be used to improve performance by reducing memory re-allocation.
 *
 */
class Base {

  /**
   * @param {Class} objectClass
   *   The class for all newly created objects.
   *
   * @param {function} pfnSetAsConstructor
   *   A function works as its constructor. Before .get_or_create_by() returns a recycled object, its .pfnSetAsConstructor() method
   * will be called to re-initilaize it.
   */
  constructor( objectClass, pfnSetAsConstructor ) {
    this.objectClass = objectClass;
    this.pfnSetAsConstructor = pfnSetAsConstructor;

    this.recycledObjects = new Set(); // Using set for handling object be recycled multiple times.
  }

  /**
   *
   * @return {object}
   *   An obeject which is an instance of this.ObjectClass. If it is newly created, all RestArgs will be passed into its constructor.
   * If it is re-used (i.e. from recycled) object, all RestArgs will be passed into its .pfnSetAsConstructor() method.
   */
  get_or_create_by( ...restArgs ) {
    let returnedObject;
    if ( this.recycledObjects.size > 0 ) {
      let values = this.recycledObjects.values();
      returnedObject = values.next().value; // Get the first object.
      this.pfnSetAsConstructor.apply( returnedObject, RestArgs );
    } else {
      returnedObject = new ( this.objectClass )( ...restArgs );
    }
    return returnedObject;
  }

  /**
   * @param {Object}
   *   The object (which should be an instance of this.ObjectClass) to be recycled.
   */
  recycle( objectToBeRecycled ) {
    this.recycledObjects.add( objectToBeRecycled );
  }

}
<|endoftext|>


<commit_before>var Class = li.require("libraries/ptclass"),
  Abstract = li.require("ui/Abstract"),
  Tabs;

/**
 * The Tabs component is a subclass of Abstract and consists of a tablist, tabs and tabpanels.
 * @class Tabs
 * @constructor
 * @extends Abstract
 * @param {HTMLElement} element The HTML element containing this component
 * @param {Object} settings Configuration properties for this instance
 */
  Tabs =  Class.create( Abstract,  ( function () {

  // RETURN METHODS OBJECT
  return {
    /**
     * PTClass constructor
     * @method initialize
     * @public
     * @param {Object} $super Pointer to superclass constructor
     * @param {Object} $element JQuery object for the element wrapped by the component
     * @param {Object} settings Configuration settings
     */
    initialize: function ( $super, $element, settings ) {

      // PRIVATE
      // Constants
      var SELECT_EVT = "select",

      // INSTANCE PROPERTIES

      /**
       * Instance of Tabs
       * @property Tabs
       * @type Object
       * @private
       */
      tabs = this,

      /**
       * Default configuration values
       * @property defaults
       * @type Object
       * @private
       * @final
       */
      defaults = {

        /**
         * A selector scoped to the $element that matches the tablist
         * @property tabList
         * @type String
         * @private
         * @final
         */
        tabList: '.tab-list',

        /**
         * A selector scoped to the $element that matches tabpanels
         * @property tabPanels
         * @type String
         * @private
         * @final
         */
        tabPanels: '.tab-panels'
      },

      /**
       * A JDOM reference to a tablist
       * @property $tabList
       * @type Object
       * @private
       */
      $tabList,

      /**
       * The collection of tab panels for tabs
       * @property $tabPanels
       * @type Object
       * @private
       */
      $tabPanels,

      /**
       * Initializes the tab component
       * @method tabInit
       * @param {Object} settings - Object literal containing settings which have been merged with default settings
       * @private
       * @return {Void}
       */
      tabInit = function(settings) {
        // Get references to tablist, tabpanels and the current tab
        $tabPanels = $($element.children( settings.tabPanels ));

        $tabList = $($element.children(settings.tabList));
      },

      /**
       * Handles the tab select.  Fires the "select" event to the tab panels and passes the selected element
       * @param {Event} event - Athena event
       * @param {Object} item - JQuery DOM element
       * @method selectTabHandler
       * @private
       * @return {Void}
       */
      selectTabHandler = function(event, item) {
        $tabPanels.trigger(SELECT_EVT, [item]);
      };

      // MIX THE DEFAULTS INTO THE SETTINGS VALUES
      _.defaults( settings, defaults );

      // Initialize a bunch of stuff for the tabs!
      tabInit(settings);

      // CALL THE PARENT'S CONSTRUCTOR
      $super( $element, settings );

      // Attach event listeners
      $tabList.on(SELECT_EVT, selectTabHandler);
    }
  };
}() ));

// EXPORT TO ATHENA FRAMEWORK
if ( typeof module !== 'undefined' && module.exports ) {
  module.exports = Tabs;
}
<commit_msg>a bit of Tabs cleaning<commit_after>var Class = li.require("libraries/ptclass"),
  Abstract = li.require("ui/Abstract"),
  Tabs;

/**
 * The Tabs component is a subclass of Abstract and consists of a tablist, tabs and tabpanels.
 * @class Tabs
 * @constructor
 * @extends Abstract
 * @param {HTMLElement} element The HTML element containing this component
 * @param {Object} settings Configuration properties for this instance
 */
Tabs =  Class.create( Abstract,  ( function () {

  // RETURN METHODS OBJECT
  return {
    /**
     * PTClass constructor
     * @method initialize
     * @public
     * @param {Object} $super Pointer to superclass constructor
     * @param {Object} $element JQuery object for the element wrapped by the component
     * @param {Object} settings Configuration settings
     */
    initialize: function ( $super, $element, settings ) {

      // PRIVATE
      // Constants
      var SELECT_EVT = 'select',

      // INSTANCE PROPERTIES

      /**
       * Instance of Tabs
       * @property Tabs
       * @type Object
       * @private
       */
      Tabs = this,

      /**
       * Default configuration values
       * @property defaults
       * @type Object
       * @private
       * @final
       */
      defaults = {
        /**
         * A selector scoped to the $element that matches the tablist
         * @property tabList
         * @type String
         * @private
         * @final
         */
        tabList: '.tab-list',

        /**
         * A selector scoped to the $element that matches tabpanels
         * @property tabPanels
         * @type String
         * @private
         * @final
         */
        tabPanels: '.tab-panels'
      },

      /**
       * A JDOM reference to a tablist
       * @property $tabList
       * @type Object
       * @private
       */
      $tabList,

      /**
       * The collection of tab panels for tabs
       * @property $tabPanels
       * @type Object
       * @private
       */
      $tabPanels,

      /**
       * Initializes the tab component
       * @method tabInit
       * @param {Object} settings - Object literal containing settings which have been merged with default settings
       * @private
       * @return {Void}
       */
      tabInit = function( settings ) {
        // Get references to tablist, tabpanels and the current tab
        $tabPanels = $( $element.children( settings.tabPanels ) );
        $tabList = $( $element.children(settings.tabList) );
      },

      /**
       * Handles the tab select.  Fires the "select" event to the tab panels and passes the selected element
       * @param {Event} event - Athena event
       * @param {Object} item - JQuery DOM element
       * @method selectTabHandler
       * @private
       * @return {Void}
       */
      selectTabHandler = function( event, item ) {
        $tabPanels.trigger( SELECT_EVT, [item] );
      };

      // MIX THE DEFAULTS INTO THE SETTINGS VALUES
      _.defaults( settings, defaults );

      // Initialize a bunch of stuff for the tabs!
      tabInit(settings);

      // CALL THE PARENT'S CONSTRUCTOR
      $super( $element, settings );

      // Attach event listeners
      $tabList.on( SELECT_EVT, selectTabHandler );
    }
  };
}() ) );

// EXPORT TO ATHENA FRAMEWORK
if ( typeof module !== 'undefined' && module.exports ) {
  module.exports = Tabs;
}<|endoftext|>


<commit_before>import constant from "./constant";
import jiggle from "./jiggle";
import {map} from "d3-collection";

function index(d, i) {
  return i;
}

function find(nodeById, nodeId) {
  var node = nodeById.get(nodeId);
  if (!node) throw new Error("missing: " + nodeId);
  return node;
}

export default function(links) {
  var id = index,
      strength = defaultStrength,
      strengths,
      distance = constant(30),
      distances,
      nodes,
      count,
      bias,
      iterations = 1;

  if (links == null) links = [];

  function defaultStrength(link) {
    return 1 / Math.min(count[link.source.index], count[link.target.index]);
  }

  function force(alpha) {
    for (var k = 0, n = links.length; k < iterations; ++k) {
      for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {
        link = links[i], source = link.source, target = link.target;
        x = target.x + target.vx - source.x - source.vx || jiggle();
        y = target.y + target.vy - source.y - source.vy || jiggle();
        l = Math.sqrt(x * x + y * y);
        l = (l - distances[i]) / l * alpha * strengths[i];
        x *= l, y *= l;
        target.vx -= x * (b = bias[i]);
        target.vy -= y * b;
        source.vx += x * (b = 1 - b);
        source.vy += y * b;
      }
    }
  }

  function initialize() {
    if (!nodes) return;

    var i,
        n = nodes.length,
        m = links.length,
        nodeById = map(nodes, id),
        link;

    for (i = 0, count = new Array(n); i < n; ++i) {
      count[i] = 0;
    }

    for (i = 0; i < m; ++i) {
      link = links[i], link.index = i;
      if (typeof link.source !== "object") link.source = find(nodeById, link.source);
      if (typeof link.target !== "object") link.target = find(nodeById, link.target);
      ++count[link.source.index], ++count[link.target.index];
    }

    for (i = 0, bias = new Array(m); i < m; ++i) {
      link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
    }

    strengths = new Array(m), initializeStrength();
    distances = new Array(m), initializeDistance();
  }

  function initializeStrength() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      strengths[i] = +strength(links[i], i, links);
    }
  }

  function initializeDistance() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      distances[i] = +distance(links[i], i, links);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.links = function(_) {
    return arguments.length ? (links = _, initialize(), force) : links;
  };

  force.id = function(_) {
    return arguments.length ? (id = _, force) : id;
  };

  force.iterations = function(_) {
    return arguments.length ? (iterations = +_, force) : iterations;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength;
  };

  force.distance = function(_) {
    return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
  };

  return force;
}
<commit_msg>Fix #72 for d3.forceLink.<commit_after>import constant from "./constant";
import jiggle from "./jiggle";
import {map} from "d3-collection";

function index(d) {
  return d.index;
}

function find(nodeById, nodeId) {
  var node = nodeById.get(nodeId);
  if (!node) throw new Error("missing: " + nodeId);
  return node;
}

export default function(links) {
  var id = index,
      strength = defaultStrength,
      strengths,
      distance = constant(30),
      distances,
      nodes,
      count,
      bias,
      iterations = 1;

  if (links == null) links = [];

  function defaultStrength(link) {
    return 1 / Math.min(count[link.source.index], count[link.target.index]);
  }

  function force(alpha) {
    for (var k = 0, n = links.length; k < iterations; ++k) {
      for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {
        link = links[i], source = link.source, target = link.target;
        x = target.x + target.vx - source.x - source.vx || jiggle();
        y = target.y + target.vy - source.y - source.vy || jiggle();
        l = Math.sqrt(x * x + y * y);
        l = (l - distances[i]) / l * alpha * strengths[i];
        x *= l, y *= l;
        target.vx -= x * (b = bias[i]);
        target.vy -= y * b;
        source.vx += x * (b = 1 - b);
        source.vy += y * b;
      }
    }
  }

  function initialize() {
    if (!nodes) return;

    var i,
        n = nodes.length,
        m = links.length,
        nodeById = map(nodes, id),
        link;

    for (i = 0, count = new Array(n); i < m; ++i) {
      link = links[i], link.index = i;
      if (typeof link.source !== "object") link.source = find(nodeById, link.source);
      if (typeof link.target !== "object") link.target = find(nodeById, link.target);
      count[link.source.index] = (count[link.source.index] || 0) + 1;
      count[link.target.index] = (count[link.target.index] || 0) + 1;
    }

    for (i = 0, bias = new Array(m); i < m; ++i) {
      link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
    }

    strengths = new Array(m), initializeStrength();
    distances = new Array(m), initializeDistance();
  }

  function initializeStrength() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      strengths[i] = +strength(links[i], i, links);
    }
  }

  function initializeDistance() {
    if (!nodes) return;

    for (var i = 0, n = links.length; i < n; ++i) {
      distances[i] = +distance(links[i], i, links);
    }
  }

  force.initialize = function(_) {
    nodes = _;
    initialize();
  };

  force.links = function(_) {
    return arguments.length ? (links = _, initialize(), force) : links;
  };

  force.id = function(_) {
    return arguments.length ? (id = _, force) : id;
  };

  force.iterations = function(_) {
    return arguments.length ? (iterations = +_, force) : iterations;
  };

  force.strength = function(_) {
    return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength;
  };

  force.distance = function(_) {
    return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
  };

  return force;
}
<|endoftext|>


<commit_before>/** @babel */
/** @jsx etch.dom */
/* eslint-disable react/no-unknown-property */

import {CompositeDisposable} from 'atom'
import etch from 'etch'
import EtchComponent from '../etch-component'

export default class AboutStatusBar extends EtchComponent {
  constructor () {
    super()
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(atom.tooltips.add(this.element, {title: 'An update will be installed the next time Atom is relaunched.

Click the squirrel icon for more information.'}))
  }

  handleClick () {
    atom.workspace.open('atom://about')
  }

  render () {
    return (

    )
  }

  destroy () {
    super.destroy()
    this.subscriptions.dispose()
  }
}
<commit_msg>Fixing display for squirrel icon<commit_after>/** @babel */
/** @jsx etch.dom */
/* eslint-disable react/no-unknown-property */

import {CompositeDisposable} from 'atom'
import etch from 'etch'
import EtchComponent from '../etch-component'

export default class AboutStatusBar extends EtchComponent {
  constructor () {
    super()
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(atom.tooltips.add(this.element, {title: 'An update will be installed the next time Atom is relaunched.

Click the squirrel icon for more information.'}))
  }

  handleClick () {
    atom.workspace.open('atom://about')
  }

  render () {
    return (

    )
  }

  destroy () {
    super.destroy()
    this.subscriptions.dispose()
  }
}
<|endoftext|>


<commit_before>{
    "values": {
        "webmap": "",
        "title": "Crowdsource Polling",
        "titleIcon": "images/banner.png",
        "displayText": "Welcome to the Crowdsource Polling application
Use Crowdsource Polling to provide information and collect feedback on plans and issues around your community.

Search for a location or click an item in the list to get started.
",
        "featureLayer": {
            "id": "LandUseCasesVotesComments_8488",
            "fields": [{
                "id": "sortField",
                "fields": ["CASENAME"]
            }, {
                "id": "itemVotesField",
                "fields": ["VOTES"]
            }]
        },
        "ascendingSortOrder": "true",
        "showListViewFirst": "true",
        "showAllFeatures": "true",
        "commentNameField": "NAME",
        "allowFacebook": false,
        "facebookAppId": "",
        "allowGoogle": false,
        "googleplusClientId": "",
        "allowTwitter": true,
        "socialMediaDisclaimer": "Choose how you would like to sign in to this application. The name associated with your social media account will be added to any comments you post.",
        "showDisplayTextAsSplashScreen": false,
        "customUrlLayer": {
            "id": null,
            "fields": []
        },
        "customUrlParam": null,
        "color": "#206bdb",
        "headerBackgroundColor": "white",
        "bodyTextColor": "black",
        "bodyBackgroundColor": "white",
        "buttonTextColor": "#206bdb",
        "buttonBackgroundColor": "white"
    },
    "configurationSettings": [{
        "category": "General",
        "fields": [{
            "label": "Select a map",
            "fieldName": "webmap",
            "type": "webmap",
            "tooltip": "Map displayed in the application"
        }, {
            "label": "Application title",
            "fieldName": "title",
            "type": "string",
            "tooltip": "Application name (max 23 chars)"
        }, {
            "label": "Help widget text",
            "fieldName": "displayText",
            "type": "string",
            "tooltip": "Text displayed in the help window. HTML tags can be used for formatting.",
            "stringFieldOption": "richtext"
        }, {
            "label": "Display the help widget as a splash screen",
            "fieldName": "showDisplayTextAsSplashScreen",
            "type": "boolean"
        }, {
            "type": "subcategory",
            "label": "Sign in options"
        }, {
            "type": "paragraph",
            "value": "Allow your users to sign in to this application using their social media credentials. Comments submitted by authenticated users will have the commenters name automatically stored with their feedback."
        }, {
            "type": "paragraph",
            "value": "See the help for the steps to register your app with Facebook and Google+."
        }, {
            "label": "Field to store the name of authenticated commenters.",
            "fieldName": "commentNameField",
            "type": "string",
            "tooltip": "Field in a table with a geodatabase relationship to the selected feature layer for storing the name of authenticated commenters. Table must exist in map. Field name is case-sensitive."
        }, {
            "label": "Allow users to sign in using Twitter",
            "fieldName": "allowTwitter",
            "type": "boolean",
            "tooltip": "Enable to allow users to sign in using their Twitter credentials"
        }, {
            "label": "Allow users to sign in using Facebook",
            "tooltip": "Enable to allow users to sign in using their Facebook credentials",
            "type": "conditional",
            "fieldName": "allowFacebook",
            "condition": false,
            "items":[{
                "label": "Please register your app with Facebook and provide your Facebook AppId",
                "tooltip": "Facebook AppId",
                "type": "string",
                "fieldName": "facebookAppId"
            }]
        }, {
            "label": "Allow users to sign in using Google+",
            "tooltip": "Enable to allow users to sign in using their Google+ credentials",
            "type": "conditional",
            "fieldName": "allowGoogle",
            "condition":false,
            "items":[{
                "label": "Please register your app with Google+ and provide your Google+ Client ID",
                "tooltip": "Google+ ClientId",
                "type": "string",
                "fieldName": "googleplusClientId"
            }]
        }, {
            "label": "Sign in window text",
            "fieldName": "socialMediaDisclaimer",
            "type": "string",
            "placeholder": "",
            "tooltip": "Text to display in the Sign In window",
            "stringFieldOption": "richtext"
        }]
    }, {
        "category": "Theme",
        "fields": [{
            "label": "Header text color",
            "tooltip": "Set header text color",
            "type": "color",
            "sharedThemeProperty": "header.text",
            "fieldName": "color"
        }, {
            "label": "Header background color",
            "tooltip": "Set header background color",
            "type": "color",
            "sharedThemeProperty": "header.background",
            "fieldName": "headerBackgroundColor"
        }, {
            "label": "Body text color",
            "tooltip": "Set body text color",
            "type": "color",
            "sharedThemeProperty": "body.text",
            "fieldName": "bodyTextColor"
        }, {
            "label": "Body background color",
            "tooltip": "Set body background color",
            "type": "color",
            "sharedThemeProperty": "body.background",
            "fieldName": "bodyBackgroundColor"
        }, {
            "label": "Button text color",
            "tooltip": "Set button text color",
            "type": "color",
            "sharedThemeProperty": "button.text",
            "fieldName": "buttonTextColor"
        }, {
            "label": "Button background color",
            "tooltip": "Set button background color",
            "type": "color",
            "sharedThemeProperty": "button.background",
            "fieldName": "buttonBackgroundColor"
        }, {
            "label": "Application logo",
            "fieldName": "titleIcon",
            "type": "string",
            "sharedThemeProperty": "logo.small",
            "tooltip": "Icon in top left corner of application. Icon should be 48px high."
        }]
    }, {
        "category": "Options",
        "fields": [{
            "label": "Polling feature layer",
            "fieldName": "featureLayer",
            "type": "layerAndFieldSelector",
            "tooltip": "Point, line, or polygon layer containing the features to present in the application.",
            "layerOptions": {
                "supportedTypes": ["FeatureLayer"],
                "geometryTypes": ["esriGeometryPoint", "esriGeometryLine", "esriGeometryPolyline", "esriGeometryPolygon"]
            },
            "fields": [{
                "supportedTypes": ["esriFieldTypeSmallInteger", "esriFieldTypeInteger"],
                "multipleSelection": false,
                "fieldName": "itemVotesField",
                "label": "Field storing the vote tally for each report",
                "tooltip": "Numeric field in the selected layer for tracking the votes received for each feature. Field name is case-sensitive."
            }, {
                "supportedTypes": ["esriFieldTypeSmallInteger", "esriFieldTypeInteger", "esriFieldTypeSingle",
                    "esriFieldTypeDouble", "esriFieldTypeString", "esriFieldTypeDate"],
                "multipleSelection": false,
                "fieldName": "sortField",
                "label": "Field used for sorting the list of features",
                "tooltip": "Field in the selected layer for sorting items listed in app. If omitted, items are not sorted."
            }]
        }, {
            "label": "Sort order of features using values from the field defined above.",
            "fieldName": "ascendingSortOrder",
            "type": "radio",
            "tooltip": "Sorts features in ascending or descending order using the values of the sorting field. This parameter is ignored when no sorting field is specified.",
            "items":[{
                "label": "Ascending",
                "value": "true",
                "checked": true
            }, {
                "label": "Descending",
                "value": "false"
            }]
        }, {
            "label": "Initial view on mobile devices",
            "fieldName": "showListViewFirst",
            "type": "radio",
            "tooltip": "Choose to initially load a map view or a list view of the features",
            "items":[{
                "label": "Show list first",
                "value": "true",
                "checked": true
            }, {
                "label": "Show map first",
                "value": "false"
            }]
        }, {
            "label": "Initial feature display",
            "fieldName": "showAllFeatures",
            "type": "radio",
            "tooltip": "Choose to initially list all features, or to list only the features that are currently visible on the map",
            "items":[{
                "label": "Show all features",
                "value": "true",
                "checked": true
            }, {
                "label": "Show features in current map extent",
                "value": "false"
            }]
        }]
    }, {
        "category": "Custom URL Parameter",
        "fields": [{
            "type": "paragraph",
            "value": "Set up the app to support a custom URL parameter. For example, if your map contains a feature layer with parcel information and you'd like to be able to find parcels using a URL parameter you can use this section to do so. Select a layer and search field then define the name of a custom param. Once you've defined these values you can append the custom search to your application URL using the custom parameter name you define. For example, if I set the custom param value to parcels a custom URL would look like this index.html?parcel=3045"
        }, {
            "placeHolder": "i.e. parcels",
            "label": "URL parameter name:",
            "fieldName": "customUrlParam",
            "type": "string",
            "tooltip": "Custom URL parameter name"
        }, {
            "type": "layerAndFieldSelector",
            "fieldName": "customUrlLayer",
            "label": "Layer to search for custom URL parameter value",
            "tooltip": "URL parameter search layer",
            "fields": [{
                "multipleSelection": false,
                "fieldName": "urlField",
                "label": "URL parameter search field",
                "tooltip": "URL parameter search field"
            }],
            "layerOptions": {
                "supportedTypes": [
                    "FeatureLayer"
                ],
                "geometryTypes": [
                    "esriGeometryPoint",
                    "esriGeometryLine",
                    "esriGeometryPolyline",
                    "esriGeometryPolygon"
                ]
            }
        }]
    }]
}
<commit_msg>Tweaked example for custom URL param<commit_after>{
    "values": {
        "webmap": "",
        "title": "Crowdsource Polling",
        "titleIcon": "images/banner.png",
        "displayText": "Welcome to the Crowdsource Polling application
Use Crowdsource Polling to provide information and collect feedback on plans and issues around your community.

Search for a location or click an item in the list to get started.
",
        "featureLayer": {
            "id": "LandUseCasesVotesComments_8488",
            "fields": [{
                "id": "sortField",
                "fields": ["CASENAME"]
            }, {
                "id": "itemVotesField",
                "fields": ["VOTES"]
            }]
        },
        "ascendingSortOrder": "true",
        "showListViewFirst": "true",
        "showAllFeatures": "true",
        "commentNameField": "NAME",
        "allowFacebook": false,
        "facebookAppId": "",
        "allowGoogle": false,
        "googleplusClientId": "",
        "allowTwitter": true,
        "socialMediaDisclaimer": "Choose how you would like to sign in to this application. The name associated with your social media account will be added to any comments you post.",
        "showDisplayTextAsSplashScreen": false,
        "customUrlLayer": {
            "id": null,
            "fields": []
        },
        "customUrlParam": null,
        "color": "#206bdb",
        "headerBackgroundColor": "white",
        "bodyTextColor": "black",
        "bodyBackgroundColor": "white",
        "buttonTextColor": "#206bdb",
        "buttonBackgroundColor": "white"
    },
    "configurationSettings": [{
        "category": "General",
        "fields": [{
            "label": "Select a map",
            "fieldName": "webmap",
            "type": "webmap",
            "tooltip": "Map displayed in the application"
        }, {
            "label": "Application title",
            "fieldName": "title",
            "type": "string",
            "tooltip": "Application name (max 23 chars)"
        }, {
            "label": "Help widget text",
            "fieldName": "displayText",
            "type": "string",
            "tooltip": "Text displayed in the help window. HTML tags can be used for formatting.",
            "stringFieldOption": "richtext"
        }, {
            "label": "Display the help widget as a splash screen",
            "fieldName": "showDisplayTextAsSplashScreen",
            "type": "boolean"
        }, {
            "type": "subcategory",
            "label": "Sign in options"
        }, {
            "type": "paragraph",
            "value": "Allow your users to sign in to this application using their social media credentials. Comments submitted by authenticated users will have the commenters name automatically stored with their feedback."
        }, {
            "type": "paragraph",
            "value": "See the help for the steps to register your app with Facebook and Google+."
        }, {
            "label": "Field to store the name of authenticated commenters.",
            "fieldName": "commentNameField",
            "type": "string",
            "tooltip": "Field in a table with a geodatabase relationship to the selected feature layer for storing the name of authenticated commenters. Table must exist in map. Field name is case-sensitive."
        }, {
            "label": "Allow users to sign in using Twitter",
            "fieldName": "allowTwitter",
            "type": "boolean",
            "tooltip": "Enable to allow users to sign in using their Twitter credentials"
        }, {
            "label": "Allow users to sign in using Facebook",
            "tooltip": "Enable to allow users to sign in using their Facebook credentials",
            "type": "conditional",
            "fieldName": "allowFacebook",
            "condition": false,
            "items":[{
                "label": "Please register your app with Facebook and provide your Facebook AppId",
                "tooltip": "Facebook AppId",
                "type": "string",
                "fieldName": "facebookAppId"
            }]
        }, {
            "label": "Allow users to sign in using Google+",
            "tooltip": "Enable to allow users to sign in using their Google+ credentials",
            "type": "conditional",
            "fieldName": "allowGoogle",
            "condition":false,
            "items":[{
                "label": "Please register your app with Google+ and provide your Google+ Client ID",
                "tooltip": "Google+ ClientId",
                "type": "string",
                "fieldName": "googleplusClientId"
            }]
        }, {
            "label": "Sign in window text",
            "fieldName": "socialMediaDisclaimer",
            "type": "string",
            "placeholder": "",
            "tooltip": "Text to display in the Sign In window",
            "stringFieldOption": "richtext"
        }]
    }, {
        "category": "Theme",
        "fields": [{
            "label": "Header text color",
            "tooltip": "Set header text color",
            "type": "color",
            "sharedThemeProperty": "header.text",
            "fieldName": "color"
        }, {
            "label": "Header background color",
            "tooltip": "Set header background color",
            "type": "color",
            "sharedThemeProperty": "header.background",
            "fieldName": "headerBackgroundColor"
        }, {
            "label": "Body text color",
            "tooltip": "Set body text color",
            "type": "color",
            "sharedThemeProperty": "body.text",
            "fieldName": "bodyTextColor"
        }, {
            "label": "Body background color",
            "tooltip": "Set body background color",
            "type": "color",
            "sharedThemeProperty": "body.background",
            "fieldName": "bodyBackgroundColor"
        }, {
            "label": "Button text color",
            "tooltip": "Set button text color",
            "type": "color",
            "sharedThemeProperty": "button.text",
            "fieldName": "buttonTextColor"
        }, {
            "label": "Button background color",
            "tooltip": "Set button background color",
            "type": "color",
            "sharedThemeProperty": "button.background",
            "fieldName": "buttonBackgroundColor"
        }, {
            "label": "Application logo",
            "fieldName": "titleIcon",
            "type": "string",
            "sharedThemeProperty": "logo.small",
            "tooltip": "Icon in top left corner of application. Icon should be 48px high."
        }]
    }, {
        "category": "Options",
        "fields": [{
            "label": "Polling feature layer",
            "fieldName": "featureLayer",
            "type": "layerAndFieldSelector",
            "tooltip": "Point, line, or polygon layer containing the features to present in the application.",
            "layerOptions": {
                "supportedTypes": ["FeatureLayer"],
                "geometryTypes": ["esriGeometryPoint", "esriGeometryLine", "esriGeometryPolyline", "esriGeometryPolygon"]
            },
            "fields": [{
                "supportedTypes": ["esriFieldTypeSmallInteger", "esriFieldTypeInteger"],
                "multipleSelection": false,
                "fieldName": "itemVotesField",
                "label": "Field storing the vote tally for each report",
                "tooltip": "Numeric field in the selected layer for tracking the votes received for each feature. Field name is case-sensitive."
            }, {
                "supportedTypes": ["esriFieldTypeSmallInteger", "esriFieldTypeInteger", "esriFieldTypeSingle",
                    "esriFieldTypeDouble", "esriFieldTypeString", "esriFieldTypeDate"],
                "multipleSelection": false,
                "fieldName": "sortField",
                "label": "Field used for sorting the list of features",
                "tooltip": "Field in the selected layer for sorting items listed in app. If omitted, items are not sorted."
            }]
        }, {
            "label": "Sort order of features using values from the field defined above.",
            "fieldName": "ascendingSortOrder",
            "type": "radio",
            "tooltip": "Sorts features in ascending or descending order using the values of the sorting field. This parameter is ignored when no sorting field is specified.",
            "items":[{
                "label": "Ascending",
                "value": "true",
                "checked": true
            }, {
                "label": "Descending",
                "value": "false"
            }]
        }, {
            "label": "Initial view on mobile devices",
            "fieldName": "showListViewFirst",
            "type": "radio",
            "tooltip": "Choose to initially load a map view or a list view of the features",
            "items":[{
                "label": "Show list first",
                "value": "true",
                "checked": true
            }, {
                "label": "Show map first",
                "value": "false"
            }]
        }, {
            "label": "Initial feature display",
            "fieldName": "showAllFeatures",
            "type": "radio",
            "tooltip": "Choose to initially list all features, or to list only the features that are currently visible on the map",
            "items":[{
                "label": "Show all features",
                "value": "true",
                "checked": true
            }, {
                "label": "Show features in current map extent",
                "value": "false"
            }]
        }]
    }, {
        "category": "Custom URL Parameter",
        "fields": [{
            "type": "paragraph",
            "value": "Set up the app to support a custom URL parameter. For example, if your map contains a feature layer with parcel information and you'd like to be able to find parcels using a URL parameter you can use this section to do so. Select a layer and search field then define the name of a custom param. Once you've defined these values you can append the custom search to your application URL using the custom parameter name you define. For example, if I set the custom param value to 'parcel' a custom URL would look like this index.html?parcel=3045"
        }, {
            "placeHolder": "i.e. parcels",
            "label": "URL parameter name:",
            "fieldName": "customUrlParam",
            "type": "string",
            "tooltip": "Custom URL parameter name"
        }, {
            "type": "layerAndFieldSelector",
            "fieldName": "customUrlLayer",
            "label": "Layer to search for custom URL parameter value",
            "tooltip": "URL parameter search layer",
            "fields": [{
                "multipleSelection": false,
                "fieldName": "urlField",
                "label": "URL parameter search field",
                "tooltip": "URL parameter search field"
            }],
            "layerOptions": {
                "supportedTypes": [
                    "FeatureLayer"
                ],
                "geometryTypes": [
                    "esriGeometryPoint",
                    "esriGeometryLine",
                    "esriGeometryPolyline",
                    "esriGeometryPolygon"
                ]
            }
        }]
    }]
}
<|endoftext|>


<commit_before>var $ = require('jquery');
var CoreView = require('backbone/core-view');
var VisDefinitionModel = require('../../data/vis-definition-model');
var CreationModalView = require('../../components/modals/creation/modal-creation-view');
var DatasetBaseView = require('../../components/dataset/dataset-base-view');
var errorParser = require('../../helpers/error-parser');
var PanelWithOptionsView = require('../../components/view-options/panel-with-options-view');
var TabPaneView = require('../../components/tab-pane/tab-pane-view');
var TabPaneCollection = require('../../components/tab-pane/tab-pane-collection');
var Toggler = require('../../components/toggler/toggler-view');
var DatasetEditorView = require('./dataset-sql-view');
var ActionView = require('./dataset-actions-view');
var PreviewMapView = require('./preview-map-view');
var ActionViewEdition = require('./dataset-actions-edition-view');
var DataSQLModel = require('../data-sql-model');
var SQLUtils = require('../../helpers/sql-utils');
var SQLNotifications = require('../../sql-notifications');
var MetricsTracker = require('../../components/metrics/metrics-tracker');
var checkAndBuildOpts = require('../../helpers/required-opts');

var REQUIRED_OPTS = [
  'analysisDefinitionNodeModel',
  'configModel',
  'editorModel',
  'layerDefinitionModel',
  'modals',
  'router',
  'userModel',
  'visModel'
];

module.exports = DatasetBaseView.extend({

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this._querySchemaModel = this._analysisDefinitionNodeModel.querySchemaModel;

    if (!this._layerDefinitionModel.sqlModel) {
      var sqlHistory = this._layerDefinitionModel.options && this._layerDefinitionModel.options.sql_history;
      this._layerDefinitionModel.sqlModel = new DataSQLModel({
        content: this._querySchemaModel.get('query')
      }, {
        history: sqlHistory || []
      });
    }

    DatasetBaseView.prototype.initialize.call(this, {
      layerDefinitionModel: this._layerDefinitionModel,
      editorModel: this._editorModel,
      configModel: this._configModel,
      querySchemaModel: this._querySchemaModel
    });

    this._tableModel = this._analysisDefinitionNodeModel.getTableModel();
    this._queryGeometryModel = this._analysisDefinitionNodeModel.queryGeometryModel;
    this._syncModel = this._tableModel.getSyncModel();

    this._canCreateMap = this._userModel.hasCreateMapsFeature();

    this._parseSQL = this._internalParseSQL.bind(this);

    SQLNotifications.track(this);

    this._configPanes();
    this._initBinds();
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    this._checkClearButton();
    return this;
  },

  _initBinds: function () {
    this.listenTo(this._editorModel, 'change:edition', this._onChangeEdition);
    this.listenTo(this._querySchemaModel, 'change:query_errors', this._showErrors);
    this.listenTo(this._visModel, 'change:name', this._onChangeName);
    this.listenTo(this._sqlModel, 'undo redo', function () {
      this._codemirrorModel.set('content', this._sqlModel.get('content'));
    });
  },

  _onChangeName: function (model, name) {
    this._codemirrorModel.set('content', this._analysisDefinitionNodeModel.getDefaultQuery());
  },

  _initViews: function () {
    var self = this;

    var panelWithOptionsView = new PanelWithOptionsView({
      editorModel: self._editorModel,
      createContentView: function () {
        return new TabPaneView({
          collection: self._collectionPane
        });
      },
      createControlView: function () {
        return new Toggler({
          editorModel: self._editorModel,
          labels: [_t('dataset.data'), _t('dataset.sql')]
        });
      },
      createActionView: function () {
        return new TabPaneView({
          collection: self._collectionPane,
          createContentKey: 'createActionView'
        });
      }
    });

    this.$el.append(panelWithOptionsView.render().el);
    this.addView(panelWithOptionsView);
  },

  _onChangeEdition: function () {
    this.$el.toggleClass('is-dark', this._editorModel.isEditing());

    var edition = this._editorModel.get('edition');
    var index = edition ? 1 : 0;
    this._collectionPane.at(index).set({ selected: true });
  },

  _configPanes: function () {
    var self = this;
    var tabPaneTabs = [{
      selected: !this._editorModel.get('edition'),
      createContentView: function () {
        return new CoreView();
      },
      createActionView: function () {
        var actionViewOptions = {
          queryGeometryModel: self._queryGeometryModel,
          previewAction: self._previewMap.bind(self)
        };
        if (self._canCreateMap) {
          actionViewOptions.mapAction = self._createMap.bind(self);
        }
        return new ActionView(actionViewOptions);
      }
    }, {
      selected: this._editorModel.get('edition'),
      createContentView: function () {
        return new DatasetEditorView({
          editorModel: self._editorModel,
          codemirrorModel: self._codemirrorModel,
          onApplyEvent: self._parseSQL,
          layerDefinitionModel: self._layerDefinitionModel,
          querySchemaModel: self._querySchemaModel
        });
      },
      createActionView: function () {
        var actionViewOptions = {
          clearSQLModel: self._clearSQLModel,
          trackModel: self._sqlModel,
          editorModel: self._editorModel,
          queryGeometryModel: self._queryGeometryModel,
          onApply: self._parseSQL,
          previewAction: self._previewMap.bind(self),
          onClear: self._clearSQL.bind(self)
        };
        if (self._canCreateMap) {
          actionViewOptions.mapAction = self._createMap.bind(self);
        }
        return new ActionViewEdition(actionViewOptions);
      }
    }];

    this._collectionPane = new TabPaneCollection(tabPaneTabs);
  },

  _runQuery: function (query, callback) {
    this._querySchemaModel.set({
      query: query,
      status: 'unfetched'
    });

    this._queryGeometryModel.set({
      query: query,
      simple_geom: '',
      status: 'unfetched'
    }, {
      silent: true
    });

    this._querySchemaModel.fetch({
      success: callback
    });

    this._queryGeometryModel.fetch();
  },

  _saveSQL: function () {
    var content = this._codemirrorModel.get('content');
    this._sqlModel.set('content', content);
    this._querySchemaModel.set('query_errors', []);
    this._layerDefinitionModel.save({
      sql: content
    });

    SQLNotifications.showNotification({
      status: 'success',
      info: _t('notifications.sql.success'),
      closable: true
    });

    this._checkClearButton();

    MetricsTracker.track('Applied sql', {
      dataset_id: this._tableModel.get('id'),
      sql: this._sqlModel.get('content')
    });
  },

  _previewMap: function () {
    var previewMap = new PreviewMapView({
      tableModel: this._tableModel,
      configModel: this._configModel,
      querySchemaModel: this._querySchemaModel,
      syncModel: this._syncModel,
      userModel: this._userModel,
      visModel: this._visModel,
      modals: this._modals
    });
    $('body').append(previewMap.render().el);
    this.addView(previewMap);
  },

  _createMap: function () {
    var self = this;
    var tableName = this._tableModel.getUnquotedName();

    this._modals.create(function (modalModel) {
      return new CreationModalView({
        modalModel: modalModel,
        loadingTitle: _t('dataset.create-map.loading', { tableName: tableName }),
        errorTitle: _t('dataset.create-map.error', { tableName: tableName }),
        runAction: function (opts) {
          var newVisModel = new VisDefinitionModel({
            name: self._visModel.get('name') + ' ' + _t('editor.map')
          }, {
            configModel: self._configModel
          });

          newVisModel.save({
            source_visualization_id: self._visModel.get('id')
          }, {
            success: function (visModel) {
              window.location = visModel.builderURL();
            },
            error: function (mdl, e) {
              opts.error && opts.error(errorParser(e));
            }
          });
        }
      });
    });
  }
});
<commit_msg>Fixing #10126<commit_after>var $ = require('jquery');
var CoreView = require('backbone/core-view');
var VisDefinitionModel = require('../../data/vis-definition-model');
var CreationModalView = require('../../components/modals/creation/modal-creation-view');
var DatasetBaseView = require('../../components/dataset/dataset-base-view');
var errorParser = require('../../helpers/error-parser');
var PanelWithOptionsView = require('../../components/view-options/panel-with-options-view');
var TabPaneView = require('../../components/tab-pane/tab-pane-view');
var TabPaneCollection = require('../../components/tab-pane/tab-pane-collection');
var Toggler = require('../../components/toggler/toggler-view');
var DatasetEditorView = require('./dataset-sql-view');
var ActionView = require('./dataset-actions-view');
var PreviewMapView = require('./preview-map-view');
var ActionViewEdition = require('./dataset-actions-edition-view');
var DataSQLModel = require('../data-sql-model');
var SQLNotifications = require('../../sql-notifications');
var MetricsTracker = require('../../components/metrics/metrics-tracker');
var checkAndBuildOpts = require('../../helpers/required-opts');

var REQUIRED_OPTS = [
  'analysisDefinitionNodeModel',
  'configModel',
  'editorModel',
  'layerDefinitionModel',
  'modals',
  'router',
  'userModel',
  'visModel'
];

module.exports = DatasetBaseView.extend({

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this._querySchemaModel = this._analysisDefinitionNodeModel.querySchemaModel;

    if (!this._layerDefinitionModel.sqlModel) {
      var sqlHistory = this._layerDefinitionModel.options && this._layerDefinitionModel.options.sql_history;
      this._layerDefinitionModel.sqlModel = new DataSQLModel({
        content: this._querySchemaModel.get('query')
      }, {
        history: sqlHistory || []
      });
    }

    DatasetBaseView.prototype.initialize.call(this, {
      layerDefinitionModel: this._layerDefinitionModel,
      editorModel: this._editorModel,
      configModel: this._configModel,
      querySchemaModel: this._querySchemaModel
    });

    this._tableModel = this._analysisDefinitionNodeModel.getTableModel();
    this._queryGeometryModel = this._analysisDefinitionNodeModel.queryGeometryModel;
    this._syncModel = this._tableModel.getSyncModel();

    this._canCreateMap = this._userModel.hasCreateMapsFeature();

    this._parseSQL = this._internalParseSQL.bind(this);

    SQLNotifications.track(this);

    this._configPanes();
    this._initBinds();
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    this._checkClearButton();
    return this;
  },

  _initBinds: function () {
    this.listenTo(this._editorModel, 'change:edition', this._onChangeEdition);
    this.listenTo(this._querySchemaModel, 'change:query_errors', this._showErrors);
    this.listenTo(this._visModel, 'change:name', this._onChangeName);
    this.listenTo(this._sqlModel, 'undo redo', function () {
      this._codemirrorModel.set('content', this._sqlModel.get('content'));
    });
  },

  _onChangeName: function (model, name) {
    this._codemirrorModel.set('content', this._analysisDefinitionNodeModel.getDefaultQuery());
  },

  _initViews: function () {
    var self = this;

    var panelWithOptionsView = new PanelWithOptionsView({
      editorModel: self._editorModel,
      createContentView: function () {
        return new TabPaneView({
          collection: self._collectionPane
        });
      },
      createControlView: function () {
        return new Toggler({
          editorModel: self._editorModel,
          labels: [_t('dataset.data'), _t('dataset.sql')]
        });
      },
      createActionView: function () {
        return new TabPaneView({
          collection: self._collectionPane,
          createContentKey: 'createActionView'
        });
      }
    });

    this.$el.append(panelWithOptionsView.render().el);
    this.addView(panelWithOptionsView);
  },

  _onChangeEdition: function () {
    this.$el.toggleClass('is-dark', this._editorModel.isEditing());

    var edition = this._editorModel.get('edition');
    var index = edition ? 1 : 0;
    this._collectionPane.at(index).set({ selected: true });
  },

  _configPanes: function () {
    var self = this;
    var tabPaneTabs = [{
      selected: !this._editorModel.get('edition'),
      createContentView: function () {
        return new CoreView();
      },
      createActionView: function () {
        var actionViewOptions = {
          queryGeometryModel: self._queryGeometryModel,
          previewAction: self._previewMap.bind(self)
        };
        if (self._canCreateMap) {
          actionViewOptions.mapAction = self._createMap.bind(self);
        }
        return new ActionView(actionViewOptions);
      }
    }, {
      selected: this._editorModel.get('edition'),
      createContentView: function () {
        return new DatasetEditorView({
          editorModel: self._editorModel,
          codemirrorModel: self._codemirrorModel,
          onApplyEvent: self._parseSQL,
          layerDefinitionModel: self._layerDefinitionModel,
          querySchemaModel: self._querySchemaModel
        });
      },
      createActionView: function () {
        var actionViewOptions = {
          clearSQLModel: self._clearSQLModel,
          trackModel: self._sqlModel,
          editorModel: self._editorModel,
          queryGeometryModel: self._queryGeometryModel,
          onApply: self._parseSQL,
          previewAction: self._previewMap.bind(self),
          onClear: self._clearSQL.bind(self)
        };
        if (self._canCreateMap) {
          actionViewOptions.mapAction = self._createMap.bind(self);
        }
        return new ActionViewEdition(actionViewOptions);
      }
    }];

    this._collectionPane = new TabPaneCollection(tabPaneTabs);
  },

  _runQuery: function (query, callback) {
    this._querySchemaModel.set({
      query: query,
      status: 'unfetched'
    });

    this._queryGeometryModel.set({
      query: query,
      simple_geom: '',
      status: 'unfetched'
    }, {
      silent: true
    });

    this._querySchemaModel.fetch({
      success: callback
    });

    this._queryGeometryModel.fetch();
  },

  _saveSQL: function () {
    var content = this._codemirrorModel.get('content');
    this._sqlModel.set('content', content);
    this._querySchemaModel.set('query_errors', []);

    if (this._tableModel.hasWriteAccess(this._userModel)) {
      this._layerDefinitionModel.save({
        sql: content
      });

      MetricsTracker.track('Applied sql', {
        dataset_id: this._tableModel.get('id'),
        sql: content
      });
    }

    SQLNotifications.showNotification({
      status: 'success',
      info: _t('notifications.sql.success'),
      closable: true
    });

    this._checkClearButton();
  },

  _defaultSQL: function () {
    return this._analysisDefinitionNodeModel.getDefaultQuery();
  },

  _previewMap: function () {
    var previewMap = new PreviewMapView({
      tableModel: this._tableModel,
      configModel: this._configModel,
      querySchemaModel: this._querySchemaModel,
      syncModel: this._syncModel,
      userModel: this._userModel,
      visModel: this._visModel,
      modals: this._modals
    });
    $('body').append(previewMap.render().el);
    this.addView(previewMap);
  },

  _createMap: function () {
    var self = this;
    var tableName = this._tableModel.getUnquotedName();

    this._modals.create(function (modalModel) {
      return new CreationModalView({
        modalModel: modalModel,
        loadingTitle: _t('dataset.create-map.loading', { tableName: tableName }),
        errorTitle: _t('dataset.create-map.error', { tableName: tableName }),
        runAction: function (opts) {
          var newVisModel = new VisDefinitionModel({
            name: self._visModel.get('name') + ' ' + _t('editor.map')
          }, {
            configModel: self._configModel
          });

          newVisModel.save({
            source_visualization_id: self._visModel.get('id')
          }, {
            success: function (visModel) {
              window.location = visModel.builderURL();
            },
            error: function (mdl, e) {
              opts.error && opts.error(errorParser(e));
            }
          });
        }
      });
    });
  }
});
<|endoftext|>


<commit_before>(function($) {
  // Slick.FilterPanel
  $.extend(true, window, {
      Slick: {
          FilterPanel: FilterPanel
      }
  });
  function FilterPanel(grid, loader, triggerElement, currentFilters) {
    var filterWidthOffset = -3; // 2 pixels padding on the left and one pixel for the border on the left
    // private
    var $grid;
    var $loader;
    var self = this;
    var currentFiltersApplied = [];

    function init() {
      $grid = grid;
      $loader = loader;

      generateFilters();

      $grid.onColumnsReordered.subscribe(function(){
        generateFilters();
      });
      $grid.onColumnsResized.subscribe(function(){
        generateFilters();
      });

      if (currentFilters) {
        $grid.showHeaderRowColumns();
      }

      triggerElement.click(function() {
        if($(this).hasClass('toolbar_icon_disabled')) return false;

        if ($($grid.getHeaderRow()).is(":visible")) {
            $grid.hideHeaderRowColumns();
            currentFilters = null;
            trigger(self.onFilterPanelClosed, {filterData:currentFiltersApplied});
        } else {
            $grid.showHeaderRowColumns();
            // This corrects the scrollLeft of the filter secondary header row.
            // The problem is that if the user scrolls on the left then click on filter, the
            //   filters wouldn't have scrolled while there were hidden so they appear shifted.
            // This corrects this problem by setting the scrollLeft value of the filters panel
            //   to the scrollLeft of the header row
            headerScroller = $($grid.getHeaderRow()).parent()[0];
            headerScroller.scrollLeft = $(headerScroller).prev()[0].scrollLeft;
        }
        return false;
      });

      var delay = (function(){
        var timer = 0;
        return function(callback, ms){
          clearTimeout (timer);
          timer = setTimeout(callback, ms);
        };
      })();

      // Hook between the filter input box and the data loader setFilter
      // Applay filter after 1000ms
      $("input", $($grid.getHeaderRow())).live('keyup', function(e) {
        delay(function(){
          updateCurrentFilters();
          applyCurrentFilters(currentFilters);
          setCurrentFilter();
          trigger(self.onFilterLoaded, {filterData:currentFiltersApplied});
        }, 1000);
      });
    }

    function trigger(evt, args, e) {
        e = e || new Slick.EventData();
        args = args || {};
        args.filterPanel = self;
        return evt.notify(args, e, self);
    }

    function generateFilters() {
      var inputWidth, columns, inputElement;
      var ua = navigator.userAgent.toLowerCase();

      html = "";
      columns = $grid.getColumns();
      totalColumnsCount = columns.length;

      applyCurrentFilters(currentFilters);
      setOriginalFilter();

      $.each(columns, function(i, value) {
        var value = '', field = this.id, inputHtml = '', inputWidth, cssClass = "";
        // Try to get the value of this filter if any
        $.each(currentFiltersApplied, function() {
          if (this.id==field)
            value = this.value;
        });

        if (i==(totalColumnsCount-1)) {
          cssClass = "lastColumn";
        }

        inputWidth = $.browser.mozilla ? parseInt(this.width)+filterWidthOffset + 1 : parseInt(this.width)+filterWidthOffset - 1;

        if (!$.browser.msie && (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1 || ua.indexOf("linux") != -1)) {
          inputWidth += 2;
        }

        inputHtml += '<input type="text" id="' + field + '" style="width:' + inputWidth + 'px;border-width:1px;height:20px;border-bottom-color:#DDD;" value="' + value + '" class="' + cssClass + '"';

        if (this.filterable == false) {
          inputHtml += ' disabled="disabled"';
        }

        inputHtml += '></input>';
        html += inputHtml;
      });

      // Fills up and display the secondary row
      $($grid.getHeaderRow()).html(html).show();
    }

    // This method update the current filters applied to the currentFiltersApplied array
    // We store the filters value so that after resizing or reordering of the columns, we can
    //  generate the filters boxes with the same values
    function updateCurrentFilters() {
      currentFilters = {};
      $.each($("input", $($grid.getHeaderRow())), function() {
        if ($(this).val()!='') {
          currentFilters[$(this).attr('id')] = $(this).val();
        }
      });
    }

    function setOriginalFilter() {
      var originalFilters = $loader.getFilters();
      if (currentFiltersApplied.length != 0) {
        $.each(currentFiltersApplied, function() {
          if(this['operator'] == undefined) this['operator'] = 'equals'
          var newFilter = [this['id'], this['value'], this['operator']];
          if(!$(originalFilters).arrayDeepInclude(newFilter)) {
            originalFilters.push([this['id'], this['value'], this['operator']]);
          }
        });

        $loader.setFilterWithoutRefresh(originalFilters);
      }
    }

    function setCurrentFilter(){
      var filters = [];
      // add current filters
      if (currentFiltersApplied.length > 0) {
        $.each(currentFiltersApplied, function(){
          filters.push([this['id'], this['value'], 'equals']);
        });
      }
      // add masters
      if ($grid.master) {
        if ($grid.master instanceof Array) {
          $.each($grid.master, function(){
            filters.push(this);
          });
        } else {
          filters.push([$grid.master.filter_column, $grid.master.filter_value, $grid.master.filter_operator]);
        }
      }
      $loader.setFilter(filters);
    }

    function applyCurrentFilters(filters) {
      currentFiltersApplied = [];
      if (filters) {
        $.each(filters, function(k, v) {
          if (v !='')
            currentFiltersApplied.push({id: k, value: v});
        });
      }
    }

    $.extend(this, {
        // Events
        "onFilterLoaded":                     new Slick.Event(),
        'onFilterPanelClosed':                new Slick.Event(),

        // Methods
        'generateFilters':                    generateFilters,
        "applyCurrentFilters":                applyCurrentFilters,
        "updateCurrentFilters":               updateCurrentFilters
    });

    init();
  }
}(jQuery));<commit_msg>BUG #14481 @8h - Tab key on filter panel broken the layout<commit_after>(function($) {
  // Slick.FilterPanel
  $.extend(true, window, {
      Slick: {
          FilterPanel: FilterPanel
      }
  });
  function FilterPanel(grid, loader, triggerElement, currentFilters) {
    var filterWidthOffset = -3; // 2 pixels padding on the left and one pixel for the border on the left
    // private
    var $grid;
    var $loader;
    var self = this;
    var currentFiltersApplied = [];

    function init() {
      $grid = grid;
      $loader = loader;

      generateFilters();

      $grid.onColumnsReordered.subscribe(function(){
        generateFilters();
      });
      $grid.onColumnsResized.subscribe(function(){
        generateFilters();
      });

      if (currentFilters) {
        $grid.showHeaderRowColumns();
      }

      triggerElement.click(function() {
        if($(this).hasClass('toolbar_icon_disabled')) return false;

        if ($($grid.getHeaderRow()).is(":visible")) {
            $grid.hideHeaderRowColumns();
            currentFilters = null;
            trigger(self.onFilterPanelClosed, {filterData:currentFiltersApplied});
        } else {
            $grid.showHeaderRowColumns();
            // This corrects the scrollLeft of the filter secondary header row.
            // The problem is that if the user scrolls on the left then click on filter, the
            //   filters wouldn't have scrolled while there were hidden so they appear shifted.
            // This corrects this problem by setting the scrollLeft value of the filters panel
            //   to the scrollLeft of the header row
            headerScroller = $($grid.getHeaderRow()).parent()[0];
            headerScroller.scrollLeft = $(headerScroller).prev()[0].scrollLeft;
        }
        return false;
      });

      var delay = (function(){
        var timer = 0;
        return function(callback, ms){
          clearTimeout (timer);
          timer = setTimeout(callback, ms);
        };
      })();

      // Hook between the filter input box and the data loader setFilter
      // Applay filter after 1000ms
      $("input", $($grid.getHeaderRow())).off('keyup').on('keyup', function(e) {
        var containerWidth = $grid.container.innerWidth();
        var inputLeft = $(this).position().left + $(this).outerWidth();
        var $viewPort = $($grid.getCanvasNode()).parent();
        var ignoreKeyCodes = [9, 224, 13];

        if (containerWidth < inputLeft) {
          $viewPort.scrollLeft(inputLeft - containerWidth);
        }

        if (ignoreKeyCodes.indexOf(e.which) == -1) {
          delay(function(){
            updateCurrentFilters();
            applyCurrentFilters(currentFilters);
            setCurrentFilter();
            trigger(self.onFilterLoaded, {filterData:currentFiltersApplied});
          }, 1000);
        }
      });
    }

    function trigger(evt, args, e) {
        e = e || new Slick.EventData();
        args = args || {};
        args.filterPanel = self;
        return evt.notify(args, e, self);
    }

    function generateFilters() {
      var inputWidth, columns, inputElement;
      var ua = navigator.userAgent.toLowerCase();

      html = "";
      columns = $grid.getColumns();
      totalColumnsCount = columns.length;

      applyCurrentFilters(currentFilters);
      setOriginalFilter();

      $.each(columns, function(i, value) {
        var value = '', field = this.id, inputHtml = '', inputWidth, cssClass = "";
        // Try to get the value of this filter if any
        $.each(currentFiltersApplied, function() {
          if (this.id==field)
            value = this.value;
        });

        if (i==(totalColumnsCount-1)) {
          cssClass = "lastColumn";
        }

        inputWidth = $.browser.mozilla ? parseInt(this.width)+filterWidthOffset + 1 : parseInt(this.width)+filterWidthOffset - 1;

        if (!$.browser.msie && (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1 || ua.indexOf("linux") != -1)) {
          inputWidth += 2;
        }

        inputHtml += '<input type="text" id="' + field + '" style="width:' + inputWidth + 'px;border-width:1px;height:20px;border-bottom-color:#DDD;" value="' + value + '" class="' + cssClass + '"';

        if (this.filterable == false) {
          inputHtml += ' disabled="disabled"';
        }

        inputHtml += '></input>';
        html += inputHtml;
      });

      // Fills up and display the secondary row
      $($grid.getHeaderRow()).html(html).show();
    }

    // This method update the current filters applied to the currentFiltersApplied array
    // We store the filters value so that after resizing or reordering of the columns, we can
    //  generate the filters boxes with the same values
    function updateCurrentFilters() {
      currentFilters = {};
      $.each($("input", $($grid.getHeaderRow())), function() {
        if ($(this).val()!='') {
          currentFilters[$(this).attr('id')] = $(this).val();
        }
      });
    }

    function setOriginalFilter() {
      var originalFilters = $loader.getFilters();
      if (currentFiltersApplied.length != 0) {
        $.each(currentFiltersApplied, function() {
          if(this['operator'] == undefined) this['operator'] = 'equals'
          var newFilter = [this['id'], this['value'], this['operator']];
          if(!$(originalFilters).arrayDeepInclude(newFilter)) {
            originalFilters.push([this['id'], this['value'], this['operator']]);
          }
        });

        $loader.setFilterWithoutRefresh(originalFilters);
      }
    }

    function setCurrentFilter(){
      var filters = [];
      // add current filters
      if (currentFiltersApplied.length > 0) {
        $.each(currentFiltersApplied, function(){
          filters.push([this['id'], this['value'], 'equals']);
        });
      }
      // add masters
      if ($grid.master) {
        if ($grid.master instanceof Array) {
          $.each($grid.master, function(){
            filters.push(this);
          });
        } else {
          filters.push([$grid.master.filter_column, $grid.master.filter_value, $grid.master.filter_operator]);
        }
      }
      $loader.setFilter(filters);
    }

    function applyCurrentFilters(filters) {
      currentFiltersApplied = [];
      if (filters) {
        $.each(filters, function(k, v) {
          if (v !='')
            currentFiltersApplied.push({id: k, value: v});
        });
      }
    }

    $.extend(this, {
        // Events
        "onFilterLoaded":                     new Slick.Event(),
        'onFilterPanelClosed':                new Slick.Event(),

        // Methods
        'generateFilters':                    generateFilters,
        "applyCurrentFilters":                applyCurrentFilters,
        "updateCurrentFilters":               updateCurrentFilters
    });

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


<commit_before>import declination from '../components/declination';

Date.prototype.asInteger = function () {
    return String(this.getFullYear()) + String(this.getMonth() + 1) + String((this.getDate() < 10 ? '0' : '') + this.getDate());
};

Date.prototype.getHour = function () {
    return (this.getHours() < 10 ? '0' : '') + this.getHours();
};

Date.prototype.getMinute = function () {
    return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes();
};

function getTimeSpan(remote) {
    return Math.abs(Math.round((new Date().getTime() / 1000) - remote));
}

function getDiffMinute(remote) {
    return Math.round(getTimeSpan(remote) / 60);
}

function getDiffSecond(remote) {
    return getTimeSpan(remote);
}

let countTime = function () {
    let dates = document.querySelectorAll('.timestamp[data-timestamp]');

    dates.forEach(date => {
        let timestamp = date.getAttribute('data-timestamp');

        if (getDiffMinute(timestamp) < 60) {
            if (getDiffSecond(timestamp) >= 60) {
                date.textContent = getDiffMinute(timestamp) + ' ' + declination(getDiffMinute(timestamp), ['minuta', 'minuty', 'minut']) + ' temu';
            }
            else {
                date.textContent = getDiffSecond(timestamp) + ' ' + declination(getDiffSecond(timestamp), ['sekunda', 'sekundy', 'sekund']) + ' temu';
            }
        }
        else {
            let currDate = new Date((new Date().getTime()));
            let currValue = currDate.asInteger();

            let spanDate = new Date(timestamp * 1000);
            let spanValue = spanDate.asInteger();

            if (spanValue === currValue) {
                date.textContent = 'dziś, ' + spanDate.getHour() + ':' + spanDate.getMinute();
            }
            else if (spanValue === currValue - 1) {
                date.textContent = 'wczoraj, ' + spanDate.getHour() + ':' + spanDate.getMinute();
            }
        }
    });
};
setInterval(countTime, 30000); // 30 sek
<commit_msg>refaktoryzacja<commit_after>import declination from '../components/declination';

Date.prototype.asInteger = function () {
  return String(this.getFullYear()) + String(this.getMonth() + 1) + String((this.getDate() < 10 ? '0' : '') + this.getDate());
};

Date.prototype.getHour = function () {
  return (this.getHours() < 10 ? '0' : '') + this.getHours();
};

Date.prototype.getMinute = function () {
  return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes();
};

function getTimeSpan(remote) {
  return Math.abs(Math.round((new Date().getTime() / 1000) - remote));
}

function getDiffMinute(remote) {
  return Math.round(getTimeSpan(remote) / 60);
}

function getDiffSecond(remote) {
  return getTimeSpan(remote);
}

const timeago = (timestamp) => {
  if (getDiffMinute(timestamp) < 60) {
    if (getDiffSecond(timestamp) >= 60) {
      return getDiffMinute(timestamp) + ' ' + declination(getDiffMinute(timestamp), ['minuta', 'minuty', 'minut']) + ' temu';
    }

    return getDiffSecond(timestamp) + ' ' + declination(getDiffSecond(timestamp), ['sekunda', 'sekundy', 'sekund']) + ' temu';
  }

  let currDate = new Date((new Date().getTime()));
  let currValue = currDate.asInteger();

  let spanDate = new Date(timestamp * 1000);
  let spanValue = spanDate.asInteger();

  if (spanValue === currValue) {
    return 'dziś, ' + spanDate.getHour() + ':' + spanDate.getMinute();
  } else if (spanValue === currValue - 1) {
    return 'wczoraj, ' + spanDate.getHour() + ':' + spanDate.getMinute();
  }

  return null;
};

const countTime = () => {
  let dates = document.querySelectorAll('.timestamp[data-timestamp]');

  dates.forEach(date => {
    const timestamp = date.getAttribute('data-timestamp');
    const value = timeago(timestamp);

    if (value) {

      date.textContent = value;
    }
  });
};

setInterval(countTime, 30000); // 30 sek

export default timeago;
<|endoftext|>


<commit_before>include('ringo/webapp/response');
include('ringo/jsdoc');
require('core/array');
require('core/string');
var Buffer = require('ringo/buffer').Buffer;
var {join, base, directory, canonical} = require('fs');
var config = require('./config');
var log = require('ringo/logging').getLogger(module.id);

exports.index = function(req) {
    return skinResponse('./skins/index.html', {
        title: "API Documentation",
        packageList: renderPackageList(req)
    });
};

exports.repository = function(req, repositoryId) {
    var repository = getScriptRepository(repositoryId);
    if (!repository.exists()) {
        return notFoundResponse(req.scriptName + req.pathInfo);
    }
    return skinResponse('./skins/package.html', {
        title: "Repository " + getRepositoryName(repositoryId, repository.getPath()),
        moduleList: renderModuleList.bind(this, repositoryId, repository)
    });
};

exports.module = function(req, repositoryId, moduleId) {
    var repository = getScriptRepository(repositoryId);
    var res = repository.getScriptResource(moduleId + '.js');
    if (!res.exists()) {
        log.error(res);
        return notFoundResponse(req.scriptName + req.pathInfo);
    }
    var moduleDoc = parseResource(res);
    // log.info("export()ed symbols: " + exported);
    return skinResponse('./skins/module.html', {
        title: "Module " + res.moduleName,
        moduleName: moduleId,
        moduleDoc: moduleDoc,
        moduleList: renderModuleList.bind(this, repositoryId, repository)
    });
};

function renderModuleList(repositoryId, repository) {
    var rootPath = require('./config').rootPath;
    var modules = repository.getScriptResources(true).filter(function(r) {
        return r.moduleName != 'ringo/global' &&  r.moduleName.indexOf('test') != 0;
    }).sort(function(a, b) {
        return a.moduleName > b.moduleName ? 1 : -1;
    });
    var previous = [];
    var indent = 0;
    var buffer = new Buffer(); // '
');
    for each (var module in modules) {
        var path = module.moduleName.split('/');
        var i;
        var hasList = false;
        for (i = previous.length; i > 0; i--) {
            if (previous[i - 1] != path[i - 1]) {
                if (i < previous.length) {
                    indent -= 2;
                    buffer.writeln(' '.repeat(indent), '
');
                    indent -= 2;
                }
                if (i < previous.length) {
                    buffer.write(' '.repeat(indent));
                }
                buffer.writeln('
');
                hasList = true;
            } else {
                break;
            }
        }
        for(var j = i; j < path.length; j++) {
            if (!hasList) {
                indent += 2;
                buffer.writeln().writeln(' '.repeat(indent), '
');
                indent += 2;
            }
            var label = j < path.length - 1 ?
                    path[j] :
                    '' + path[j] + '';
            buffer.write(' '.repeat(indent), '
', label);
            hasList = false;
        }
        previous = path;
    }
    for (var z = 0; z < previous.length; z++) {
        buffer.writeln('
');
        indent -= 2;
        buffer.writeln(' '.repeat(indent), '
');
    }
    return buffer;
}

function getScriptRepository(repositoryId) {
    return new ScriptRepository(getRepositories()[repositoryId]);
}

function getRepositories() {
    return config.scriptRepositories || require.paths;
}

function getRepositoryName(key, path) {
    // check if key is numeric
    if (+key == key) {
        // use last two path elements as anchor text
        // e.g. "ringojs/modules", "jetson/lib"
        return join(base(directory(path)), base(canonical(path)));
    }
    return key;
}

function renderPackageList(req) {
    var repos = getRepositories();
    var buffer = new Buffer();
    for (var key in repos) {
        var path = repos[key];
        var name = getRepositoryName(key, path);
        buffer.writeln('
',
                name, '
');
    }
    return buffer.toString();
}
<commit_msg>Exclude both ringoglobal and ringo/global.<commit_after>include('ringo/webapp/response');
include('ringo/jsdoc');
require('core/array');
require('core/string');
var Buffer = require('ringo/buffer').Buffer;
var {join, base, directory, canonical} = require('fs');
var config = require('./config');
var log = require('ringo/logging').getLogger(module.id);

exports.index = function(req) {
    return skinResponse('./skins/index.html', {
        title: "API Documentation",
        packageList: renderPackageList(req)
    });
};

exports.repository = function(req, repositoryId) {
    var repository = getScriptRepository(repositoryId);
    if (!repository.exists()) {
        return notFoundResponse(req.scriptName + req.pathInfo);
    }
    return skinResponse('./skins/package.html', {
        title: "Repository " + getRepositoryName(repositoryId, repository.getPath()),
        moduleList: renderModuleList.bind(this, repositoryId, repository)
    });
};

exports.module = function(req, repositoryId, moduleId) {
    var repository = getScriptRepository(repositoryId);
    var res = repository.getScriptResource(moduleId + '.js');
    if (!res.exists()) {
        log.error(res);
        return notFoundResponse(req.scriptName + req.pathInfo);
    }
    var moduleDoc = parseResource(res);
    // log.info("export()ed symbols: " + exported);
    return skinResponse('./skins/module.html', {
        title: "Module " + res.moduleName,
        moduleName: moduleId,
        moduleDoc: moduleDoc,
        moduleList: renderModuleList.bind(this, repositoryId, repository)
    });
};

function renderModuleList(repositoryId, repository) {
    var rootPath = require('./config').rootPath;
    var modules = repository.getScriptResources(true).filter(function(r) {
        return !r.moduleName.match(/^ringo\/?global$/) &&  !r.moduleName.startsWith('test');
    }).sort(function(a, b) {
        return a.moduleName > b.moduleName ? 1 : -1;
    });
    var previous = [];
    var indent = 0;
    var buffer = new Buffer(); // '
');
    for each (var module in modules) {
        var path = module.moduleName.split('/');
        var i;
        var hasList = false;
        for (i = previous.length; i > 0; i--) {
            if (previous[i - 1] != path[i - 1]) {
                if (i < previous.length) {
                    indent -= 2;
                    buffer.writeln(' '.repeat(indent), '
');
                    indent -= 2;
                }
                if (i < previous.length) {
                    buffer.write(' '.repeat(indent));
                }
                buffer.writeln('
');
                hasList = true;
            } else {
                break;
            }
        }
        for(var j = i; j < path.length; j++) {
            if (!hasList) {
                indent += 2;
                buffer.writeln().writeln(' '.repeat(indent), '
');
                indent += 2;
            }
            var label = j < path.length - 1 ?
                    path[j] :
                    '' + path[j] + '';
            buffer.write(' '.repeat(indent), '
', label);
            hasList = false;
        }
        previous = path;
    }
    for (var z = 0; z < previous.length; z++) {
        buffer.writeln('
');
        indent -= 2;
        buffer.writeln(' '.repeat(indent), '
');
    }
    return buffer;
}

function getScriptRepository(repositoryId) {
    return new ScriptRepository(getRepositories()[repositoryId]);
}

function getRepositories() {
    return config.scriptRepositories || require.paths;
}

function getRepositoryName(key, path) {
    // check if key is numeric
    if (+key == key) {
        // use last two path elements as anchor text
        // e.g. "ringojs/modules", "jetson/lib"
        return join(base(directory(path)), base(canonical(path)));
    }
    return key;
}

function renderPackageList(req) {
    var repos = getRepositories();
    var buffer = new Buffer();
    for (var key in repos) {
        var path = repos[key];
        var name = getRepositoryName(key, path);
        buffer.writeln('
',
                name, '
');
    }
    return buffer.toString();
}
<|endoftext|>