<commit_before>// @flow
import React, {Component} from 'react';
import {Table, Input, Button, Icon} from 'antd';

import InputCell from './InputCell';
import CheckboxCell from './CheckboxCell';
import SelectCell from './SelectCell';
import ColorCell from './ColorCell';
import LineStyleCell from './LineStyleCell';

const isProd = process.env.NODE_ENV === 'production';

//TODO: Таблица с фильтрами обновляется.
//TODO: редактируемые ячейки возвразают [Object]
class Grid extends Component {

  constructor(props) {
    super(props);

    this.handlerFilterChange = ::this.handlerFilterChange;
    this.handlerFilter = ::this.handlerFilter;

    this.state = {
      filterDropdownVisible: false,
      filterValue: {},
      data: null
    };
  }

  columnSorter(dataIndex, a, b) {
    return -(a[dataIndex]  {
            this.setState({
              data: this.filterData(this.props.data, reg)
            });
            console.log('updateFilter');
          }
        }
      }
    }
    return {...item, ...props};
  }

  onChange(pagination, filters, sorter) {
    console.log('params', pagination, filters, sorter);
  }

  findParentElement(el, selector) {
    let popupEl = el;
    while ((popupEl = popupEl.parentElement) !== null) {
      if (popupEl.matches(selector)) {
        return popupEl;
        break;
      }
    }
  }

  handlerFilter(e, reset = false) {
    this.handlerFilterChange(e, reset);

    let filterValue = this.state.filterValue;

    let reg = {};
    for (let dataIndex in filterValue) {
      if (filterValue[dataIndex] !== '') {
        reg[dataIndex] = new RegExp('(' + filterValue[dataIndex] + ')+', 'gi');
      }
    }

    let data = this.filterData(this.props.data, reg);

    this.setState({
      filterDropdownVisible: false,
      data,
      filterValue
    });
  }

  filterData (data, reg) {
    if (data) {
      data = data.map((item, i) => {
        return this.columnFilter(item, reg);
      }).filter(item => !!item);
    }

    return data;
  }

  handlerFilterChange(e, reset = false) {
    let input = this.findParentElement(e.target, '.custom-filter-dropdown').querySelector('input');
    if (reset) {
      input.value = '';
    }

    let filterDropdownVisible = input.name;
    let {filterValue} = this.state;
    if (filterDropdownVisible) {
      filterValue[filterDropdownVisible] = input.value;
      this.setState({
        filterValue
      });
    }
  }

  prepareColumns(columns) {
    let {filterValue, filterDropdownVisible} = this.state;
    return columns.map((item, i) => {
      let propsSorter = item.hasSorter ? {
        sorter: (a, b) => this.columnSorter(item.dataIndex, a, b),
      } : {};
      let propsFilter = item.hasFilter ? {
        filterDropdown: (

            <Input
              placeholder="Search"
              ref={(el) => this.searchInput = el}
              onPressEnter={this.handlerFilter}
              name={item.dataIndex}
            />
            <Button.Group>
              <Button type="primary" onClick={this.handlerFilter}>
                <Icon type="search"/>
              </Button>
              <Button onClick={(e) => {
                this.handlerFilter(e, true)
              }}>
                <Icon type="delete"/>
              </Button>
            </Button.Group>

        ),
        filterIcon: <Icon
          type="filter"
          style={{color: filterValue[item.dataIndex] !== undefined && filterValue[item.dataIndex] !== '' ? '#108ee9' : '#aaa'}}
        />,
        filterDropdownVisible: filterDropdownVisible === item.dataIndex,
        onFilterDropdownVisibleChange: visible => this.setState({filterDropdownVisible: visible ? item.dataIndex : false}, () => this.searchInput.focus())
      } : {};

      return {...item, ...propsSorter, ...propsFilter};
    });
  }

  filterProps(props, removeProps) {
    let tableProps = {};
    for (let name in props) {
      if (removeProps.indexOf(name)) {
        tableProps[name] = props[name];
      }
    }

    return tableProps;
  }

  render() {
    let columns = this.prepareColumns(this.props.columns);
    let data = this.state.data ? this.state.data : this.props.data;
    const tableProps = this.filterProps(this.props, ['data', 'columns']);

    if (tableProps.pagination && tableProps.size === 'x-small' && tableProps.pagination !== undefined && !tableProps.pagination.size !== undefined) {
      tableProps.pagination.size = 'small';
    }

    if (!isProd) {
      console.info('GRID RERENDER');
    }

    return (

    );
  }
}

Grid.propTypes = {};

Grid.defaultProps = {};

Grid.InputCell = InputCell;
Grid.CheckboxCell = CheckboxCell;
Grid.SelectCell = SelectCell;
Grid.ColorCell = ColorCell;
Grid.LineStyleCell = LineStyleCell;

export default Grid;
<commit_msg>Codestyle<commit_after>// @flow
import React, {Component} from 'react';
import {Table, Input, Button, Icon} from 'antd';

import InputCell from './InputCell';
import CheckboxCell from './CheckboxCell';
import SelectCell from './SelectCell';
import ColorCell from './ColorCell';
import LineStyleCell from './LineStyleCell';

const isProd = process.env.NODE_ENV === 'production';

//TODO: Таблица с фильтрами обновляется.
//TODO: редактируемые ячейки возвразают [Object]
class Grid extends Component {

  state = {
    filterDropdownVisible: false,
    filterValue: {},
    data: null
  };

  constructor(props) {
    super(props);

    this.handlerFilterChange = ::this.handlerFilterChange;
    this.handlerFilter = ::this.handlerFilter;

  }

