<commit_before>/***
|''Name''|TiddlySpaceViewTypes|
|''Version''|0.5.4|
|''Status''|@@beta@@|
|''Description''|Provides TiddlySpace specific view types|
|''Author''|Jon Robson|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpaceViewTypes.js|
|''Requires''|TiddlySpaceConfig TiddlySpaceTiddlerIconsPlugin|
!Usage
Provides replyLink, spaceLink and SiteIcon view types.
!!SiteIcon view parameters
* labelPrefix / labelSuffix : prefix or suffix the label with additional text. eg. labelPrefix:'modified by '
* spaceLink: if set to "yes" will make any avatars link to the corresponding space. {{{<<originMacro spaceLink:yes>>}}}

!Code
***/
//{{{
(function($) {

var tiddlyspace = config.extensions.tiddlyspace;
var originMacro = config.macros.tiddlerOrigin;

config.macros.view.replyLink = {
	locale: {
		label: "Reply to this tiddler"
	}
};

config.macros.view.views.replyLink = function(value, place, params, wikifier,
		paramString, tiddler) {
	var valueField = params[0];
	var imported;
	if(valueField == "title") { // special casing for imported tiddlers
		var localTitle = tiddler.title;
		var serverTitle = tiddler.fields["server.title"];
		if(serverTitle && localTitle != serverTitle) {
			value = serverTitle ? serverTitle : localTitle;
			imported = true;
		}
	} else {
		title = tiddler[valueField] ? tiddler[valueField] : tiddler.fields[valueField];
	}
	var args = paramString.parseParams("anon")[0];
	var label = (args.label) ? args.label : config.macros.view.replyLink.locale.label;
	var space;
	if(tiddler) {
		var bag = tiddler.fields["server.bag"];
		space = tiddlyspace.resolveSpaceName(bag);
	}
	var container = $('').appendTo(place)[0];
	config.extensions.tiddlyweb.getUserInfo(function(user) {
		if(!user.anon) {
			if((space && user.name != space &&
					user.name != tiddlyspace.currentSpace.name) || imported) {
				createSpaceLink(container, user.name, value, label);
			}
		}
	});
};

config.macros.view.views.spaceLink = function(value, place, params, wikifier,
		paramString, tiddler) {
		var spaceName = tiddlyspace.resolveSpaceName(value);
		var isBag = params[0] == "server.bag" && value === spaceName ? true : false;
		var args = paramString.parseParams("anon")[0];
		var titleField = args.anon[2];
		var labelField = args.labelField ? args.labelField[0] : false;
		var label;
		if(labelField) {
			label = tiddler[labelField] ? tiddler[labelField] : tiddler.fields[labelField];
		} else {
			label = args.label ? args.label[0] : false;
		}
		var title = tiddler[titleField] ? tiddler[titleField] : tiddler.fields[titleField];

		var link = createSpaceLink(place, spaceName, title, label, isBag);
		if(args.external && args.external[0] == "no") {
			$(link).click(function(ev) {
				var el = $(ev.target);
				var title = el.attr("tiddler");
				var bag = el.attr("bag");
				var space = el.attr("tiddlyspace");
				bag = space ? space + "_public" : bag;
				if(title && bag) {
					ev.preventDefault();
					tiddlyspace.displayServerTiddler(el[0], title,
						"bags/" + bag);
				}
				return false;
			});
		}
};

config.macros.view.views.SiteIcon = function(value, place, params, wikifier,
		paramString, tiddler) {
	var options = originMacro.getOptions(paramString);
	if(!tiddler || value == "None") { // some core tiddlers lack modifier
		value = false;
	}
	var field = params[0];
	if(field == "server.bag") {
		options.notSpace = !originMacro._isSpace(value);
	}
	tiddlyspace.renderAvatar(place, value, options);
};

})(jQuery);
//}}}
<commit_msg>fix reply to this tiddler to generate tiddlywiki link<commit_after>/***
|''Name''|TiddlySpaceViewTypes|
|''Version''|0.5.6|
|''Status''|@@beta@@|
|''Description''|Provides TiddlySpace specific view types|
|''Author''|Jon Robson|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpaceViewTypes.js|
|''Requires''|TiddlySpaceConfig TiddlySpaceTiddlerIconsPlugin|
!Usage
Provides replyLink, spaceLink and SiteIcon view types.
!!SiteIcon view parameters
* labelPrefix / labelSuffix : prefix or suffix the label with additional text. eg. labelPrefix:'modified by '
* spaceLink: if set to "yes" will make any avatars link to the corresponding space. {{{<<originMacro spaceLink:yes>>}}}

!Code
***/
//{{{
(function($) {

var tiddlyspace = config.extensions.tiddlyspace;
var originMacro = config.macros.tiddlerOrigin;
var tweb = config.extensions.tiddlyweb;

config.macros.view.replyLink = {
	locale: {
		label: "Reply to this tiddler"
	}
};

config.macros.view.views.replyLink = function(value, place, params, wikifier,
		paramString, tiddler) {
	var valueField = params[0];
	var imported;
	if(valueField == "title") { // special casing for imported tiddlers
		var localTitle = tiddler.title;
		var serverTitle = tiddler.fields["server.title"];
		if(serverTitle && localTitle != serverTitle) {
			value = serverTitle ? serverTitle : localTitle;
			imported = true;
		}
	} else {
		title = tiddler[valueField] ? tiddler[valueField] : tiddler.fields[valueField];
	}
	var args = paramString.parseParams("anon")[0];
	var label = (args.label) ? args.label : config.macros.view.replyLink.locale.label;
	var space;
	if(tiddler) {
		var bag = tiddler.fields["server.bag"];
		space = tiddlyspace.resolveSpaceName(bag);
	}
	var container = $('').appendTo(place)[0];
	tweb.getUserInfo(function(user) {
		if(!user.anon) {
			if((space && user.name != space &&
					user.name != tiddlyspace.currentSpace.name) || imported) {
				createSpaceLink(container, user.name, value, label);
				tweb.getStatus(function(status) { // force callback to run after existing callbacks
					var url = config.extensions.tiddlyspace.getHost(status.server_host, user.name) + "#[[" + encodeURIComponent(value) + "]]";
					jQuery("a", container).attr("href", url);
				});
			}
		}
	});
};

config.macros.view.views.spaceLink = function(value, place, params, wikifier,
		paramString, tiddler) {
		var spaceName = tiddlyspace.resolveSpaceName(value);
		var isBag = params[0] == "server.bag" && value === spaceName ? true : false;
		var args = paramString.parseParams("anon")[0];
		var titleField = args.anon[2];
		var labelField = args.labelField ? args.labelField[0] : false;
		var label;
		if(labelField) {
			label = tiddler[labelField] ? tiddler[labelField] : tiddler.fields[labelField];
		} else {
			label = args.label ? args.label[0] : false;
		}
		var title = tiddler[titleField] ? tiddler[titleField] : tiddler.fields[titleField];

		var link = createSpaceLink(place, spaceName, title, label, isBag);
		if(args.external && args.external[0] == "no") {
			$(link).click(function(ev) {
				var el = $(ev.target);
				var title = el.attr("tiddler");
				var bag = el.attr("bag");
				var space = el.attr("tiddlyspace");
				bag = space ? space + "_public" : bag;
				if(title && bag) {
					ev.preventDefault();
					tiddlyspace.displayServerTiddler(el[0], title,
						"bags/" + bag);
				}
				return false;
			});
		}
};

config.macros.view.views.SiteIcon = function(value, place, params, wikifier,
		paramString, tiddler) {
	var options = originMacro.getOptions(paramString);
	if(!tiddler || value == "None") { // some core tiddlers lack modifier
		value = false;
	}
	var field = params[0];
	if(field == "server.bag") {
		options.notSpace = !originMacro._isSpace(value);
	}
	tiddlyspace.renderAvatar(place, value, options);
};

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


<commit_before>import React from 'react';
import _ from 'underscore';

const RadioButton = React.createClass({
    propTypes: {
        value: React.PropTypes.oneOfType([
            React.PropTypes.string,
            React.PropTypes.number,
        ]).isRequired,
        disabled: React.PropTypes.bool,
        checked: React.PropTypes.bool,

        //Set by radioGroup
        name: React.PropTypes.string.isRequired,
        onChange: React.PropTypes.func.isRequired
    },
    _onChange() {
        this.props.onChange(this.props.value);
    },
    render() {
        return (

                <input disabled={this.props.disabled} checked={this.props.checked} onChange={this._onChange} type="radio" name={this.props.name} />

                    {this.props.label}

        );
    },
});

const RadioButtonGroup = React.createClass({
    propTypes: {
        name: React.PropTypes.string,
        onChange: React.PropTypes.func,
    },
    getDefaultProps() {
        return {
            name: _.uniqueId('bilprospekt-ui-radio'),
        };
    },
    _onRadioChange(value) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(value);
        }
    },
    render() {
        const children = React.Children.map(this.props.children, (child) => {
            return React.cloneElement(child, {name: this.props.name, onChange: this._onRadioChange});
        });

        return (

                {children}

        )
    },
});

export default {
    RadioButton,
    RadioButtonGroup,
};
<commit_msg>changed some proptypes<commit_after>import React from 'react';
import _ from 'underscore';

const RadioButton = React.createClass({
    propTypes: {
        value: React.PropTypes.oneOfType([
            React.PropTypes.string,
            React.PropTypes.number,
        ]).isRequired,
        label: React.PropTypes.string,
        disabled: React.PropTypes.bool,
        checked: React.PropTypes.bool,

        //Set by radioGroup
        name: React.PropTypes.string,
        onChange: React.PropTypes.func,
    },
    _onChange() {
        this.props.onChange(this.props.value);
    },
    render() {
        return (

                <input disabled={this.props.disabled} checked={this.props.checked} onChange={this._onChange} type="radio" name={this.props.name} />

                    {this.props.label}

        );
    },
});

const RadioButtonGroup = React.createClass({
    propTypes: {
        name: React.PropTypes.string,
        onChange: React.PropTypes.func,
    },
    getDefaultProps() {
        return {
            name: _.uniqueId('bilprospekt-ui-radio'),
        };
    },
    _onRadioChange(value) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(value);
        }
    },
    render() {
        const children = React.Children.map(this.props.children, (child) => {
            return React.cloneElement(child, {name: this.props.name, onChange: this._onRadioChange});
        });

        return (

                {children}

        )
    },
});

export default {
    RadioButton,
    RadioButtonGroup,
};
<|endoftext|>


<commit_before>import { combineReducers } from 'redux'

import {
  SELECT_FILE,
  UNSELECT_FILE,
  UNSELECT_ALL,
  SHOW_FILE_ACTIONMENU,
  HIDE_FILE_ACTIONMENU
} from '../actions'

const selected = (state = [], action) => {
  switch (action.type) {
    case SELECT_FILE:
      return [
        ...state,
        action.id
      ]
    case UNSELECT_FILE:
      let idx = state.indexOf(action.id)
      return [
        ...state.slice(0, idx),
        ...state.slice(idx + 1)
      ]
    case UNSELECT_ALL:
      return []
    default:
      return state
  }
}

const showFileActionMenu = (state = false, action) => {
  switch (action.type) {
    case SHOW_FILE_ACTIONMENU:
      return true
    case HIDE_FILE_ACTIONMENU:
      return false
    default:
      return state
  }
}

const actionable = (state = null, action) => {
  switch (action.type) {
    case SHOW_FILE_ACTIONMENU:
      return action.id || null
    case HIDE_FILE_ACTIONMENU:
      return null
    default:
      return state
  }
}

const actionMenu = (state = { openWith: false }, action) => {
  const newState = {}
  switch (action.type) {
    case 'SHOW_SPINNER':
      newState[action.menu] = true
      return Object.assign({}, state, newState)
    case 'HIDE_SPINNER':
      newState[action.menu] = false
      return Object.assign({}, state, newState)
    default:
      return state
  }
}

export default combineReducers({
  selected,
  showFileActionMenu,
  actionable,
  actionMenu
})
<commit_msg>[fix] Selection was not cleared when opening a new view<commit_after>import { combineReducers } from 'redux'

import {
  OPEN_FOLDER,
  SELECT_FILE,
  UNSELECT_FILE,
  UNSELECT_ALL,
  SHOW_FILE_ACTIONMENU,
  HIDE_FILE_ACTIONMENU
} from '../actions'

const selected = (state = [], action) => {
  switch (action.type) {
    case SELECT_FILE:
      return [
        ...state,
        action.id
      ]
    case UNSELECT_FILE:
      let idx = state.indexOf(action.id)
      return [
        ...state.slice(0, idx),
        ...state.slice(idx + 1)
      ]
    case OPEN_FOLDER:
    case UNSELECT_ALL:
      return []
    default:
      return state
  }
}

const showFileActionMenu = (state = false, action) => {
  switch (action.type) {
    case SHOW_FILE_ACTIONMENU:
      return true
    case HIDE_FILE_ACTIONMENU:
      return false
    default:
      return state
  }
}

const actionable = (state = null, action) => {
  switch (action.type) {
    case SHOW_FILE_ACTIONMENU:
      return action.id || null
    case HIDE_FILE_ACTIONMENU:
      return null
    default:
      return state
  }
}

const actionMenu = (state = { openWith: false }, action) => {
  const newState = {}
  switch (action.type) {
    case 'SHOW_SPINNER':
      newState[action.menu] = true
      return Object.assign({}, state, newState)
    case 'HIDE_SPINNER':
      newState[action.menu] = false
      return Object.assign({}, state, newState)
    default:
      return state
  }
}

export default combineReducers({
  selected,
  showFileActionMenu,
  actionable,
  actionMenu
})
<|endoftext|>


<commit_before>var RepoSearch = function(el) {
  this.label_text = 'Search ' + el.children('h1').contents().filter(function() {
    return (this.nodeType === 3);
  })[0].nodeValue;
  this.label_color = '#666';
  this.original_content_fragment = document.createDocumentFragment();
  this.search_input_css = { 'width': '24em', 'padding': '3px 11px 0 0', 'color': this.label_color };
  this.search_div_css = { 'margin': '5px 0 10px 0' };
  this.stored_repositories = this.loadStoredRepositories();
  this.initialize(el);
}