  columnSorter = (dataIndex, a, b) => {
    return -(a[dataIndex]  {
    let props = {};
    for (let dataIndex in reg) {
      let value = item[dataIndex].toString();
      const match = value.match(reg[dataIndex]);
      if (!match) {
        return null;
      } else {
        props[dataIndex] = {
          text: value,
          search: reg[dataIndex],
          updateFilter: () => {
            this.setState({
              data: this.filterData(this.props.data, reg)
            });
            console.log('updateFilter');
          }
        }
      }
    }
    return {...item, ...props};
  };

  onChange = (pagination, filters, sorter) => {
    console.log('params', pagination, filters, sorter);
  };

  findParentElement = (el, selector) => {
    let popupEl = el;
    while ((popupEl = popupEl.parentElement) !== null) {
      if (popupEl.matches(selector)) {
        return popupEl;
        break;
      }
    }
  };

  handlerFilter = (e, reset = false) => {
    this.handlerFilterChange(e, reset);

    let filterValue = this.state.filterValue;

    let reg = {};
    for (let dataIndex in filterValue) {
      if (filterValue[dataIndex] !== '') {
        reg[dataIndex] = new RegExp('(' + filterValue[dataIndex] + ')+', 'gi');
      }
    }

    let data = this.filterData(this.props.data, reg);

    this.setState({
      filterDropdownVisible: false,
      data,
      filterValue
    });
  };

  filterData = (data, reg) => {
    if (data) {
      data = data.map((item, i) => {
        return this.columnFilter(item, reg);
      }).filter(item => !!item);
    }

    return data;
  };

  handlerFilterChange = (e, reset = false) => {
    let input = this.findParentElement(e.target, '.custom-filter-dropdown').querySelector('input');
    if (reset) {
      input.value = '';
    }

    let filterDropdownVisible = input.name;
    let {filterValue} = this.state;
    if (filterDropdownVisible) {
      filterValue[filterDropdownVisible] = input.value;
      this.setState({
        filterValue
      });
    }
  };

  prepareColumns = (columns) => {
    let {filterValue, filterDropdownVisible} = this.state;
    return columns.map((item, i) => {
      let propsSorter = item.hasSorter ? {
        sorter: (a, b) => this.columnSorter(item.dataIndex, a, b),
      } : {};
      let propsFilter = item.hasFilter ? {
        filterDropdown: (

            <Input
              placeholder="Search"
              ref={(el) => this.searchInput = el}
              onPressEnter={this.handlerFilter}
              name={item.dataIndex}
            />
            <Button.Group>
              <Button type="primary" onClick={this.handlerFilter}>
                <Icon type="search"/>
              </Button>
              <Button onClick={(e) => {
                this.handlerFilter(e, true)
              }}>
                <Icon type="delete"/>
              </Button>
            </Button.Group>

        ),
        filterIcon: <Icon
          type="filter"
          style={{color: filterValue[item.dataIndex] !== undefined && filterValue[item.dataIndex] !== '' ? '#108ee9' : '#aaa'}}
        />,
        filterDropdownVisible: filterDropdownVisible === item.dataIndex,
        onFilterDropdownVisibleChange: visible => this.setState({filterDropdownVisible: visible ? item.dataIndex : false}, () => this.searchInput.focus())
      } : {};

      return {...item, ...propsSorter, ...propsFilter};
    });
  };

  filterProps = (props, removeProps) => {
    let tableProps = {};
    for (let name in props) {
      if (removeProps.indexOf(name)) {
        tableProps[name] = props[name];
      }
    }

    return tableProps;
  };

  render = () => {
    const columns = this.prepareColumns(this.props.columns);
    const data = this.state.data ? this.state.data : this.props.data;
    const tableProps = this.filterProps(this.props, ['data', 'columns']);

    if (tableProps.pagination && tableProps.size === 'x-small') {
      tableProps.pagination.size = 'small';
    }

    if (!isProd) {
      console.info('GRID RERENDER');
    }

    return (

    );
  };
}

Grid.propTypes = {};

Grid.defaultProps = {};

Grid.InputCell = InputCell;
Grid.CheckboxCell = CheckboxCell;
Grid.SelectCell = SelectCell;
Grid.ColorCell = ColorCell;
Grid.LineStyleCell = LineStyleCell;

export default Grid;
<|endoftext|>


<commit_before>'use strict';

var buster     = require('buster'),
    assert     = buster.assert,
    express    = require('express'),
    request    = require('request'),
    router     = require(__dirname + '/../../../app/routes/api');

var config = require(__dirname + '/../../../config/config-dist.js');
router.setConfig(config, {
    workerId: 1
});

var port = 4321;
var app = express();
app.use('/', router);
var server;

var responseHeaders = {
    connection: 'keep-alive',
    'content-type': 'application/json; charset=utf-8'
};

buster.testCase('app/routes/api', {
    setUp: function () {
        this.timeout = 2000;
        server = app.listen(port);
    },
    tearDown: function (done) {
        // TODO: Shutdown webserver.
        server.close(function() {
            done();
        });
    },
    'Test web routes:': {
        'OPTIONS /articles': function (done) {
            request({
                method: 'OPTIONS',
                uri: 'http://127.0.0.1:' + port + '/articles',
                body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'GET /articles': function (done) {
            request({
                method: 'GET',
                uri: 'http://127.0.0.1:' + port + '/articles'
                //body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'GET /articles/1/comments': function (done) {
            request({
                method: 'GET',
                uri: 'http://127.0.0.1:' + port + '/articles/1/comments'
                //body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'POST /articles': function (done) {
            request({
                method: 'POST',
                uri: 'http://127.0.0.1:' + port + '/articles',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    data: {
                        id: 'abc123',
                        title: 'test article'
                    }
                })
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(201, response.statusCode);
                done();
            });
        },

        'POST /articles/1/comments': function (done) {
            request({
                method: 'POST',
                uri: 'http://127.0.0.1:' + port + '/articles/1/comments',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    data: {
                        id: 'abc123',
                        title: 'test article'
                    }
                })
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(201, response.statusCode);
                done();
            });
        },

        'PATCH /articles/1': function (done) {
            request({
                method: 'PATCH',
                uri: 'http://127.0.0.1:' + port + '/articles/1',
                body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'PUT /articles/1': function (done) {
            request({
                method: 'PUT',
                uri: 'http://127.0.0.1:' + port + '/articles/1',
                body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'DELETE /articles/1': function (done) {
            request({
                method: 'DELETE',
                uri: 'http://127.0.0.1:' + port + '/articles/1'
            }, function (error, response) {
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(204, response.statusCode);
                done();
            });
        },

        'DELETE /articles/1/comments/1': function (done) {
            request({
                method: 'DELETE',
                uri: 'http://127.0.0.1:' + port + '/articles/1/comments/1'
            }, function (error, response) {
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(204, response.statusCode);
                done();
            });
        },

        'GET /not-found-endpoint': function (done) {
            request({
                method: 'GET',
                uri: 'http://127.0.0.1:' + port + '/not-found-endpoint',
                body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(501, response.statusCode);
                done();
            });
        },

        'POST /articles w/borked JSON': function (done) {
            request({
                method: 'POST',
                uri: 'http://127.0.0.1:' + port + '/articles',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: 'broken JSON string.'
            }, function (error, response) {
                console.log(response.headers, response.body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders.connection, response.headers.connection);
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(201, response.statusCode);
                done();
            });
        }

    }
});
<commit_msg>Removed connection from tests.<commit_after>'use strict';

var buster     = require('buster'),
    assert     = buster.assert,
    express    = require('express'),
    request    = require('request'),
    router     = require(__dirname + '/../../../app/routes/api');

var config = require(__dirname + '/../../../config/config-dist.js');
router.setConfig(config, {
    workerId: 1
});

var port = 4321;
var app = express();
app.use('/', router);
var server;

var responseHeaders = {
    connection: 'keep-alive',
    'content-type': 'application/json; charset=utf-8'
};

buster.testCase('app/routes/api', {
    setUp: function () {
        this.timeout = 2000;
        server = app.listen(port);
    },
    tearDown: function (done) {
        // TODO: Shutdown webserver.
        server.close(function() {
            done();
        });
    },
    'Test web routes:': {
        'OPTIONS /articles': function (done) {
            request({
                method: 'OPTIONS',
                uri: 'http://127.0.0.1:' + port + '/articles',
                body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'GET /articles': function (done) {
            request({
                method: 'GET',
                uri: 'http://127.0.0.1:' + port + '/articles'
                //body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'GET /articles/1/comments': function (done) {
            request({
                method: 'GET',
                uri: 'http://127.0.0.1:' + port + '/articles/1/comments'
                //body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'POST /articles': function (done) {
            request({
                method: 'POST',
                uri: 'http://127.0.0.1:' + port + '/articles',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    data: {
                        id: 'abc123',
                        title: 'test article'
                    }
                })
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(201, response.statusCode);
                done();
            });
        },

        'POST /articles/1/comments': function (done) {
            request({
                method: 'POST',
                uri: 'http://127.0.0.1:' + port + '/articles/1/comments',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    data: {
                        id: 'abc123',
                        title: 'test article'
                    }
                })
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(201, response.statusCode);
                done();
            });
        },

        'PATCH /articles/1': function (done) {
            request({
                method: 'PATCH',
                uri: 'http://127.0.0.1:' + port + '/articles/1',
                body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'PUT /articles/1': function (done) {
            request({
                method: 'PUT',
                uri: 'http://127.0.0.1:' + port + '/articles/1',
                body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(200, response.statusCode);
                done();
            });
        },

        'DELETE /articles/1': function (done) {
            request({
                method: 'DELETE',
                uri: 'http://127.0.0.1:' + port + '/articles/1'
            }, function (error, response) {
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(204, response.statusCode);
                done();
            });
        },

        'DELETE /articles/1/comments/1': function (done) {
            request({
                method: 'DELETE',
                uri: 'http://127.0.0.1:' + port + '/articles/1/comments/1'
            }, function (error, response) {
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(204, response.statusCode);
                done();
            });
        },

        'GET /not-found-endpoint': function (done) {
            request({
                method: 'GET',
                uri: 'http://127.0.0.1:' + port + '/not-found-endpoint',
                body: JSON.stringify({})
            }, function (error, response) {
                //console.log(response.headers, body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(501, response.statusCode);
                done();
            });
        },

        'POST /articles w/borked JSON': function (done) {
            request({
                method: 'POST',
                uri: 'http://127.0.0.1:' + port + '/articles',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: 'broken JSON string.'
            }, function (error, response) {
                console.log(response.headers, response.body);
                // TODO: Check response and compare.
                assert.equals(responseHeaders['content-type'], response.headers['content-type']);
                assert.equals(201, response.statusCode);
                done();
            });
        }
    }
});
<|endoftext|>


<commit_before>/**
* Property finder App using react-native
* Find the tutorial oneline: https://www.raywenderlich.com/99473/introducing-react-native-building-apps-javascript
*/
'use strict'
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  View,
  Text,
  NavigatorIOS,
} from 'react-native';

var SearchPage = require('./searchPage.js');

class HelloWorld extends Component {
  render() {
    return (
      <View>
        <Text style={styles.text}>Hello you man oho graaap!</Text>
      </View>
    )
  }
}

class PropertyFinderApp extends Component {
  render() {
    return (
      <NavigatorIOS
        style={styles.container}
        initialRoute={{
          title: 'Property Finder',
          component: SearchPage,
        }}
      />
    );
  }
}

var styles = StyleSheet.create({
  text:{
    color: 'black',
    backgroundColor: 'white',
    fontSize: 30,
    margin: 80
  },
  container: {
    flex: 1,
  }
});

AppRegistry.registerComponent('PropertyFinder', ()=> PropertyFinderApp);
<commit_msg>Refactoring code: Removing hello world<commit_after>/**
* Property finder App using react-native
* Find the tutorial oneline: https://www.raywenderlich.com/99473/introducing-react-native-building-apps-javascript
*/
'use strict'
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  View,
  Text,
  NavigatorIOS,
} from 'react-native';

var SearchPage = require('./searchPage.js');

class PropertyFinderApp extends Component {
  render() {
    return (
      <NavigatorIOS
        style={styles.container}
        initialRoute={{
          title: 'Property Finder',
          component: SearchPage,
        }}
      />
    );
  }
}

var styles = StyleSheet.create({
  text:{
    color: 'black',
    backgroundColor: 'white',
    fontSize: 30,
    margin: 80
  },
  container: {
    flex: 1,
  }
});

AppRegistry.registerComponent('PropertyFinder', ()=> PropertyFinderApp);
<|endoftext|>


<commit_before>var _ = require('_');

var _cache = {},

    _getterSetter = function(key) {
        var ref = (_cache[key] = {});

        return {
            get: function(key) {
                return ref[key];
            },
            set: function(key, value) {
                ref[key] = value;
                return value;
            },
            getOrSet: function(key, fn) {
                var cachedVal = ref[key];
                if (cachedVal !== undefined) { return cachedVal; }
                return (ref[key] = fn());
            }
        };
    },

    _biLevelGetterSetter = function(key) {
        var ref = (_cache[key] = {});

        return {
            get: function(key1, key2) {
                var ref1 = ref[key];
                return ref1 !== undefined ? ref1[key2] : ref1;
            },
            set: function(key1, key2, value) {
                var ref1 = ref[key1] || (ref[key1] = {});
                ref1[key2] = value;
                return value;
            },
            getOrSet: function(key1, key2, fn) {
                var ref1 = ref[key1],
                    cachedVal = ref1[key2];
                if (cachedVal !== undefined) { return cachedVal; }
                return (ref1[key2] = fn());
            }
        };
    };

var api = function(name) {
    return _getterSetter(name || _.uniqueId());
};
api.biLevel = function(name) {
    return _biLevelGetterSetter(name || _.uniqueId());
};
module.exports = api;<commit_msg>Minor/ignore - formatting<commit_after>var _ = require('_');

var _cache = {},

    _getterSetter = function(key) {
        var ref = (_cache[key] = {});

        return {
            get: function(key) {
                return ref[key];
            },
            set: function(key, value) {
                ref[key] = value;
                return value;
            },
            getOrSet: function(key, fn) {
                var cachedVal = ref[key];
                if (cachedVal !== undefined) { return cachedVal; }
                return (ref[key] = fn());
            }
        };
    },

    _biLevelGetterSetter = function(key) {
        var ref = (_cache[key] = {});

        return {
            get: function(key1, key2) {
                var ref1 = ref[key];
                return ref1 !== undefined ? ref1[key2] : ref1;
            },
            set: function(key1, key2, value) {
                var ref1 = ref[key1] || (ref[key1] = {});
                ref1[key2] = value;
                return value;
            },
            getOrSet: function(key1, key2, fn) {
                var ref1 = ref[key1],
                    cachedVal = ref1[key2];
                if (cachedVal !== undefined) { return cachedVal; }
                return (ref1[key2] = fn());
            }
        };
    };

var api = function(name) {
    return _getterSetter(name || _.uniqueId());
};
api.biLevel = function(name) {
    return _biLevelGetterSetter(name || _.uniqueId());
};
module.exports = api;
<|endoftext|>


<commit_before>import {LitElement, html, nothing} from 'lit';
import {ROADMAP_MILESTONE_CARD_CSS} from
  '../sass/elements/chromedash-roadmap-milestone-card-css.js';

class ChromedashRoadmapMilestoneCard extends LitElement {
  static styles = ROADMAP_MILESTONE_CARD_CSS;
  static get properties() {
    return {
      // Assigned in schedule-apge.js, value from Django
      starredFeatures: {type: Object},
      highlightFeature: {type: Number},
      templateContent: {type: Object},
      channel: {type: Object},
      showDates: {type: Boolean},
      removedStatus: {type: Array},
      originTrialStatus: {type: Array},
      browserInterventionStatus: {type: Array},
      deprecatedStatus: {type: Array},
      signedIn: {type: Boolean},
      cardWidth: {type: Number},
      noFeatureString: {type: String},
    };
  }

  constructor() {
    super();
    this.starredFeatures = new Set();
    this.noFeatureString = 'NO FEATURES ARE PLANNED FOR THIS MILESTONE YET';
  }

  /**
   *  Returns the number of days between a and b.
   *  @param {!Date} a
   *  @param {!Date} b
   *  @return {!{days: number, future: boolean}}
   */
  _dateDiffInDays(a, b) {
    // Discard time and time-zone information.
    const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
    const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

    const MS_PER_DAY = 1000 * 60 * 60 * 24;
    const daysDiff = Math.floor((utc2 - utc1) / MS_PER_DAY);
    return {days: Math.abs(daysDiff), future: daysDiff < 1};
  }

  _computeDate(dateStr) {
    const opts = {/* weekday: 'short', */month: 'short', day: 'numeric'};
    const date = new Date(dateStr);
    return new Intl.DateTimeFormat('en-US', opts).format(date);
  }

  _fireEvent(eventName, detail) {
    const event = new CustomEvent(eventName, {
      bubbles: true,
      composed: true,
      detail,
    });
    this.dispatchEvent(event);
  }

  _isAnyFeatureReleased() {
    for (const shippingType of this._objKeys(this.channel.features)) {
      if (this.channel.features[shippingType].length != 0) {
        return true;
      }
    }

    return false;
  }

  toggleStar(e) {
    e.preventDefault();
    e.stopPropagation();

    const iconEl = e.target;
    const featureId = Number(iconEl.dataset.featureId);
    const newStarred = !this.starredFeatures.has(featureId);

    this._fireEvent('star-toggle-event', {
      feature: featureId,
      doStar: newStarred,
    });
  }

  highlight(e) {
    e.preventDefault();
    e.stopPropagation();

    const iconEl = e.target.parentNode;
    const featureId = Number(iconEl.dataset.featureId);

    this._fireEvent('highlight-feature-event', {
      feature: featureId,
    });
  }

  _computeDaysUntil(dateStr) {
    const today = new Date();
    const diff = this._dateDiffInDays(new Date(dateStr), today);
    const dayWord = diff.days == 1 ? 'day' : 'days';

    if (diff.future) {
      return `in ${diff.days} ${dayWord}`;
    } else {
      return `${diff.days} ${dayWord} ago`;
    }
  }

  _objKeys(obj) {
    if (!obj) {
      return [];
    }
    return Object.keys(obj).sort();
  }

  _cardHeaderTemplate() {
    return html `

${this.templateContent.channelLabel}

        Chrome ${this.channel.version}

      ${this.showDates && this.channel.earliest_beta ? html`

          Beta ${this.templateContent.dateText}
          ${this._computeDate(this.channel.earliest_beta)} - ${this._computeDate(this.channel.latest_beta)}

          Stable ${this._computeDaysUntil(this.channel.stable_date)}
          (${this._computeDate(this.channel.stable_date)})

      ` : nothing}
    `;
  }

  _cardFeatureItemTemplate(f, shippingType) {
    return html `

      ${f.name}

        ${this.originTrialStatus.includes(shippingType) ? html`

          <iron-icon icon="chromestatus:extension" class="experimental" data-tooltip></iron-icon>

        ` : nothing}
        ${this.browserInterventionStatus.includes(shippingType) ? html`

          <iron-icon icon="chromestatus:pan-tool" class="intervention" data-tooltip></iron-icon>

        ` : nothing}
        ${this.removedStatus.includes(shippingType) ? html`

          <iron-icon icon="chromestatus:cancel" class="remove" data-tooltip></iron-icon>

        ` : nothing}
        ${this.deprecatedStatus.includes(shippingType) ? html`

          <iron-icon icon="chromestatus:warning" class="deprecated" data-tooltip></iron-icon>

        ` : nothing}
        ${this.signedIn ? html`

          <iron-icon
            icon="${this.starredFeatures.has(Number(f.id)) ?
            'chromestatus:star' :
            'chromestatus:star-border'}"
            class="pushicon"
            data-feature-id="${f.id}"
            @click="${this.toggleStar}">
          </iron-icon>

        ` : nothing}

    `;
  }

  _cardFeatureListTemplate() {
    return html `

        ${this._isAnyFeatureReleased() ? html `

${this.templateContent.featureHeader}:

          ${this._objKeys(this.channel.features).map((shippingType) => this.channel.features[shippingType] != 0 ? html`

${shippingType}

            ${this.channel.features[shippingType].map((f) => html`
              ${this._cardFeatureItemTemplate(f, shippingType)}
            `)}

          ` : nothing)}

` : html `

${this.noFeatureString}

        `}

    `;
  }

  _widthStyle() {
    return html`

    `;
  }

  render() {
    return html`
      ${this._widthStyle()}

        ${this._cardHeaderTemplate()}
        ${this._cardFeatureListTemplate()}

    `;
  }
}

customElements.define(
  'chromedash-roadmap-milestone-card',
  ChromedashRoadmapMilestoneCard);
<commit_msg>remove highlight on mouse leave from roadmap (#1840)<commit_after>import {LitElement, html, nothing} from 'lit';
import {ROADMAP_MILESTONE_CARD_CSS} from
  '../sass/elements/chromedash-roadmap-milestone-card-css.js';

class ChromedashRoadmapMilestoneCard extends LitElement {
  static styles = ROADMAP_MILESTONE_CARD_CSS;
  static get properties() {
    return {
      // Assigned in schedule-apge.js, value from Django
      starredFeatures: {type: Object},
      highlightFeature: {type: Number},
      templateContent: {type: Object},
      channel: {type: Object},
      showDates: {type: Boolean},
      removedStatus: {type: Array},
      originTrialStatus: {type: Array},
      browserInterventionStatus: {type: Array},
      deprecatedStatus: {type: Array},
      signedIn: {type: Boolean},
      cardWidth: {type: Number},
      noFeatureString: {type: String},
    };
  }

  constructor() {
    super();
    this.starredFeatures = new Set();
    this.noFeatureString = 'NO FEATURES ARE PLANNED FOR THIS MILESTONE YET';
  }

  /**
   *  Returns the number of days between a and b.
   *  @param {!Date} a
   *  @param {!Date} b
   *  @return {!{days: number, future: boolean}}
   */
  _dateDiffInDays(a, b) {
    // Discard time and time-zone information.
    const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
    const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

    const MS_PER_DAY = 1000 * 60 * 60 * 24;
    const daysDiff = Math.floor((utc2 - utc1) / MS_PER_DAY);
    return {days: Math.abs(daysDiff), future: daysDiff < 1};
  }

  _computeDate(dateStr) {
    const opts = {/* weekday: 'short', */month: 'short', day: 'numeric'};
    const date = new Date(dateStr);
    return new Intl.DateTimeFormat('en-US', opts).format(date);
  }

  _fireEvent(eventName, detail) {
    const event = new CustomEvent(eventName, {
      bubbles: true,
      composed: true,
      detail,
    });
    this.dispatchEvent(event);
  }

  _isAnyFeatureReleased() {
    for (const shippingType of this._objKeys(this.channel.features)) {
      if (this.channel.features[shippingType].length != 0) {
        return true;
      }
    }

    return false;
  }

  toggleStar(e) {
    e.preventDefault();
    e.stopPropagation();

    const iconEl = e.target;
    const featureId = Number(iconEl.dataset.featureId);
    const newStarred = !this.starredFeatures.has(featureId);

    this._fireEvent('star-toggle-event', {
      feature: featureId,
      doStar: newStarred,
    });
  }

  highlight(e) {
    e.preventDefault();
    e.stopPropagation();

    const iconEl = e.target.parentNode;
    const featureId = Number(iconEl.dataset.featureId);

    this._fireEvent('highlight-feature-event', {
      feature: featureId,
    });
  }

  removeHighlight(e) {
    e.preventDefault();
    e.stopPropagation();

    this._fireEvent('highlight-feature-event', {
      feature: null,
    });
  }

  _computeDaysUntil(dateStr) {
    const today = new Date();
    const diff = this._dateDiffInDays(new Date(dateStr), today);
    const dayWord = diff.days == 1 ? 'day' : 'days';

    if (diff.future) {
      return `in ${diff.days} ${dayWord}`;
    } else {
      return `${diff.days} ${dayWord} ago`;
    }
  }

  _objKeys(obj) {
    if (!obj) {
      return [];
    }
    return Object.keys(obj).sort();
  }

  _cardHeaderTemplate() {
    return html `

${this.templateContent.channelLabel}

        Chrome ${this.channel.version}

      ${this.showDates && this.channel.earliest_beta ? html`

          Beta ${this.templateContent.dateText}
          ${this._computeDate(this.channel.earliest_beta)} - ${this._computeDate(this.channel.latest_beta)}

          Stable ${this._computeDaysUntil(this.channel.stable_date)}
          (${this._computeDate(this.channel.stable_date)})

      ` : nothing}
    `;
  }

  _cardFeatureItemTemplate(f, shippingType) {
    return html `

      ${f.name}

        ${this.originTrialStatus.includes(shippingType) ? html`

          <iron-icon icon="chromestatus:extension" class="experimental" data-tooltip></iron-icon>

        ` : nothing}
        ${this.browserInterventionStatus.includes(shippingType) ? html`

          <iron-icon icon="chromestatus:pan-tool" class="intervention" data-tooltip></iron-icon>

        ` : nothing}
        ${this.removedStatus.includes(shippingType) ? html`

          <iron-icon icon="chromestatus:cancel" class="remove" data-tooltip></iron-icon>

        ` : nothing}
        ${this.deprecatedStatus.includes(shippingType) ? html`

          <iron-icon icon="chromestatus:warning" class="deprecated" data-tooltip></iron-icon>

        ` : nothing}
        ${this.signedIn ? html`

          <iron-icon
            icon="${this.starredFeatures.has(Number(f.id)) ?
            'chromestatus:star' :
            'chromestatus:star-border'}"
            class="pushicon"
            data-feature-id="${f.id}"
            @click="${this.toggleStar}">
          </iron-icon>

        ` : nothing}

    `;
  }

  _cardFeatureListTemplate() {
    return html `

        ${this._isAnyFeatureReleased() ? html `

${this.templateContent.featureHeader}:

          ${this._objKeys(this.channel.features).map((shippingType) => this.channel.features[shippingType] != 0 ? html`

${shippingType}

            ${this.channel.features[shippingType].map((f) => html`
              ${this._cardFeatureItemTemplate(f, shippingType)}
            `)}

          ` : nothing)}

` : html `

${this.noFeatureString}

        `}

    `;
  }

  _widthStyle() {
    return html`

    `;
  }

  render() {
    return html`
      ${this._widthStyle()}

        ${this._cardHeaderTemplate()}
        ${this._cardFeatureListTemplate()}

    `;
  }
}

customElements.define(
  'chromedash-roadmap-milestone-card',
  ChromedashRoadmapMilestoneCard);
<|endoftext|>


<commit_before>/* Load CSS and create the markup necessary to render the Site Map */
if(document.getElementById('myModal') !== null) {
  document.getElementById('myModal').style.display="block";
  var count=document.getElementById('myModal').getAttribute('count');
  count++;
  document.getElementById('myModal').setAttribute('count',count);
} else {
  var styles = ['css/googlestyle.css', 'css/RTstyle.css', 'css/sequences.css',
                'css/radial-tree.css'];
  for (var i in styles) {
    var el = document.createElement('link');
    el.rel = 'stylesheet';
    el.type = 'text/css';
    el.href = chrome.extension.getURL(styles[i]);
    document.head.appendChild(el);
  }
  var modal=document.createElement('div');
  modal.setAttribute('id','myModal');
  modal.setAttribute('class','RTmodal');
  modal.setAttribute('count','1');
  /**
  var modalContent=document.createElement('div');
  modalContent.setAttribute('class','modal-content');
  var divBtn=document.createElement('div');
  divBtn.setAttribute('id','divBtn');
  var message=document.createElement('div');
  message.setAttribute('id','message');
  **/
  var span=document.createElement('button');
  span.innerHTML='×';
  span.setAttribute('class','RTclose');
  modal.appendChild(span);
  /**
   * var main=document.createElement('div');
  var sequence=document.createElement('p');
  var chart=document.createElement('div');
  sequence.setAttribute('id','sequence');
  chart.setAttribute('id','chart');
  main.setAttribute('id','main');

  modal.appendChild(divBtn);
  modal.appendChild(sequence);
  modal.appendChild(chart);
  modal.appendChild(message);
  **/
  document.body.appendChild(modal);
  modal.style.display = "block";

  span.onclick = function() {
    modal.style.display = "none";
    // var Modal=document.getElementById("myModal");
    // document.body.removeChild(Modal);
  };
}
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.message=="deletenode"){
    console.log("Message received for deleting node");
  	var Modal=document.getElementById("myModal");
    document.body.removeChild(Modal);
  }
});
var $container = document.getElementById('myModal');
if ($container.getAttribute('count') == 1) {
  var loading = document.createElement('div');
  loading.setAttribute('id', 'loading');
  $container.appendChild(loading);
  var animate = document.createElement('img');
  var fullURL = chrome.runtime.getURL('images/logo-animate.svg');
  animate.setAttribute('src', fullURL);
  animate.setAttribute('id', 'animated-logo');
  document.getElementById('loading').appendChild(animate);
}
chrome.runtime.sendMessage({ message: 'sendurlforrt' });
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
	if (message.RTurl != "") {
		var url = message.RTurl;
		if (url.includes('https')) {
			url = url.replace('https://', '');
		} else {
			url = url.replace('http://', '');
		}
		var pos = url.indexOf('/');
		if (pos != -1) url = url.substring(0, pos);
		var base_url = url;
		var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://web.archive.org/web/timemap/json?url="+url+"/&fl=timestamp:4,urlkey&matchType=prefix&filter=statuscode:200&filter=mimetype:text/html&collapse=urlkey&collapse=timestamp:4&limit=100000", true);
		xhr.onerror = function() {
			var animateSvg = document.getElementById('animated-logo');
			document.getElementById('loading').removeChild(animateSvg);
			alert("An error occured. Please refresh the page and try again");
		};
		xhr.ontimeout = function() {
			var animateSvg = document.getElementById('animated-logo');
			document.getElementById('loading').removeChild(animateSvg);
			alert("Time out. Please refresh the page and try again");
		}
		xhr.onload = function() {
			var response = JSON.parse(xhr.responseText);
			var animateSvg = document.getElementById('animated-logo');
			document.getElementById('loading').removeChild(animateSvg);
      new wb.RadialTree(document.getElementById('loading'), response, {url: url});
		};
		xhr.send();
	}
});
<commit_msg>Remove commented code in scripts/RTcontent.js<commit_after>/* Load CSS and create the markup necessary to render the Site Map */
if(document.getElementById('myModal') !== null) {
  document.getElementById('myModal').style.display="block";
  var count=document.getElementById('myModal').getAttribute('count');
  count++;
  document.getElementById('myModal').setAttribute('count',count);
} else {
  var styles = ['css/googlestyle.css', 'css/RTstyle.css', 'css/sequences.css',
                'css/radial-tree.css'];
  for (var i in styles) {
    var el = document.createElement('link');
    el.rel = 'stylesheet';
    el.type = 'text/css';
    el.href = chrome.extension.getURL(styles[i]);
    document.head.appendChild(el);
  }
  var modal=document.createElement('div');
  modal.setAttribute('id','myModal');
  modal.setAttribute('class','RTmodal');
  modal.setAttribute('count','1');
  var span=document.createElement('button');
  span.innerHTML='×';
  span.setAttribute('class','RTclose');
  modal.appendChild(span);
  document.body.appendChild(modal);
  modal.style.display = "block";

  span.onclick = function() {
    modal.style.display = "none";
  };
}
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.message=="deletenode"){
    console.log("Message received for deleting node");
  	var Modal=document.getElementById("myModal");
    document.body.removeChild(Modal);
  }
});
var $container = document.getElementById('myModal');
if ($container.getAttribute('count') == 1) {
  var loading = document.createElement('div');
  loading.setAttribute('id', 'loading');
  $container.appendChild(loading);
  var animate = document.createElement('img');
  var fullURL = chrome.runtime.getURL('images/logo-animate.svg');
  animate.setAttribute('src', fullURL);
  animate.setAttribute('id', 'animated-logo');
  document.getElementById('loading').appendChild(animate);
}
chrome.runtime.sendMessage({ message: 'sendurlforrt' });
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
	if (message.RTurl != "") {
		var url = message.RTurl;
		if (url.includes('https')) {
			url = url.replace('https://', '');
		} else {
			url = url.replace('http://', '');
		}
		var pos = url.indexOf('/');
		if (pos != -1) url = url.substring(0, pos);
		var base_url = url;
		var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://web.archive.org/web/timemap/json?url="+url+"/&fl=timestamp:4,urlkey&matchType=prefix&filter=statuscode:200&filter=mimetype:text/html&collapse=urlkey&collapse=timestamp:4&limit=100000", true);
		xhr.onerror = function() {
			var animateSvg = document.getElementById('animated-logo');
			document.getElementById('loading').removeChild(animateSvg);
			alert("An error occured. Please refresh the page and try again");
		};
		xhr.ontimeout = function() {
			var animateSvg = document.getElementById('animated-logo');
			document.getElementById('loading').removeChild(animateSvg);
			alert("Time out. Please refresh the page and try again");
		}
		xhr.onload = function() {
			var response = JSON.parse(xhr.responseText);
			var animateSvg = document.getElementById('animated-logo');
			document.getElementById('loading').removeChild(animateSvg);
      new wb.RadialTree(document.getElementById('loading'), response, {url: url});
		};
		xhr.send();
	}
});
<|endoftext|>


<commit_before>L.ResponsivePopup = L.Popup.extend({

	/**
	 * Options:
	 * - Do we use tips ? (no)
	 * - How near to an edge can a popup be ? (fenceWidth)
	 */

	/**
	 * Overrides https://github.com/Leaflet/Leaflet/blob/release-1.0.2/src/layer/Popup.js#L158
	 */
	_initLayout: function () {

		var prefix = 'leaflet-popup',
		    container = this._container = L.DomUtil.create('div',
			prefix + ' ' + (this.options.className || '') +
			' leaflet-zoom-animated');

		if (this.options.closeButton) {
			var closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
			closeButton.href = '#close';
			closeButton.innerHTML = '×';

			L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
		}

		var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
		this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);

		L.DomEvent
			.disableClickPropagation(wrapper)
			.disableScrollPropagation(this._contentNode)
			.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);

		/* No tip
		this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
		this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
		*/
	},

	/**
	 * Overrides https://github.com/Leaflet/Leaflet/blob/release-1.0.2/src/layer/DivOverlay.js#L172
	 */
	_updatePosition: function () {
		if (!this._map) { return; }

		// position upper left corner of the popup before offsetting
		var pos = this._map.latLngToLayerPoint(this._latlng),
		    offset = L.point(this.options.offset),
		    anchor = this._getAnchor();

		if (this._zoomAnimated) {
			L.DomUtil.setPosition(this._container, pos.add(anchor));
		} else {
			offset = offset.add(pos).add(anchor);
		}

		// what is the position before offsetting ?
		var mapSize = this._map.getSize();
		var posQuadrant = "";

		if(pos.y < Math.round(mapSize.y / 2)) {
			posQuadrant = "n";
		}
		else {
			posQuadrant = "s";
		}

		if(pos.x < Math.round(mapSize.x / 2)) {
			posQuadrant += "w";
		}
		else {
			posQuadrant += "e";
		}

		// can the popup fit ?
		var canGoAbove = true;
		var canGoSideway = true;
		if(this._container.offsetHeight > Math.round(mapSize.y/2)) { // There are more parameters to take into account
			canGoAbove = false;
			console.log('does not fit above');
		}
		if(this._containerWidth > Math.round(mapSize.x/2)) { // There are more parameters to take into account
			canGoSideway = false;
			console.log('does not fit on the side');
		}

		// offset the popup in a way it will be visible without moving the map
		var fenceWidth = 10;

		var bottom = this._containerBottom = -offset.y;
		if(/n/.test(posQuadrant)) {
			bottom = this._containerBottom = -this._container.offsetHeight -offset.y -20 -5; // leaflet-popup margin-bottom: 20px
		}

		var left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
		if(/w/.test(posQuadrant) && pos.x + left < fenceWidth) { // left from the fence
			left = this._containerLeft = fenceWidth - pos.x;
		}

		if(/e/.test(posQuadrant) && (pos.x + Math.round(this._containerWidth/2) + fenceWidth) > mapSize.x) { // right from the fence
			left = this._containerLeft = (mapSize.x - pos.x) - this._containerWidth - fenceWidth;
		}

		if(!canGoAbove && canGoSideway) { // let's change the position
			left = this._containerLeft = 20; // margin
			if(/e/.test(posQuadrant)) {
				left = this._containerLeft = -this._containerWidth - 20; // margin
			}

			bottom = this._containerBottom = -Math.round(this._container.offsetHeight / 2) -offset.y -20; // margin
			if(/n/.test(posQuadrant) && pos.y - Math.round(this._container.offsetHeight / 2) < fenceWidth ) {
				console.log('move it n');
			}
			if(/s/.test(posQuadrant) && pos.y + Math.round(this._container.offsetHeight / 2) > mapSize.y - fenceWidth) {
				console.log('move it s');
			}
		}

		// bottom position the popup in case the height of the popup changes (images loading etc)
		this._container.style.bottom = bottom + 'px';
		this._container.style.left = left + 'px';
	}

});

//Instantiates a `ResponsivePopup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers.
L.responsivePopup = function (options, source) {
	return new L.ResponsivePopup(options, source);
};
<commit_msg>implement reponsive portrait popup<commit_after>L.ResponsivePopup = L.Popup.extend({

	/**
	 * Options:
	 * - Do we use tips ? (no)
	 * - How near to an edge can a popup be ? (fenceWidth)
	 */

	/**
	 * Overrides https://github.com/Leaflet/Leaflet/blob/release-1.0.2/src/layer/Popup.js#L158
	 */
	_initLayout: function () {

		var prefix = 'leaflet-popup',
		    container = this._container = L.DomUtil.create('div',
			prefix + ' ' + (this.options.className || '') +
			' leaflet-zoom-animated');

		if (this.options.closeButton) {
			var closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
			closeButton.href = '#close';
			closeButton.innerHTML = '×';

			L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
		}

		var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
		this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);

		L.DomEvent
			.disableClickPropagation(wrapper)
			.disableScrollPropagation(this._contentNode)
			.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);

		/* No tip
		this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
		this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
		*/
	},

	/**
	 * Overrides https://github.com/Leaflet/Leaflet/blob/release-1.0.2/src/layer/DivOverlay.js#L172
	 */
	_updatePosition: function () {
		if (!this._map) { return; }

		// position upper left corner of the popup before offsetting
		var pos = this._map.latLngToLayerPoint(this._latlng),
		    offset = L.point(this.options.offset),
		    anchor = this._getAnchor();

		if (this._zoomAnimated) {
			L.DomUtil.setPosition(this._container, pos.add(anchor));
		} else {
			offset = offset.add(pos).add(anchor);
		}

		// what is the position before offsetting ?
		var mapSize = this._map.getSize();
		var posQuadrant = "";

		if(pos.y < Math.round(mapSize.y / 2)) {
			posQuadrant = "n";
		}
		else {
			posQuadrant = "s";
		}

		if(pos.x < Math.round(mapSize.x / 2)) {
			posQuadrant += "w";
		}
		else {
			posQuadrant += "e";
		}

		// can the popup fit ?
		var canGoAbove = true;
		var canGoSideway = true;
		if(this._container.offsetHeight > Math.round(mapSize.y/2)) { // There are more parameters to take into account
			canGoAbove = false;
		}
		if(this._containerWidth > Math.round(mapSize.x/2)) { // There are more parameters to take into account
			canGoSideway = false;
		}

		// offset the popup in a way it will be visible without moving the map
		var fenceWidth = 10;

		var bottom = this._containerBottom = -offset.y;
		if(/n/.test(posQuadrant)) {
			bottom = this._containerBottom = -this._container.offsetHeight -offset.y -20 -5; // leaflet-popup margin-bottom: 20px
		}

		var left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
		if(/w/.test(posQuadrant) && pos.x + left < fenceWidth) { // left from the fence
			left = this._containerLeft = fenceWidth - pos.x;
		}

		if(/e/.test(posQuadrant) && (pos.x + Math.round(this._containerWidth/2) + fenceWidth) > mapSize.x) { // right from the fence
			left = this._containerLeft = (mapSize.x - pos.x) - this._containerWidth - fenceWidth;
		}

		if(!canGoAbove && canGoSideway) { // let's change the position
			left = this._containerLeft = 20; // margin
			if(/e/.test(posQuadrant)) {
				left = this._containerLeft = -this._containerWidth - 20; // margin
			}

			bottom = this._containerBottom = -Math.round(this._container.offsetHeight / 2) -offset.y -20; // margin
			if(/n/.test(posQuadrant) && pos.y - Math.round(this._container.offsetHeight / 2) < fenceWidth ) {
				bottom = this._containerBottom = -this._container.offsetHeight + pos.y - 20 - fenceWidth; // margin
			}
			if(/s/.test(posQuadrant) && pos.y + Math.round(this._container.offsetHeight / 2) > mapSize.y - fenceWidth) {
				bottom = this._containerBottom = pos.y - mapSize.y - 20 + fenceWidth;
			}
		}

		// bottom position the popup in case the height of the popup changes (images loading etc)
		this._container.style.bottom = bottom + 'px';
		this._container.style.left = left + 'px';
	}

});

//Instantiates a `ResponsivePopup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers.
L.responsivePopup = function (options, source) {
	return new L.ResponsivePopup(options, source);
};
<|endoftext|>


<commit_before>$(document).ready(function(){

    var fechaHoy=new Date();
    var fechaAyer=new Date(fechaHoy.getFullYear(), fechaHoy.getMonth(), fechaHoy.getDate()-1);

    //DatePicker http://www.jqueryrain.com/?A_MO0kvZ
    $('#idFechaN').datepicker({
	language: 'es',
	minDate: new Date("1970","0","1"),
    view: "years",
    autoClose: true,
    maxDate: fechaAyer// Now can select only dates, which goes after today
})

    jQuery.validator.addMethod('lettersonly', function(value, element) {
    return this.optional(element) || /^[a-z áãâäàéêëèíîïìóõôöòúûüùç]+$/i.test(value);
}, "Letras y espacios solo");

$.validator.addMethod("dateFormat",
    function(value, element) {
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
    },
    "Por favor introduce una fecha con el formato dd-mm-yyyy.");

    $('#abrir').on('click',function(){

       var inst = $('[data-remodal-id=modal]').remodal();

        inst.open();

    });

    $('#miForm').validate(

      {

        rules:
        {
          idNombre: {
            required: true,
            lettersonly: true,
              maxlength: 10,
              minlength: 3
          },
            idApellidos: {
                required: true,
            lettersonly: true,
              maxlength: 25,
              minlength: 4

            },
            idFechaN: {

                dateFormat: true,
                required: true
            },

            idCorreo: {

                email:true,
                required:true,
                remote: {
                                url: "check-email.php",
                                type: "post",
                                data: {
                                username: function() {
                                    return $( "#idCorreo" ).val();
                                            }
                                    }
                }

            }

        },

        messages:
        {
          idNombre:{
            required: "Por favor, introduzca su nombre",
              maxlength: "Nombre demasiado largo",
              minlength: "Nombre demasiado corto"
          },

            idApellidos:{
            required: "Por favor, introduzca sus apellidos",
              maxlength: "Apellidos demasiados largos",
              minlength: "Apellidos demasiados cortos"
          },

            idFechaN:{

                required: "Por favor, introduzca su fecha de nacimiento"

            }
        },

         submitHandler: function(form) {

        $(form).ajaxSubmit();
  }

      });

          $('#miForm').on('submit',function(e){

    e.preventDefault();
    isValid=$('#miForm').valid();

    if(!isValid){
        alert("no");
    }else{
        alert("si");
        inst.close();
    }

})

});