RepoSearch.InstanceMethods = {
  initialize: function(el) {
    if (this.repos = $(el)) {
      this.addSearchInputs();
      this.addSearchText();
      this.original_content_fragment.appendChild(this.repos.children('ul')[0].cloneNode(true))
    }
  },

  addSearchInputs: function() {
    var div = $(document.createElement('div'))
          .css(this.search_div_css).addClass('repo_search');

    var input = $(document.createElement('input'))
          .attr({ 'type': 'text', 'value': this.label_text })
          .css(this.search_input_css);
    div.append(input);
    this.attachSearchInputEvents(input);
    this.repos.children('ul').before(div);
  },

  addSearchText: function() {
    var span, key, description_text,
        lis = this.repos.children('ul').children('li');

    for(var i = 0; i < lis.length; i++) {
      description_text = '';
      li = $(lis[i]);
      key = li.find('b > a').attr('href').replace(/(?:^\/|http:\/\/github.com\/)(.*)\/tree/, '$1')
      if (this.stored_repositories[key]) {
        description_text = (this.stored_repositories[key]['description'] || '');
      }
      span = $(document.createElement('span'))
        .addClass('search_text')
        .hide()
        .text((key + ' ' + $.trim(description_text)).toLowerCase());
      li.append(span);
      this.addDescription(li, description_text);
    }
  },

  addDescription: function(li, description) {
    if (description !== '') {
      var div = $(document.createElement('div'))
        .addClass('description')
        .css({'border-top': '1px solid #333', 'margin-top': '5px', 'padding': '2px 5px 2px 5px'})
        .hide();
      var p = $(document.createElement('p'))
        .css({'font-size': '12px', 'color': '#333'})
        .text(description);
      div.append(p);
      li.append(div);
    }
  },

  attachSearchInputEvents: function(input) {
    var self = this;
    input.keyup(function(e) {
      var el = $(e.target);
      if(el.attr('value') === '') {
        el.removeClass('dirty');
      } else {
        el.addClass('dirty');
      }
      self.performSearch($(e.target));
    });
    input.blur(function(e) {
      var el = $(e.target);
      if(!el.hasClass('dirty')) {
        el.attr('value', self.label_text);
        el.css('color', self.label_color);
      }
    });
    input.focus(function(e) {
      var el = $(e.target);
      if(!el.hasClass('dirty')) {
        el.attr('value', '');
        el.css('color', '#000');
      }
    });
  },

  performSearch: function(el) {
    var token = el.attr('value'), document_ul = this.repos.children('ul'), ul;
    if (token !== '') {
      var score,
          scores = [],
          lis = document_ul.children('li'),
          fragment = document.createDocumentFragment();

      ul = $(fragment.appendChild(document.createElement('ul')));
      for(var i = 0; i < lis.length; i++) {
        score = lis[i].getElementsByClassName('search_text')[0].innerHTML.score(token);
        scores.push([score, i]);
      }
      scores = scores.sort().reverse();
      for(var i = 0; i < scores.length; i++) {
        li = lis[scores[i][1]];
        if(scores[i][0]) {
          li.style.display = '';
        } else {
          li.style.display = 'none';
        }
        ul[0].appendChild(li);
      }
      ul.find('div.description').show();
    } else {
      ul = $(this.original_content_fragment.childNodes[0].cloneNode(true));
    }
    document_ul.replaceWith(ul);
  },

  loadStoredRepositories: function() {
    return JSON.parse(localStorage.getItem('repositories') || "{}");
  }
}

$.extend(RepoSearch.prototype, RepoSearch.InstanceMethods);
delete RepoSearch.InstanceMethods;

$('div.repos').each(function() {
  new RepoSearch($(this));
})

<commit_msg>Using json_search to perform the repo search.<commit_after>var RepoSearch = function(el) {
  this.label_text = 'Search ' + el.children('h1').contents().filter(function() {
    return (this.nodeType === 3);
  })[0].nodeValue;
  this.label_color = '#666';
  this.original_content_fragment = document.createDocumentFragment();
  this.search_input_css = { 'width': '24em', 'padding': '3px 11px 0 0', 'color': this.label_color };
  this.search_div_css = { 'margin': '5px 0 10px 0' };
  this.stored_repositories = this.loadStoredRepositories();
  this.initialize(el);
}