<commit_msg>Delete dialog.js<commit_after><|endoftext|>


<commit_before>/*
 * slush-blueprints
 * https://github.com/Truemedia/slush-blueprints
 *
 * Copyright (c) 2015, Wade Penistone
 * Licensed under the MIT license.
 */

'use strict';

// Slush core files
var gulp = require('gulp'),
    install = require('gulp-install'),
    conflict = require('gulp-conflict'),
    template = require('gulp-template'),
    rename = require('gulp-rename'),
    _ = require('underscore.string'),
    inquirer = require('inquirer');

// Extras specific to this project
var gutil = require('gulp-util'),
    cheerio = require('gulp-cheerio'),
    rm = require('gulp-rm'),
    fs = require('fs'),
    changeCase = require('change-case'),
    moment = require('moment'),
    jsonpatch = require('jsonpatch'),
    jsonfile = require('jsonfile'),
    walk = require('tree-walk'),
    kvp = require('key-value-pointer');
    // CLI UI
    Table = require('cli-table'),
    ProgressBar = require('progress');

function format(string) {
    var username = string.toLowerCase();
    return username.replace(/\s/g, '');
}

var defaults = (function () {
    var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
        workingDirName = process.cwd().split('/').pop().split('\\').pop(),
        osUserName = homeDir && homeDir.split('/').pop() || 'root',
        configFile = homeDir + '/.gitconfig',
        user = {};
    if (require('fs').existsSync(configFile)) {
        user = require('iniparser').parseSync(configFile).user;
    }
    return {
        vendorName: 'regeneration',
        packageName: workingDirName,
        userName: format(user.name) || osUserName,
        authorEmail: user.email || ''
    };
})();

gulp.task('default', function (done) {
    var prompts = [{
        name: 'vendorName',
        message: 'What project is this for, e.g vendor?',
        default: defaults.vendorName
    }, {
        name: 'packageName',
        message: 'What is the name of your package?',
        default: defaults.packageName
    }, {
        name: 'packageDescription',
        message: 'What is the description?'
    }, {
        name: 'packageVersion',
        message: 'What is the version of your project?',
        default: '0.1.0'
    }, {
        name: 'authorName',
        message: 'What is the author name?',
    }, {
        name: 'authorEmail',
        message: 'What is the author email?',
        default: defaults.authorEmail
    }, {
        name: 'userName',
        message: 'What is the github username?',
        default: defaults.userName
    }, {
        type: 'confirm',
        name: 'moveon',
        message: 'Continue?'
    }];
    //Ask
    inquirer.prompt(prompts,
        function (answers) {
            if (!answers.moveon) {
                return done();
            }

            // Transform user input into usable data
            var data = {
                vendorName: answers.vendorName,
                packageName: answers.packageName,
                packageDescription: answers.packageDescription,
                packageVersion: answers.packageVersion,
                authorName: answers.authorName,
                authorEmail: answers.authorEmail,
                userName: answers.userName,
                packageNameSlug: _.slugify(answers.packageName),
                packageNameCaps: _.capitalize(answers.packageName),
                vendorNameCaps: _.capitalize(answers.vendorName)
            };

            gulp.src(__dirname + '/templates/package/**')
                .pipe( template(data) )
                .pipe( rename( function(file)
                {
                    var dir = file.dirname;
                    var name = file.basename;
                    var ext = file.extname;

                    if (file.basename[0] === '_')
                    {
                        var replacements = [];

                        switch (file.basename)
                        {
                            // This is a weird file to deal with
                            case '_packageNameCapsServiceProvider':
                                replacements.push('vendorNameCaps', 'packageNameCaps');
                            break;

                            case '_packageNameCaps':
                                replacements.push('vendorNameCaps', 'packageNameCaps');
                            break;

                            default:
                                // Try to match file name against template variable exactly or try all the variables
                                if (data[file.basename.slice(1)] !== undefined || data[file.dirname.slice(1)] !== undefined)
                                {
                                    replacements.push(file.basename.slice(1), file.dirname.slice(1));
                                }
                                else
                                {
                                    replacements = Object.keys(data);
                                }
                            break;
                        }

                        if (replacements.length > 0)
                        {
                            replacements.forEach( function(item)
                            {
                                var find = '_' + item;
                                var replace = data[item];

                                dir = dir.replace(find, replace);
                                name = name.replace(find, replace);
                            });
                        }
                    }

                    file.dirname = dir;
                    file.basename = name;
                    file.ext = ext;
                }))
                .pipe(conflict('./'))
                .pipe(gulp.dest('./'))
                .pipe(install())
                .on('end', function()
                {
                    done();
                });
        });
});
<commit_msg>Fixed include bug<commit_after>/*
 * slush-blueprints
 * https://github.com/Truemedia/slush-blueprints
 *
 * Copyright (c) 2015, Wade Penistone
 * Licensed under the MIT license.
 */