RepoSearch.InstanceMethods = {
  initialize: function(el) {
    if (this.repos = $(el)) {
      this.addSearchInputs();
      this.buildJsonSearchObject()
      this.createJSONSearch();
      this.original_content_fragment.appendChild(this.repos.children('ul')[0].cloneNode(true))
    }
  },

  addSearchInputs: function() {
    var div = $(document.createElement('div'))
          .css(this.search_div_css).addClass('repo_search');

    var input = $(document.createElement('input'))
          .attr({ 'type': 'text', 'value': this.label_text })
          .css(this.search_input_css);
    div.append(input);
    this.attachSearchInputEvents(input);
    this.repos.children('ul').before(div);
  },

  buildJsonSearchObject: function() {
    var li, key, row, search_data = [], lis = this.repos.children('ul').children('li');
    for(var i = 0; i < lis.length; i++) {
      li = $(lis[i]);
      key = li.find('b > a').attr('href').replace(/(?:^\/|http:\/\/github.com\/)(.*)\/tree/, '$1')
      row = {
        'class': key.replace(/\//, '_'),
        user: $.trim(key.split(/\//)[0]),
        repo: $.trim(key.split(/\//)[1]),
        description: ''
      }
      if (this.stored_repositories[key]) {
        row['description'] = (this.stored_repositories[key]['description'] || '');
      }
      li.addClass(row['class']);
      this.addDescription(li, row['description']);
      search_data.push(row);
    }
    this.search_data = search_data;
  },

  createJSONSearch: function() {
    this.json_search = new JSONSearch({
      fields: {
        user: 'prefix',
        repo: 'prefix',
        description: 'word_prefix'
      },
      ranks: {
        user: 1,
        repo: 2,
        description: 0
      }
    })
  },

  addDescription: function(li, description) {
    if (description !== '') {
      var div = $(document.createElement('div'))
        .addClass('description')
        .css({'border-top': '1px solid #333', 'margin-top': '5px', 'padding': '2px 5px 2px 5px'})
        .hide();
      var p = $(document.createElement('p'))
        .css({'font-size': '12px', 'color': '#333'})
        .text(description);
      div.append(p);
      li.append(div);
    }
  },

  attachSearchInputEvents: function(input) {
    var self = this;
    input.keyup(function(e) {
      var el = $(e.target);
      if(el.attr('value') === '') {
        el.removeClass('dirty');
      } else {
        el.addClass('dirty');
      }
      self.performSearch($(e.target));
    });
    input.blur(function(e) {
      var el = $(e.target);
      if(!el.hasClass('dirty')) {
        el.attr('value', self.label_text);
        el.css('color', self.label_color);
      }
    });
    input.focus(function(e) {
      var el = $(e.target);
      if(!el.hasClass('dirty')) {
        el.attr('value', '');
        el.css('color', '#000');
      }
    });
  },

  performSearch: function(el) {
    var token = el.attr('value'), document_ul = this.repos.children('ul'), ul
    if(token !== '') {
      // Ugly but substantially faster than a pure JQuery implementation
      var description, li, lis = [], results, fragment = document.createDocumentFragment();
      ul = $(fragment.appendChild(document.createElement('ul')));
      results = this.json_search.getResults(token, this.search_data)
      search_data_ordered_by_results = $.unique(results.concat(this.search_data))

      for(var i = 0; i < search_data_ordered_by_results.length; i++) {
        li = document_ul[0].getElementsByClassName(search_data_ordered_by_results[i]['class'])[0];
        description = li.getElementsByClassName('description')[0];
        if(description) {
          description.style.display = '';
        }
        li.style.display = 'none'
        ul[0].appendChild(li);
        lis.push(li);
      }
      for(var i = 0; i < results.length; i++) {
        lis[i].style.display = ''
      }
    } else {
      ul = $(this.original_content_fragment.childNodes[0].cloneNode(true));
    }
    document_ul.replaceWith(ul);
  },

  loadStoredRepositories: function() {
    return JSON.parse(localStorage.getItem('repositories') || "{}");
  }
}

$.extend(RepoSearch.prototype, RepoSearch.InstanceMethods);
delete RepoSearch.InstanceMethods;

$('div.repos').each(function() {
  new RepoSearch($(this));
})

<|endoftext|>


<commit_before>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _table = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    that.clean_table = function () {
        $('#data-table > thead').empty();
        $('#data-table > tbody').empty();
        $('#filtered-thead').empty();
        $('#filtered-tbody').empty();
    };

    that.init_table = function () {
        _utils.create_preloader('Wczytuj tabel');
        if ( !_store.active_filtered() ) {
            create_thead();
            create_tbody();
            _gui.make_zebra();
        } else {
            create_filtered_thead();
            create_filtered_tbody();
        }
        _utils.clean_preloader();
    };

    that.add_node = function ( parent_id ) {
        var children = _store.active_rows().filter( function ( e ) {
            return e['data']['parent'] === parent_id;
        });

        add_rows( children );
        _gui.make_zebra();
    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function create_thead() {
        var schema = _store.active_columns();
        var total = _store.active_rows()['total'];
        var html = [ '
' ];

        // create header
        schema.forEach( function ( column ) {
            html.push( '' );
            html.push( column['label'] );
            html.push( '	' );
        });

        html.push( '
' );

        // create total row
        if( !!total ) {
            html.push( '
' );

            schema.forEach( function ( column ) {
                html.push( '' );
                html.push( total['data'][ column['key'] ] );
                html.push( '	' );
            });

            html.push( '
' );
        }
        $('#data-table > thead').append( html.join('') );
    }

    function create_tbody() {
        var level = 'a';
        var hashed_list = _utils.hash_list( _store.active_rows() );
        var selected_node;

        while( !!hashed_list[ level ] ) {
            if( level === 'a' ) {
                add_top_level( hashed_list[ level ] );
            }
            else {
                add_rows( hashed_list[ level ] );
            }

            level = _utils.next_letter( level );
        }

        // apply node selection(if there is selected node) to css classes
        selected_node = _store.active_rows().filter( function ( e ) {
            return e['state']['selected'];
        });
        if ( selected_node.length > 0 ) {
            apply_selection( selected_node[0]['data']['idef'] );
        }
    }

    function add_top_level( data ) {
        var i, len = data.length;
        var schema = _store.active_columns();

        for( i = 0; i < len; ++i ) {
            $('#data-table > tbody').append( generate_row({
                node: data[i],
                index: i,
                schema: schema
            }));
        }
    }

    function add_rows( data ) {
        var i = data.length - 1;
        var schema = _store.active_columns();
        var parent;

        for( ; i >= 0; i -= 1 ) {
            parent = $( '#' + data[i]['data']['parent'] );
            if( parent.attr( 'data-open' ) === 'false' ) {
                continue;
            }
            parent.after( generate_row({
                node: data[i],
                schema: schema
            }));
        }
//        _gui.make_zebra();
    }

    // generate a single table row
    function generate_row( args ) {
        var node = args['node'];
        var data = node['data'];
        var schema = args['schema'];
        var is_open = node['state']['open'];
        var is_selected = node['state']['selected'];
        var html = [];
        var row;

        // row definition
        html.push( '
' );

        // cells definition
        // TODO >> it can be sligthly slower than for loop - test it
        schema.forEach( function ( column ) {
            html.push( '' : '">' );
            html.push( data[column['key']] );
            html.push( '	' );
        });

        html.push( '
' );

        // create & arm row
        row = $( html.join('') );
        row.click( function ( event ) {
            // update css classes connected with node selection
            apply_selection( $(this).attr('id') );

            // open/close a subtree if it's a-level or already selected/open
            open_close_subtree( $(this), a_parent( $(this) ) );

//            _gui.make_zebra();
        });

        return row;
    }

    function create_filtered_thead() {
        var schema = _store.active_columns();
        var html = [];

        html.push( '
' );
        schema.forEach( function ( column ) {
            html.push( '' );
            html.push( column['label'], '	' );
        });
        html.push( '
' );

        $('#filtered-thead').append( html.join('') );
    }

    function create_filtered_tbody() {
        var copy_rows = [];
        var schema = _store.active_columns();
        $.extend( true, copy_rows, _store.active_rows() );

        copy_rows.sort( function ( a, b ) {
                     var return_value;
                     if ( a['data']['idef_sort']  b['data']['idef_sort'] ) {
                         return_value = 1;
                     } else {
                         return_value = 0;
                     }
                return return_value;
            })
            .forEach( function ( row ) {
                //var parent = find_parent( row['data']['idef'] );
                var new_node = generate_filtered_row({
                                    node: row,
                                    schema: schema
                                });

                /*if ( !!parent ) {
                    parent.after( new_node );
                }
                else {
                    $('#filtered-tbody').prepend( new_node );
                }*/
                $('#filtered-tbody').append( new_node );
            });

        /*var level;
        var hashed_list = _utils.hash_list( _store.active_rows() );

        for( level in hashed_list ) {
            if( hashed_list.hasOwnProperty( level )) {
                add_filtered_rows( hashed_list[ level ] );
            }
        }*/
    }

    function add_filtered_rows( data ) {
        var schema = _store.active_columns();

        data.sort( function ( a, b ) {
                var return_value;
                if ( a['data']['idef_sort']  b['data']['idef_sort'] ) {
                    return_value = 1;
                } else {
                    return_value = 0;
                }

                return return_value;
            })
            .forEach( function ( row ) {
                var parent = find_parent( row['data']['idef'] );
                var new_node = generate_filtered_row({
                                    node: row,
                                    schema: schema
                                });

                if ( !!parent ) {
                    parent.after( new_node );
                }
                else {
                    $('#filtered-tbody').prepend( new_node );
                }
            });
    }

    function generate_filtered_row( args ) {
        var node = args['node'];
        var breadcrumb = node['breadcrumb'] || '';
        var html = [];

        // breadcrumb
        html.push( '
' );
        html.push( '');
        html.push( breadcrumb );
        html.push( '	' );
        html.push( '
');

        // filtered row
        html.push( '
' );
        args['schema'].forEach( function ( column ) {
            html.push( '' );
            html.push( node['data'][ column['key'] ] );
            html.push('	');
        });
        html.push( '
' );

        return $( html.join('') );
    }

    function find_parent( id ) {
        var parent_id = _utils.get_parent_id( id );
        var parent;

        while ( !!parent_id ) {
            parent = $( '#' + parent_id );
            if ( !!parent.length ) {
                return parent;
            }
            parent_id = _utils.get_parent_id( parent_id );
        }
        // if parent not found, return ''
        return null;
    }

    function apply_selection( id ) {
        var node = $('#' + id);

        // a-level parent
        var a_root = a_parent( node );
        var a_root_id = a_root.attr('id');
        // next a-level node
        var a_root_index = parseInt( a_root.attr( 'data-index' ), 10 );
        var next = $('tr[data-index='+ (a_root_index + 1) +']');

        // dim everything outside this a-rooted subtree
        a_root
            .siblings()
            .addClass('dim')
            .end()
            .removeClass('dim');

        // make a-root background black
        $('tr.root').removeClass('root');
        a_root.addClass('root');

        // highlight the subtree
        _utils.with_subtree( a_root.attr('id'), function () {
            // uses 'this' instead of '$(this)' for fun.call reason
            this.removeClass( 'dim' );
        });

        // add the bottom border
        $('.next').removeClass('next');
        next.addClass('next');
    }

    function open_close_subtree( node, root ) {
        var a_root = root || a_parent( node );
        var a_root_id = a_root.attr('id');
        var is_a_open     = a_root.attr( 'data-open' );
        var is_a_selected = a_root.attr( 'data-selected' );
        var id = node.attr('id');
        var children;
        var previously_selected_id;

        if ( is_a_selected === is_a_open ) {
            // if the node is closed
            if( node.attr( 'data-open' ) === 'false' ) {

                // if children are hidden
                if( $('.'+id).length !== 0 ) {
                    _utils.with_subtree( id, $.fn.show );
                }
                // if children not loaded yet
                else {
                    _db.download_node( id );
                }

                // if there is previously selected node, unselect it in _store
                previously_selected_id = $('tr[data-selected=true]').attr('id');
                if ( !!previously_selected_id ) {
                    _store.set_selected( previously_selected_id, false );
                }

                // mark subtree as open
                _store.set_open( id, true );
                node.attr( 'data-open', 'true' );

                // clear selected attributes and set selection to clicked tree
                _store.set_selected( a_root_id, true );
                $('tr[data-selected=true]').attr('data-selected', 'false');
                a_root.attr('data-selected', 'true');
            }
            // the node is closed
            else {
                // hide subtree
                _utils.with_subtree( id, $.fn.hide );

                // mark subtree as closed
                _store.set_open( id, false );
                node.attr( 'data-open', 'false' );

                // if it's a-level node - clear the css highlight/dim
                if( node.hasClass( 'a' ) ) {
                    node.removeClass( 'root' );
                    $('.dim').removeClass('dim');
                    $('.next').removeClass('next');

                    // clear selected attributes and set selection to clicked tree
                    _store.set_selected( a_root_id, false );
                    $('tr[data-selected=true]').attr('data-selected', 'false');
                }
            }
        }
        else if( a_root.attr( 'data-selected' ) === 'false' ) {
            // unselect previously selected node in _store
            previously_selected_id = $('tr[data-selected=true]').attr('id');
            _store.set_selected( previously_selected_id, false );

            _store.set_selected( a_root_id, true );
            $('tr[data-selected=true]').attr('data-selected', 'false');
            a_root.attr('data-selected', 'true');
        }
    }

    // return a-level parent of a given node
    function a_parent( node ) {
        if( node.hasClass( 'a' ) ) {
            return node;
        }
        var prev = node.prev();

        return prev.hasClass('a') ? prev : a_parent( prev );
    }

})();
<commit_msg>Filter code cleaned<commit_after>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _table = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    that.clean_table = function () {
        $('#data-table > thead').empty();
        $('#data-table > tbody').empty();
        $('#filtered-thead').empty();
        $('#filtered-tbody').empty();
    };

    that.init_table = function () {
        _utils.create_preloader('Wczytuj tabel');
        if ( !_store.active_filtered() ) {
            create_thead();
            create_tbody();
            _gui.make_zebra();
        } else {
            create_filtered_thead();
            create_filtered_tbody();
        }
        _utils.clean_preloader();
    };

    that.add_node = function ( parent_id ) {
        var children = _store.active_rows().filter( function ( e ) {
            return e['data']['parent'] === parent_id;
        });

        add_rows( children );
        _gui.make_zebra();
    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function create_thead() {
        var schema = _store.active_columns();
        var total = _store.active_rows()['total'];
        var html = [ '
' ];

        // create header
        schema.forEach( function ( column ) {
            html.push( '' );
            html.push( column['label'] );
            html.push( '	' );
        });

        html.push( '
' );

        // create total row
        if( !!total ) {
            html.push( '
' );

            schema.forEach( function ( column ) {
                html.push( '' );
                html.push( total['data'][ column['key'] ] );
                html.push( '	' );
            });

            html.push( '
' );
        }
        $('#data-table > thead').append( html.join('') );
    }

    function create_tbody() {
        var level = 'a';
        var hashed_list = _utils.hash_list( _store.active_rows() );
        var selected_node;

        while( !!hashed_list[ level ] ) {
            if( level === 'a' ) {
                add_top_level( hashed_list[ level ] );
            }
            else {
                add_rows( hashed_list[ level ] );
            }

            level = _utils.next_letter( level );
        }

        // apply node selection(if there is selected node) to css classes
        selected_node = _store.active_rows().filter( function ( e ) {
            return e['state']['selected'];
        });
        if ( selected_node.length > 0 ) {
            apply_selection( selected_node[0]['data']['idef'] );
        }
    }

    function add_top_level( data ) {
        var i, len = data.length;
        var schema = _store.active_columns();

        for( i = 0; i < len; ++i ) {
            $('#data-table > tbody').append( generate_row({
                node: data[i],
                index: i,
                schema: schema
            }));
        }
    }

    function add_rows( data ) {
        var i = data.length - 1;
        var schema = _store.active_columns();
        var parent;

        for( ; i >= 0; i -= 1 ) {
            parent = $( '#' + data[i]['data']['parent'] );
            if( parent.attr( 'data-open' ) === 'false' ) {
                continue;
            }
            parent.after( generate_row({
                node: data[i],
                schema: schema
            }));
        }
//        _gui.make_zebra();
    }

    // generate a single table row
    function generate_row( args ) {
        var node = args['node'];
        var data = node['data'];
        var schema = args['schema'];
        var is_open = node['state']['open'];
        var is_selected = node['state']['selected'];
        var html = [];
        var row;

        // row definition
        html.push( '
' );

        // cells definition
        // TODO >> it can be sligthly slower than for loop - test it
        schema.forEach( function ( column ) {
            html.push( '' : '">' );
            html.push( data[column['key']] );
            html.push( '	' );
        });

        html.push( '
' );

        // create & arm row
        row = $( html.join('') );
        row.click( function ( event ) {
            // update css classes connected with node selection
            apply_selection( $(this).attr('id') );

            // open/close a subtree if it's a-level or already selected/open
            open_close_subtree( $(this), a_parent( $(this) ) );

//            _gui.make_zebra();
        });

        return row;
    }

    function create_filtered_thead() {
        var schema = _store.active_columns();
        var html = [];

        html.push( '
' );
        schema.forEach( function ( column ) {
            html.push( '' );
            html.push( column['label'], '	' );
        });
        html.push( '
' );

        $('#filtered-thead').append( html.join('') );
    }

    function create_filtered_tbody() {
        var schema = _store.active_columns();
        // deep copy is made to ensure that _store is not changed by sort
        var rows_copy = [];
        $.extend( true, rows_copy, _store.active_rows() );

        rows_copy.sort( function ( a, b ) {
                     var return_value;
                     if ( a['data']['idef_sort']  b['data']['idef_sort'] ) {
                         return_value = 1;
                     } else {
                         return_value = 0;
                     }
                return return_value;
            })
            .forEach( function ( row ) {
                var new_node = generate_filtered_row({
                                    node: row,
                                    schema: schema
                                });
                $('#filtered-tbody').append( new_node );
            });
    }

    function generate_filtered_row( args ) {
        var node = args['node'];
        var breadcrumb = node['breadcrumb'] || '';
        var html = [];

        // breadcrumb
        html.push( '
' );
        html.push( '');
        html.push( breadcrumb );
        html.push( '	' );
        html.push( '
');

        // filtered row
        html.push( '
' );
        args['schema'].forEach( function ( column ) {
            html.push( '' );
            html.push( node['data'][ column['key'] ] );
            html.push('	');
        });
        html.push( '
' );

        return $( html.join('') );
    }

    function find_parent( id ) {
        var parent_id = _utils.get_parent_id( id );
        var parent;

        while ( !!parent_id ) {
            parent = $( '#' + parent_id );
            if ( !!parent.length ) {
                return parent;
            }
            parent_id = _utils.get_parent_id( parent_id );
        }
        // if parent not found, return ''
        return null;
    }

    function apply_selection( id ) {
        var node = $('#' + id);

        // a-level parent
        var a_root = a_parent( node );
        var a_root_id = a_root.attr('id');
        // next a-level node
        var a_root_index = parseInt( a_root.attr( 'data-index' ), 10 );
        var next = $('tr[data-index='+ (a_root_index + 1) +']');

        // dim everything outside this a-rooted subtree
        a_root
            .siblings()
            .addClass('dim')
            .end()
            .removeClass('dim');

        // make a-root background black
        $('tr.root').removeClass('root');
        a_root.addClass('root');

        // highlight the subtree
        _utils.with_subtree( a_root.attr('id'), function () {
            // uses 'this' instead of '$(this)' for fun.call reason
            this.removeClass( 'dim' );
        });

        // add the bottom border
        $('.next').removeClass('next');
        next.addClass('next');
    }

    function open_close_subtree( node, root ) {
        var a_root = root || a_parent( node );
        var a_root_id = a_root.attr('id');
        var is_a_open     = a_root.attr( 'data-open' );
        var is_a_selected = a_root.attr( 'data-selected' );
        var id = node.attr('id');
        var children;
        var previously_selected_id;

        if ( is_a_selected === is_a_open ) {
            // if the node is closed
            if( node.attr( 'data-open' ) === 'false' ) {

                // if children are hidden
                if( $('.'+id).length !== 0 ) {
                    _utils.with_subtree( id, $.fn.show );
                }
                // if children not loaded yet
                else {
                    _db.download_node( id );
                }

                // if there is previously selected node, unselect it in _store
                previously_selected_id = $('tr[data-selected=true]').attr('id');
                if ( !!previously_selected_id ) {
                    _store.set_selected( previously_selected_id, false );
                }

                // mark subtree as open
                _store.set_open( id, true );
                node.attr( 'data-open', 'true' );

                // clear selected attributes and set selection to clicked tree
                _store.set_selected( a_root_id, true );
                $('tr[data-selected=true]').attr('data-selected', 'false');
                a_root.attr('data-selected', 'true');
            }
            // the node is closed
            else {
                // hide subtree
                _utils.with_subtree( id, $.fn.hide );

                // mark subtree as closed
                _store.set_open( id, false );
                node.attr( 'data-open', 'false' );

                // if it's a-level node - clear the css highlight/dim
                if( node.hasClass( 'a' ) ) {
                    node.removeClass( 'root' );
                    $('.dim').removeClass('dim');
                    $('.next').removeClass('next');

                    // clear selected attributes and set selection to clicked tree
                    _store.set_selected( a_root_id, false );
                    $('tr[data-selected=true]').attr('data-selected', 'false');
                }
            }
        }
        else if( a_root.attr( 'data-selected' ) === 'false' ) {
            // unselect previously selected node in _store
            previously_selected_id = $('tr[data-selected=true]').attr('id');
            _store.set_selected( previously_selected_id, false );

            _store.set_selected( a_root_id, true );
            $('tr[data-selected=true]').attr('data-selected', 'false');
            a_root.attr('data-selected', 'true');
        }
    }

    // return a-level parent of a given node
    function a_parent( node ) {
        if( node.hasClass( 'a' ) ) {
            return node;
        }
        var prev = node.prev();

        return prev.hasClass('a') ? prev : a_parent( prev );
    }

})();
<|endoftext|>


<commit_before>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _table = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    that.clean_table = function () {
        $('table').empty();
    };

    that.init_table = function () {
        // TODO header generation to be implemented
        create_thead();
        create_tbody();

        _gui.make_zebra();
    };

    that.add_node = function ( parent_id ) {
        var children = _store.active_rows().filter( function ( e ) {
            return e['data']['parent'] === parent_id;
        });

        add_rows( children );
    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function create_tbody() {
        var level = 'a';
        var hashed_list = _utils.hash_list( _store.active_rows() );

        while( !!hashed_list[ level ] ) {
            if( level === 'a' ) {
                add_top_level( hashed_list[ level ] );
            }
            else {
                add_rows( hashed_list[ level ] );
            }

            level = _utils.next_letter( level );
        }
    }

    function add_top_level( data ) {
        var i, len = data.length;
        var schema = _store.basic_schema();

        for( i = 0; i < len; ++i ) {
            $('tbody').append( generate_row({
                node: data[i],
                index: i,
                schema: schema
            }));
        }
    }

    function add_rows( data ) {
        var i = data.length - 1;
        var schema = _store.basic_schema();
        var parent = $( '#' + data[0]['data']['parent'] );

        for( ; i >= 0; i -= 1 ) {
            parent.after( generate_row({
                node: data[i],
                schema: schema
            }));
        }
    }

    // generate a single table row
    function generate_row( args ) {
        var node = args['node'];
        var data = node['data'];
        var schema = args['schema'];
        var is_open = node['state']['open'];
        var is_selected = node['state']['selected'];
        var html = [];
        var row;

        // row definition
        html.push( '
' );

        // cells definition
        // TODO >> it can be sligthly slower than for loop - test it
        schema.forEach( function ( column ) {
            html.push( '' : ' click">' );
            html.push( data[column['key']] );
            html.push( '	' );
        });

        html.push( '
' );

        // create & arm row
        row = $( html.join('') );
        row.click( function ( event ) {
            // a-level parent
            var a_root = a_parent( $(this) );
            var a_root_id = a_root.attr('id');
            // next a-level node
            var a_root_index = parseInt( a_root.attr( 'data-index' ), 10 );
            var next = $('tr[data-index='+ (a_root_index + 1) +']');

            // dim everything outside this a-rooted subtree
            a_root
                .siblings()
                .not(':hidden')
                .addClass('dim');

            // make a-root background black
            $('tr.root').removeClass('root');
            a_root.addClass('root');

            // highlight the subtree
            with_subtree( a_root.attr('id'), function () {
                // uses 'this' instead of '$(this)' for fun.call reason
                // TODO do it with just one css class if possible
                this.addClass( 'highlight' );
                this.removeClass( 'dim' );
            });

            // add the bottom border
            $('.next').removeClass('next');
            next.addClass('next');

            // open/close a subtree if it's a-level or already selected/open
            open_close_subtree( $(this), a_root );

            // clear selected attributes and set selection to clicked tree
            _store.set_selected( a_root_id );
            $('tr[data-selected=true]').attr('data-selected', 'false');
            a_root.attr('data-selected', 'true');

            _gui.make_zebra();
        });

        return row;
    }

    function open_close_subtree( node, root ) {
        var a_root = root || a_parent( node );
        var is_a_open     = a_root.attr( 'data-open' );
        var is_a_selected = a_root.attr( 'data-selected' );
        var id = node.attr('id');
        var children;

        if ( is_a_selected === is_a_open ) {
            // if the node is closed
            if( node.attr( 'data-open' ) === 'false' ) {

                // if children are hidden
                if( $('.'+id).length !== 0 ) {
                    with_subtree( id, $.fn.show );
                }
                // if children not loaded yet
                else {
                    _db.download_node( id );
                }

                // mark subtree as open
                _store.set_open( id, true );
                node.attr( 'data-open', 'true' );
            }
            // the node is closed
            else {
                // hide subtree
                with_subtree( id, $.fn.hide );

                // mark subtree as closed
                _store.set_open( id, false );
                node.attr( 'data-open', 'false' );

                // if it's a-level node - clear the css highlight/dim
                if( node.hasClass( 'a' ) ) {
                    node.removeClass( 'root' );
                    $('.dim').removeClass('dim');
                    $('.highlight').removeClass('highlight');
                    $('.next').removeClass('next');
                }
            }
        }
    }

    // return a-level parent of a given node
    function a_parent( node ) {
        if( node.hasClass( 'a' ) ) {
            return node;
        }
        var prev = node.prev();

        return prev.hasClass('a') ? prev : a_parent( prev );
    }

    // go through the subtree of id-node and do fun
    function with_subtree( id, fun ) {
        $('tr.'+id).each( function () {
            with_subtree( $(this).attr('id'), fun );
            fun.call( $(this) );
        });
    }

})();
<commit_msg>Debugging continued<commit_after>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _table = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    that.clean_table = function () {
        $('table').empty();
    };

    that.init_table = function () {
        // TODO header generation to be implemented
        // create_thead();
        create_tbody();

        _gui.make_zebra();
    };

    that.add_node = function ( parent_id ) {
        var children = _store.active_rows().filter( function ( e ) {
            return e['data']['parent'] === parent_id;
        });

        add_rows( children );
    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function create_tbody() {
        var level = 'a';
        var hashed_list = _utils.hash_list( _store.active_rows() );

        while( !!hashed_list[ level ] ) {
            if( level === 'a' ) {
                add_top_level( hashed_list[ level ] );
            }
            else {
                add_rows( hashed_list[ level ] );
            }

            level = _utils.next_letter( level );
        }
    }

    function add_top_level( data ) {
        var i, len = data.length;
        var schema = _store.basic_schema();

        for( i = 0; i < len; ++i ) {
            $('tbody').append( generate_row({
                node: data[i],
                index: i,
                schema: schema
            }));
        }
    }

    function add_rows( data ) {
        var i = data.length - 1;
        var schema = _store.basic_schema();
        var parent = $( '#' + data[0]['data']['parent'] );

        for( ; i >= 0; i -= 1 ) {
            parent.after( generate_row({
                node: data[i],
                schema: schema
            }));
        }
    }

    // generate a single table row
    function generate_row( args ) {
        var node = args['node'];
        var data = node['data'];
        var schema = args['schema'];
        var is_open = node['state']['open'];
        var is_selected = node['state']['selected'];
        var html = [];
        var row;

        // row definition
        html.push( '
' );

        // cells definition
        // TODO >> it can be sligthly slower than for loop - test it
        schema.forEach( function ( column ) {
            html.push( '' : ' click">' );
            html.push( data[column['key']] );
            html.push( '	' );
        });

        html.push( '
' );

        // create & arm row
        row = $( html.join('') );
        row.click( function ( event ) {
            // a-level parent
            var a_root = a_parent( $(this) );
            var a_root_id = a_root.attr('id');
            // next a-level node
            var a_root_index = parseInt( a_root.attr( 'data-index' ), 10 );
            var next = $('tr[data-index='+ (a_root_index + 1) +']');

            // dim everything outside this a-rooted subtree
            a_root
                .siblings()
                .not(':hidden')
                .addClass('dim');

            // make a-root background black
            $('tr.root').removeClass('root');
            a_root.addClass('root');

            // highlight the subtree
            with_subtree( a_root.attr('id'), function () {
                // uses 'this' instead of '$(this)' for fun.call reason
                // TODO do it with just one css class if possible
                this.addClass( 'highlight' );
                this.removeClass( 'dim' );
            });

            // add the bottom border
            $('.next').removeClass('next');
            next.addClass('next');

            // open/close a subtree if it's a-level or already selected/open
            open_close_subtree( $(this), a_root );

            // clear selected attributes and set selection to clicked tree
            _store.set_selected( a_root_id );
            $('tr[data-selected=true]').attr('data-selected', 'false');
            a_root.attr('data-selected', 'true');

            _gui.make_zebra();
        });

        return row;
    }

    function open_close_subtree( node, root ) {
        var a_root = root || a_parent( node );
        var is_a_open     = a_root.attr( 'data-open' );
        var is_a_selected = a_root.attr( 'data-selected' );
        var id = node.attr('id');
        var children;

        if ( is_a_selected === is_a_open ) {
            // if the node is closed
            if( node.attr( 'data-open' ) === 'false' ) {

                // if children are hidden
                if( $('.'+id).length !== 0 ) {
                    with_subtree( id, $.fn.show );
                }
                // if children not loaded yet
                else {
                    _db.download_node( id );
                }

                // mark subtree as open
                _store.set_open( id, true );
                node.attr( 'data-open', 'true' );
            }
            // the node is closed
            else {
                // hide subtree
                with_subtree( id, $.fn.hide );

                // mark subtree as closed
                _store.set_open( id, false );
                node.attr( 'data-open', 'false' );

                // if it's a-level node - clear the css highlight/dim
                if( node.hasClass( 'a' ) ) {
                    node.removeClass( 'root' );
                    $('.dim').removeClass('dim');
                    $('.highlight').removeClass('highlight');
                    $('.next').removeClass('next');
                }
            }
        }
    }

    // return a-level parent of a given node
    function a_parent( node ) {
        if( node.hasClass( 'a' ) ) {
            return node;
        }
        var prev = node.prev();

        return prev.hasClass('a') ? prev : a_parent( prev );
    }

    // go through the subtree of id-node and do fun
    function with_subtree( id, fun ) {
        $('tr.'+id).each( function () {
            with_subtree( $(this).attr('id'), fun );
            fun.call( $(this) );
        });
    }

})();
<|endoftext|>


<commit_before>var roleReserver = require('roleReserver')

roleSpawner = {

    run: function(roomId) {

	    var roomStore = {
	        'W8N68': {
                'harvester': 2,
                'worker': 7,
                'reserver': Object.keys(Memory.claimTargets).length,
                'distanceHarvester': 6,
                //'claimer': 1,
                //'settler': 4,
                //'attacker': 1,
                //'sniper': 1,
	        },
	        'W6N68': {
	            'harvester': 2,
	            'worker': 10,
                'roleClaimEast': 1,
                'roleClaimSEast': 1,
	        }
	    };

	    var store = roomStore[roomId];

        if(!roleReserver.expiringSoon()) {
            store['reserver'] = 0;
        }

	    for(role in store) {
	        var count = store[role];
	        var creeps = _.filter(Game.creeps, (creep) => creep.memory.role == role && creep.memory.home == roomId);
	        if(creeps.length < count) {

	            var build = undefined;
	            switch (role) {
                    case 'harvester':
                        build = roleSpawner.currentHarvesterBuild(roomId);
                        break;
	                case 'worker':
	                    build = roleSpawner.currentWorkerBuild(roomId);
	                    break;
	                case 'roadLayer':
	                    build = roleSpawner.currentWorkerBuild();
	                    break;
	                case 'reserver':
	                    build = roleSpawner.currentReserverBuild();
	                    break;
                    case 'claimer':
                        build = roleSpawner.currentClaimerBuild();
                        break;
                    case 'settler':
                        build = roleSpawner.currentSettlerBuild();
                        break;
                    case 'attacker':
                        build = roleSpawner.currentAttackerBuild();
                        break;
                    case 'distanceHarvester':
                        build = roleSpawner.currentDistanceHarvesterBuild();
                        break;
                    case 'sniper':
                        build = roleSpawner.currentSniperBuild();
                        break;
                    case 'claimEast':
                        build = roleSpawner.currentReserverBuild();
                        break;
                    case 'claimSEast':
                        build = roleSpawner.currentReserverBuild();
                        break;
	            }
                var spawnName = Memory[roomId].spawns[0];

                var targetHome = roomId;
                if(role == 'settler') {
                    targetHome = Memory.expansionTarget;
                }

                console.log('about to spawn ' + role + ' at ' + spawnName + ' in room ' + roomId + ' arg is ' + targetHome + ' build is ' + build);
		        var newName = Game.spawns[spawnName].createCreep(build, undefined, {role: role, home: targetHome});
                if(newName != ERR_BUSY && newName != ERR_NOT_ENOUGH_ENERGY) {
                    console.log('spawning new ' + role + ': ' + newName);
                }
	        }
	    }
    },

    assembleBuild: function(stats) {
        var build = [];
        for(part in stats) {
            for(var i=0; i < stats[part]; i++) {
                var partCode = undefined;
                switch (part) {
                    case 'WORK':
                        partCode = WORK;
                        break;
                    case 'CARRY':
                        partCode = CARRY;
                        break;
                    case 'MOVE':
                        partCode = MOVE;
                        break;
                    case 'ATTACK':
                        partCode = ATTACK;
                        break;
                     case 'RANGED_ATTACK':
                         partCode = RANGED_ATTACK;
                         break;
                }

                build.push(partCode);
            }
        }
        return build;
    },

    currentWorkerBuild: function(roomId) {
        var spawnRoomCapacity = Game.rooms[roomId].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 8,
                MOVE: 6,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 6,
                MOVE: 4,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 4,
                MOVE: 3,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentHarvesterBuild: function(roomId) {
        var spawnRoomCapacity = Game.rooms[roomId].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 6,
                CARRY: 4,
                MOVE: 3,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 4,
                MOVE: 2,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 3,
                CARRY: 3,
                MOVE: 2,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentReserverBuild: function() {
        return [CLAIM, CLAIM, MOVE, MOVE];
    },

    currentClaimerBuild: function() {
        return [CLAIM, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE];
    },

    currentSettlerBuild: function() {
        return roleSpawner.assembleBuild({
            WORK: 4,
            CARRY: 4,
            MOVE: 8,
        })
    },

    currentAttackerBuild: function() {
        return roleSpawner.assembleBuild({
            ATTACK: 10,
            MOVE: 10,
        })
    },

    currentSniperBuild: function() {
        return roleSpawner.assembleBuild({
            RANGED_ATTACK: 1,
            MOVE: 1,
        })
    },

    currentDistanceHarvesterBuild: function() {
        return roleSpawner.assembleBuild({
            WORK: 5, // 500 + 250
            CARRY: 15, // 500 + 500
            MOVE: 10,
        })
    },
}

module.exports = roleSpawner;
<commit_msg>name error<commit_after>var roleReserver = require('roleReserver')

roleSpawner = {

    run: function(roomId) {

	    var roomStore = {
	        'W8N68': {
                'harvester': 2,
                'worker': 7,
                'reserver': Object.keys(Memory.claimTargets).length,
                'distanceHarvester': 6,
                //'claimer': 1,
                //'settler': 4,
                //'attacker': 1,
                //'sniper': 1,
	        },
	        'W6N68': {
	            'harvester': 2,
	            'worker': 10,
                'claimEast': 1,
                'claimSEast': 1,
	        }
	    };

	    var store = roomStore[roomId];

        if(!roleReserver.expiringSoon()) {
            store['reserver'] = 0;
        }

	    for(role in store) {
	        var count = store[role];
	        var creeps = _.filter(Game.creeps, (creep) => creep.memory.role == role && creep.memory.home == roomId);
	        if(creeps.length < count) {

	            var build = undefined;
	            switch (role) {
                    case 'harvester':
                        build = roleSpawner.currentHarvesterBuild(roomId);
                        break;
	                case 'worker':
	                    build = roleSpawner.currentWorkerBuild(roomId);
	                    break;
	                case 'roadLayer':
	                    build = roleSpawner.currentWorkerBuild();
	                    break;
	                case 'reserver':
	                    build = roleSpawner.currentReserverBuild();
	                    break;
                    case 'claimer':
                        build = roleSpawner.currentClaimerBuild();
                        break;
                    case 'settler':
                        build = roleSpawner.currentSettlerBuild();
                        break;
                    case 'attacker':
                        build = roleSpawner.currentAttackerBuild();
                        break;
                    case 'distanceHarvester':
                        build = roleSpawner.currentDistanceHarvesterBuild();
                        break;
                    case 'sniper':
                        build = roleSpawner.currentSniperBuild();
                        break;
                    case 'claimEast':
                        build = roleSpawner.currentReserverBuild();
                        break;
                    case 'claimSEast':
                        build = roleSpawner.currentReserverBuild();
                        break;
	            }
                var spawnName = Memory[roomId].spawns[0];

                var targetHome = roomId;
                if(role == 'settler') {
                    targetHome = Memory.expansionTarget;
                }

                console.log('about to spawn ' + role + ' at ' + spawnName + ' in room ' + roomId + ' arg is ' + targetHome + ' build is ' + build);
		        var newName = Game.spawns[spawnName].createCreep(build, undefined, {role: role, home: targetHome});
                if(newName != ERR_BUSY && newName != ERR_NOT_ENOUGH_ENERGY) {
                    console.log('spawning new ' + role + ': ' + newName);
                }
	        }
	    }
    },

    assembleBuild: function(stats) {
        var build = [];
        for(part in stats) {
            for(var i=0; i < stats[part]; i++) {
                var partCode = undefined;
                switch (part) {
                    case 'WORK':
                        partCode = WORK;
                        break;
                    case 'CARRY':
                        partCode = CARRY;
                        break;
                    case 'MOVE':
                        partCode = MOVE;
                        break;
                    case 'ATTACK':
                        partCode = ATTACK;
                        break;
                     case 'RANGED_ATTACK':
                         partCode = RANGED_ATTACK;
                         break;
                }

                build.push(partCode);
            }
        }
        return build;
    },

    currentWorkerBuild: function(roomId) {
        var spawnRoomCapacity = Game.rooms[roomId].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 8,
                MOVE: 6,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 6,
                MOVE: 4,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 4,
                MOVE: 3,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentHarvesterBuild: function(roomId) {
        var spawnRoomCapacity = Game.rooms[roomId].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 6,
                CARRY: 4,
                MOVE: 3,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 4,
                MOVE: 2,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 3,
                CARRY: 3,
                MOVE: 2,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentReserverBuild: function() {
        return [CLAIM, CLAIM, MOVE, MOVE];
    },

    currentClaimerBuild: function() {
        return [CLAIM, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE];
    },

    currentSettlerBuild: function() {
        return roleSpawner.assembleBuild({
            WORK: 4,
            CARRY: 4,
            MOVE: 8,
        })
    },

    currentAttackerBuild: function() {
        return roleSpawner.assembleBuild({
            ATTACK: 10,
            MOVE: 10,
        })
    },

    currentSniperBuild: function() {
        return roleSpawner.assembleBuild({
            RANGED_ATTACK: 1,
            MOVE: 1,
        })
    },

    currentDistanceHarvesterBuild: function() {
        return roleSpawner.assembleBuild({
            WORK: 5, // 500 + 250
            CARRY: 15, // 500 + 500
            MOVE: 10,
        })
    },
}

module.exports = roleSpawner;
<|endoftext|>