'use strict';

// Slush core files
var gulp = require('gulp'),
    install = require('gulp-install'),
    conflict = require('gulp-conflict'),
    template = require('gulp-template'),
    rename = require('gulp-rename'),
    _ = require('underscore.string'),
    inquirer = require('inquirer');

// Extras specific to this project
var gutil = require('gulp-util'),
    cheerio = require('gulp-cheerio'),
    rm = require('gulp-rm'),
    fs = require('fs'),
    changeCase = require('change-case'),
    moment = require('moment'),
    jsonpatch = require('jsonpatch'),
    jsonfile = require('jsonfile'),
    walk = require('tree-walk'),
    kvp = require('key-value-pointer'),
    // CLI UI
    Table = require('cli-table'),
    ProgressBar = require('progress');

function format(string) {
    var username = string.toLowerCase();
    return username.replace(/\s/g, '');
}

var defaults = (function () {
    var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
        workingDirName = process.cwd().split('/').pop().split('\\').pop(),
        osUserName = homeDir && homeDir.split('/').pop() || 'root',
        configFile = homeDir + '/.gitconfig',
        user = {};
    if (require('fs').existsSync(configFile)) {
        user = require('iniparser').parseSync(configFile).user;
    }
    return {
        vendorName: 'regeneration',
        packageName: workingDirName,
        userName: format(user.name) || osUserName,
        authorEmail: user.email || ''
    };
})();

gulp.task('default', function (done) {
    var prompts = [{
        name: 'vendorName',
        message: 'What project is this for, e.g vendor?',
        default: defaults.vendorName
    }, {
        name: 'packageName',
        message: 'What is the name of your package?',
        default: defaults.packageName
    }, {
        name: 'packageDescription',
        message: 'What is the description?'
    }, {
        name: 'packageVersion',
        message: 'What is the version of your project?',
        default: '0.1.0'
    }, {
        name: 'authorName',
        message: 'What is the author name?',
    }, {
        name: 'authorEmail',
        message: 'What is the author email?',
        default: defaults.authorEmail
    }, {
        name: 'userName',
        message: 'What is the github username?',
        default: defaults.userName
    }, {
        type: 'confirm',
        name: 'moveon',
        message: 'Continue?'
    }];
    //Ask
    inquirer.prompt(prompts,
        function (answers) {
            if (!answers.moveon) {
                return done();
            }

            // Transform user input into usable data
            var data = {
                vendorName: answers.vendorName,
                packageName: answers.packageName,
                packageDescription: answers.packageDescription,
                packageVersion: answers.packageVersion,
                authorName: answers.authorName,
                authorEmail: answers.authorEmail,
                userName: answers.userName,
                packageNameSlug: _.slugify(answers.packageName),
                packageNameCaps: _.capitalize(answers.packageName),
                vendorNameCaps: _.capitalize(answers.vendorName)
            };

            gulp.src(__dirname + '/templates/package/**')
                .pipe( template(data) )
                .pipe( rename( function(file)
                {
                    var dir = file.dirname;
                    var name = file.basename;
                    var ext = file.extname;

                    if (file.basename[0] === '_')
                    {
                        var replacements = [];

                        switch (file.basename)
                        {
                            // This is a weird file to deal with
                            case '_packageNameCapsServiceProvider':
                                replacements.push('vendorNameCaps', 'packageNameCaps');
                            break;

                            case '_packageNameCaps':
                                replacements.push('vendorNameCaps', 'packageNameCaps');
                            break;

                            default:
                                // Try to match file name against template variable exactly or try all the variables
                                if (data[file.basename.slice(1)] !== undefined || data[file.dirname.slice(1)] !== undefined)
                                {
                                    replacements.push(file.basename.slice(1), file.dirname.slice(1));
                                }
                                else
                                {
                                    replacements = Object.keys(data);
                                }
                            break;
                        }

                        if (replacements.length > 0)
                        {
                            replacements.forEach( function(item)
                            {
                                var find = '_' + item;
                                var replace = data[item];

                                dir = dir.replace(find, replace);
                                name = name.replace(find, replace);
                            });
                        }
                    }

                    file.dirname = dir;
                    file.basename = name;
                    file.ext = ext;
                }))
                .pipe(conflict('./'))
                .pipe(gulp.dest('./'))
                .pipe(install())
                .on('end', function()
                {
                    done();
                });
        });
});
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.'},
    {'name': 'Motorola XOOM with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.'},
    {'name': 'Motorola Xoom',
     'snippet': 'The Next, Next Generation tablet.'}
  ];
});<commit_msg>Updated the phones model to add an age property for each phone.<commit_after>'use strict';

/* Controllers */

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.',
     'age': 1},
    {'name': 'Motorola XOOM with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.',
     'age': 2},
    {'name': 'Motorola Xoom',
     'snippet': 'The Next, Next Generation tablet.',
     'age': 3}
  ];

  $scope.orderProp = 'age';
});<|endoftext|>


<commit_before>var openUrl = require('./helpers/utils').open;
var openBlog = require('./helpers/utils').openBlog;

describe('Blog settings', function() {
    'use strict';

    var DEFAULT_LANGUAGE = 'en';
    var NEW_LANGUAGE = 'fr';

    beforeEach(openUrl('/#/liveblog'));

    function openSettings() {
        // click on the settings button
        element(by.css('.settings-link')).click();
    }

    function expectSelectedLanguageIs(language) {
        expect(element(by.model('settings.blogPreferences.language')).getAttribute('value')).toEqual(language);
    }

    function setLanguage(language) {
        element(by.model('settings.blogPreferences.language')).sendKeys(language);
    }

    it('shows the default language selected', function() {
        openBlog(0);
        openSettings();
        expectSelectedLanguageIs(DEFAULT_LANGUAGE);
    });

    it('save a new value for language', function() {
        openBlog(0);
        openSettings();
        setLanguage(NEW_LANGUAGE);
        // save
        element(by.css('[ng-click="settings.save()"]')).click();
        openSettings();
        expectSelectedLanguageIs(NEW_LANGUAGE);
    });

    it('reset default language value', function() {
        openBlog(0);
        openSettings();
        setLanguage(NEW_LANGUAGE);
        // save a new value
        element(by.css('[ng-click="settings.save()"]')).click();
        openSettings();
        expectSelectedLanguageIs(NEW_LANGUAGE);
        // reset
        element(by.css('[ng-click="settings.reset()"]')).click();
        expectSelectedLanguageIs(DEFAULT_LANGUAGE);
    });

    it('cancel changed language', function() {
        openBlog(0);
        openSettings();
        setLanguage(NEW_LANGUAGE);
        // cancel
        element(by.css('[ng-click="settings.close()"]')).click();
        openSettings();
        expectSelectedLanguageIs(DEFAULT_LANGUAGE);
    });

});
<commit_msg>using the new openUrl from spec/utils<commit_after>var openUrl = require('./helpers/utils').open;
var openBlog = require('./helpers/utils').openBlog;

describe('Blog settings', function() {
    'use strict';

    var DEFAULT_LANGUAGE = 'en';
    var NEW_LANGUAGE = 'fr';

    beforeEach(function(done) {openUrl('/#/liveblog').then(done);});

    function openSettings() {
        // click on the settings button
        element(by.css('.settings-link')).click();
    }

    function expectSelectedLanguageIs(language) {
        expect(element(by.model('settings.blogPreferences.language')).getAttribute('value')).toEqual(language);
    }

    function setLanguage(language) {
        element(by.model('settings.blogPreferences.language')).sendKeys(language);
    }

    it('shows the default language selected', function() {
        openBlog(0);
        openSettings();
        expectSelectedLanguageIs(DEFAULT_LANGUAGE);
    });

    it('save a new value for language', function() {
        openBlog(0);
        openSettings();
        setLanguage(NEW_LANGUAGE);
        // save
        element(by.css('[ng-click="settings.save()"]')).click();
        openSettings();
        expectSelectedLanguageIs(NEW_LANGUAGE);
    });

    it('reset default language value', function() {
        openBlog(0);
        openSettings();
        setLanguage(NEW_LANGUAGE);
        // save a new value
        element(by.css('[ng-click="settings.save()"]')).click();
        openSettings();
        expectSelectedLanguageIs(NEW_LANGUAGE);
        // reset
        element(by.css('[ng-click="settings.reset()"]')).click();
        expectSelectedLanguageIs(DEFAULT_LANGUAGE);
    });

    it('cancel changed language', function() {
        openBlog(0);
        openSettings();
        setLanguage(NEW_LANGUAGE);
        // cancel
        element(by.css('[ng-click="settings.close()"]')).click();
        openSettings();
        expectSelectedLanguageIs(DEFAULT_LANGUAGE);
    });

});
<|endoftext|>


<commit_before>import Appbase from 'appbase-js';

import valueReducer from '@appbaseio/reactivecore/lib/reducers/valueReducer';
import queryReducer from '@appbaseio/reactivecore/lib/reducers/queryReducer';
import queryOptionsReducer from '@appbaseio/reactivecore/lib/reducers/queryOptionsReducer';
import dependencyTreeReducer from '@appbaseio/reactivecore/lib/reducers/dependencyTreeReducer';
import { buildQuery, pushToAndClause } from '@appbaseio/reactivecore/lib/utils/helper';

const componentsWithOptions = [
	'ResultList',
	'ResultCard',
	'ReactiveList',
	'ReactiveMap',
	'SingleList',
	'MultiList',
	'TagCloud',
];

function getValue(state, id, defaultValue) {
	return state ? state[id] : defaultValue;
}

function getQuery(component, value) {
	if (component.customQuery) {
		return component.customQuery(value, component);
	}
	return component.source.defaultQuery
		? component.source.defaultQuery(value, component)
		: null;
}

export default function initReactivesearch(componentCollection, searchState, settings) {
	return new Promise((resolve, reject) => {
		const credentials = settings.url && settings.url.trim() !== '' && !settings.credentials
			? null
			: settings.credentials;
		const config = {
			url: settings.url && settings.url.trim() !== '' ? settings.url : 'https://scalr.api.appbase.io',
			app: settings.app,
			credentials,
			type: settings.type ? settings.type : '*',
		};
		const appbaseRef = new Appbase(config);

		let components = [];
		let selectedValues = {};
		let queryList = {};
		let queryOptions = {};
		let dependencyTree = {};
		let finalQuery = [];
		let orderOfQueries = [];
		let hits = {};
		let aggregations = {};
		let state = {};

		componentCollection.forEach((component) => {
			components = [...components, component.componentId];

			let isInternalComponentPresent = false;
			const internalComponent = `${component.componentId}__internal`;
			const label = component.filterLabel || component.componentId;
			const value = getValue(searchState, label, component.defaultSelected);

			// [1] set selected values
			selectedValues = valueReducer(selectedValues, {
				type: 'SET_VALUE',
				component: component.componentId,
				label,
				value,
				showFilter: component.showFilter || false,
				URLParams: component.URLParams || false,
			});

			// [2] set query options - main component query (valid for result components)
			if (componentsWithOptions.includes(component.type)) {
				const options = component.source.generateQueryOptions
					? component.source.generateQueryOptions(component)
					: null;

				if (options && Object.keys(options).length) {
					const { aggs, size, ...otherQueryOptions } = options;

					if (aggs && Object.keys(aggs).length) {
						isInternalComponentPresent = true;

						// query should be applied on the internal component
						// to enable feeding the data to parent component
						queryOptions = queryOptionsReducer(queryOptions, {
							type: 'SET_QUERY_OPTIONS',
							component: internalComponent,
							options: { aggs, size: size || 100 },
						});
					}

					// sort, size, from - query should be applied on the main component
					if (otherQueryOptions && Object.keys(otherQueryOptions).length) {
						let mainQueryOptions = { ...otherQueryOptions, size };
						if (isInternalComponentPresent) {
							mainQueryOptions = { ...otherQueryOptions };
						}
						queryOptions = queryOptionsReducer(queryOptions, {
							type: 'SET_QUERY_OPTIONS',
							component: component.componentId,
							options: { ...mainQueryOptions },
						});
					}
				}
			}

			// [3] set dependency tree
			if (component.react || isInternalComponentPresent) {
				let { react } = component;
				if (isInternalComponentPresent) {
					react = pushToAndClause(react, internalComponent);
				}

				dependencyTree = dependencyTreeReducer(dependencyTree, {
					type: 'WATCH_COMPONENT',
					component: component.componentId,
					react,
				});
			}

			// [4] set query list
			queryList = queryReducer(queryList, {
				type: 'SET_QUERY',
				component: component.componentId,
				query: getQuery(component, value),
			});
		});

		// [5] Generate finalQuery for search
		componentCollection.forEach((component) => {
			const { queryObj, options } = buildQuery(
				component.componentId,
				dependencyTree,
				queryList,
				queryOptions,
			);

			if (
				(queryObj && Object.keys(queryObj).length)
			|| (options && Object.keys(options).length)
			) {
				orderOfQueries = [...orderOfQueries, component.componentId];
				finalQuery = [
					...finalQuery,
					{},
					{
						query: { ...queryObj },
						...options,
					},
				];
			}
		});

		state = {
			components,
			dependencyTree,
			queryList,
			queryOptions,
			selectedValues,
		};

		appbaseRef.msearch({
			type: config.type === '*' ? '' : config.type,
			body: finalQuery,
		})
			.on('data', (res) => {
				orderOfQueries.forEach((component, index) => {
					const response = res.responses[index];
					if (response.aggregations) {
						aggregations = {
							...aggregations,
							[component]: response.aggregations,
						};
					}
					hits = {
						...hits,
						[component]: {
							hits: response.hits.hits,
							total: response.hits.total,
							time: response.took,
						},
					};
				});
				state = {
					...state,
					hits,
					aggregations,
				};
				resolve(state);
			})
			.on('error', err => reject(err));
	});
}
<commit_msg>Add support for SSR with SelectedFilters<commit_after>import Appbase from 'appbase-js';

import valueReducer from '@appbaseio/reactivecore/lib/reducers/valueReducer';
import queryReducer from '@appbaseio/reactivecore/lib/reducers/queryReducer';
import queryOptionsReducer from '@appbaseio/reactivecore/lib/reducers/queryOptionsReducer';
import dependencyTreeReducer from '@appbaseio/reactivecore/lib/reducers/dependencyTreeReducer';
import { buildQuery, pushToAndClause } from '@appbaseio/reactivecore/lib/utils/helper';

const componentsWithOptions = [
	'ResultList',
	'ResultCard',
	'ReactiveList',
	'ReactiveMap',
	'SingleList',
	'MultiList',
	'TagCloud',
];

function getValue(state, id, defaultValue) {
	return state ? state[id] : defaultValue;
}

function getQuery(component, value) {
	if (component.customQuery) {
		return component.customQuery(value, component);
	}
	return component.source.defaultQuery
		? component.source.defaultQuery(value, component)
		: null;
}

export default function initReactivesearch(componentCollection, searchState, settings) {
	return new Promise((resolve, reject) => {
		const credentials = settings.url && settings.url.trim() !== '' && !settings.credentials
			? null
			: settings.credentials;
		const config = {
			url: settings.url && settings.url.trim() !== '' ? settings.url : 'https://scalr.api.appbase.io',
			app: settings.app,
			credentials,
			type: settings.type ? settings.type : '*',
		};
		const appbaseRef = new Appbase(config);

		let components = [];
		let selectedValues = {};
		let queryList = {};
		let queryOptions = {};
		let dependencyTree = {};
		let finalQuery = [];
		let orderOfQueries = [];
		let hits = {};
		let aggregations = {};
		let state = {};

		componentCollection.forEach((component) => {
			components = [...components, component.componentId];

			let isInternalComponentPresent = false;
			const internalComponent = `${component.componentId}__internal`;
			const label = component.filterLabel || component.componentId;
			const value = getValue(searchState, label, component.defaultSelected);

			// [1] set selected values
			selectedValues = valueReducer(selectedValues, {
				type: 'SET_VALUE',
				component: component.componentId,
				label,
				value,
				showFilter: component.showFilter || true,
				URLParams: component.URLParams || false,
			});

			// [2] set query options - main component query (valid for result components)
			if (componentsWithOptions.includes(component.type)) {
				const options = component.source.generateQueryOptions
					? component.source.generateQueryOptions(component)
					: null;

				if (options && Object.keys(options).length) {
					const { aggs, size, ...otherQueryOptions } = options;

					if (aggs && Object.keys(aggs).length) {
						isInternalComponentPresent = true;

						// query should be applied on the internal component
						// to enable feeding the data to parent component
						queryOptions = queryOptionsReducer(queryOptions, {
							type: 'SET_QUERY_OPTIONS',
							component: internalComponent,
							options: { aggs, size: size || 100 },
						});
					}

					// sort, size, from - query should be applied on the main component
					if (otherQueryOptions && Object.keys(otherQueryOptions).length) {
						let mainQueryOptions = { ...otherQueryOptions, size };
						if (isInternalComponentPresent) {
							mainQueryOptions = { ...otherQueryOptions };
						}
						queryOptions = queryOptionsReducer(queryOptions, {
							type: 'SET_QUERY_OPTIONS',
							component: component.componentId,
							options: { ...mainQueryOptions },
						});
					}
				}
			}

			// [3] set dependency tree
			if (component.react || isInternalComponentPresent) {
				let { react } = component;
				if (isInternalComponentPresent) {
					react = pushToAndClause(react, internalComponent);
				}

				dependencyTree = dependencyTreeReducer(dependencyTree, {
					type: 'WATCH_COMPONENT',
					component: component.componentId,
					react,
				});
			}

			// [4] set query list
			queryList = queryReducer(queryList, {
				type: 'SET_QUERY',
				component: component.componentId,
				query: getQuery(component, value),
			});
		});

		// [5] Generate finalQuery for search
		componentCollection.forEach((component) => {
			const { queryObj, options } = buildQuery(
				component.componentId,
				dependencyTree,
				queryList,
				queryOptions,
			);

			if (
				(queryObj && Object.keys(queryObj).length)
			|| (options && Object.keys(options).length)
			) {
				orderOfQueries = [...orderOfQueries, component.componentId];
				finalQuery = [
					...finalQuery,
					{},
					{
						query: { ...queryObj },
						...options,
					},
				];
			}
		});

		state = {
			components,
			dependencyTree,
			queryList,
			queryOptions,
			selectedValues,
		};

		appbaseRef.msearch({
			type: config.type === '*' ? '' : config.type,
			body: finalQuery,
		})
			.on('data', (res) => {
				orderOfQueries.forEach((component, index) => {
					const response = res.responses[index];
					if (response.aggregations) {
						aggregations = {
							...aggregations,
							[component]: response.aggregations,
						};
					}
					hits = {
						...hits,
						[component]: {
							hits: response.hits.hits,
							total: response.hits.total,
							time: response.took,
						},
					};
				});
				state = {
					...state,
					hits,
					aggregations,
				};
				resolve(state);
			})
			.on('error', err => reject(err));
	});
}
<|endoftext|>


<commit_before>module.exports = function(grunt) {

	'use strict';

	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		paths: {
			bower: 'bower_components',
			modules: 'src/modules',
			output: 'dist'
		},

		uglify: {
			options: {
				preserveComments: false,
				banner: '/**\n' +
					' * <%= pkg.name %> - <%= pkg.description %>\n' +
					' *\n' +
					' * @author <%= pkg.author.name %> - <%= pkg.author.url %>\n' +
					' * @see <%= pkg.homepage %>\n' +
					' * @version <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd") %>)\n' +
					' */\n',
				footer: '\nwindow.AdManager = admanager.bootstrap.init;'
			},
			build: {
				files: {
					'<%= paths.output %>/admanager.js': [ '<%= paths.modules %>/*.js' ]
				}
			}
		},
		watch: {
			scripts: {
				files: [
					'<%= paths.modules %>/*',
					'<%= paths.bower %>/*'
				],
				tasks: ['uglify'],
			},
		},
	});

	// grunt plugins
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-watch');

	// Tasks
	grunt.registerTask('default', ['uglify', 'watch']);

};<commit_msg>Create banner templates for reuse<commit_after>module.exports = function(grunt) {

	'use strict';

	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		comments: {
			banner: '/**\n' +
				' * <%= pkg.name %> - <%= pkg.description %>\n' +
				' *\n' +
				' * @author <%= pkg.author.name %> - <%= pkg.author.url %>\n' +
				' * @see <%= pkg.homepage %>\n' +
				' * @version <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd") %>)\n' +
				' */\n',
			footer: '\nwindow.AdManager = admanager.bootstrap.init;'
		},
		paths: {
			bower: 'bower_components',
			modules: 'src/modules',
			output: 'dist'
		},

		uglify: {
			options: {
				preserveComments: false,
				banner: '<%= comments.banner %>',
				footer: '<%= comments.footer %>'
			},
			build: {
				files: {
					'<%= paths.output %>/admanager.js': [ '<%= paths.modules %>/*.js' ]
				}
			}
		},
		watch: {
			scripts: {
				files: [
					'<%= paths.modules %>/*',
					'<%= paths.bower %>/*'
				],
				tasks: ['uglify'],
			},
		},
	});

	// grunt plugins
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-watch');

	// Tasks
	grunt.registerTask('default', ['uglify', 'watch']);

};<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

import * as actions from 'reduxes/actions';

import Paper from 'src/Paper';
import FlatButton from 'src/FlatButton';

import 'sass/containers/landing/sections/LandingExamples.scss';

class LandingExamples extends Component {

    constructor(props) {

        super(props);

        this.goToDemo = ::this.goToDemo;

    }

    goToDemo() {
        this.props.routerPush('/components');
    }

    render() {
        return (

Examples

                    <FlatButton className="ghost-button"
                                value="Go to Demo"
                                onTouchTap={this.goToDemo}/>

                    <Paper className="landing-examples-demo"
                           depth={4}>

                    </Paper>

        );
    }
}

LandingExamples.propTypes = {
    routerPush: PropTypes.func
};

function mapStateToProps(state, ownProps) {
    return {};
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators(actions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(LandingExamples);<commit_msg>update LandingExamples<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

import * as actions from 'reduxes/actions';

import Paper from 'src/Paper';
import FlatButton from 'src/FlatButton';

import 'sass/containers/landing/sections/LandingExamples.scss';

class LandingExamples extends Component {

    constructor(props) {

        super(props);

        this.goToDemo = ::this.goToDemo;

    }

    goToDemo() {
        this.props.routerPush('/components');
    }

    render() {
        return (

Examples

                    <FlatButton className="ghost-button"
                                value="Go to Demo"
                                onTouchTap={this.goToDemo}/>

                    <Paper className="landing-examples-demo"
                           depth={4}>

                    </Paper>

        );
    }
}

LandingExamples.propTypes = {
    routerPush: PropTypes.func
};

export default connect(state = ({}), dispatch => bindActionCreators({
    routerPush: actions.routerPush
}, dispatch))(LandingExamples);<|endoftext|>