diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..c7a0b0c --- /dev/null +++ b/.babelrc @@ -0,0 +1,14 @@ +{ + "presets": ["es2015", "react", "stage-2"], + "plugins": [ + ["transform-object-rest-spread", { "useBuiltIns": true }], + ["add-module-exports"] + ], + "env": { + "test": { + "plugins": [ + "istanbul" + ] + } + } +} \ No newline at end of file diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c3b073c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# EditorConfig - http://EditorConfig.org + +root = true + +[*] +end_of_line = lf +insert_final_newline = true + +[**.html] +indent_style = space +indent_size = 4 + +[**.js] +indent_style = space +indent_size = 2 diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..16f01ec --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,29 @@ +const fs = require('fs'); + +const prettierOptions = JSON.parse(fs.readFileSync('./.prettierrc', 'utf8')); + +module.exports = { + extends: ['last', 'prettier', 'prettier/react', 'plugin:react/recommended'], + plugins: ['react', 'prettier'], + env: { + browser: true, + }, + globals: { + describe: true, + it: true, + module: true, + exports: true, + require: true + }, + rules: { + 'prettier/prettier': ['error', prettierOptions], + 'no-unused-vars': [ + 'off', + { + vars: 'all', + args: 'after-used', + ignoreRestSiblings: false + } + ] + } +}; diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index e0094c4..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -dist/** -diff merge=binary diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md new file mode 100644 index 0000000..fdba6d3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Bug_report.md @@ -0,0 +1,22 @@ +--- +name: Bug report +about: Submit a bug you found using the package + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Please clone your layout and use of react-infinite-scroller by forking [this Code Sandbox](https://codesandbox.io/s/my6vo3yo78) and linking it here. Doing so will massively expedite getting the bug fixed! 👊 + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Device (please complete the following information):** + - OS: [e.g. Mac] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] diff --git a/.github/ISSUE_TEMPLATE/Feature_request.md b/.github/ISSUE_TEMPLATE/Feature_request.md new file mode 100644 index 0000000..5384295 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..60c6074 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,23 @@ +name: Test + +on: + pull_request: + branches: [master] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Cache node modules + id: cache + uses: actions/cache@v2 + with: + path: node_modules + key: cache-node-modules-${{ hashFiles('package-lock.json') }} + - name: npm install + if: steps.cache.outputs.cache-hit != 'true' + run: npm ci + - run: npm run lint + - run: npm run test + - run: npm run build diff --git a/.gitignore b/.gitignore index 299aea9..19880bb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ -npm-debug.log node_modules +npm-debug.log .DS_Store +.idea +.nyc_output +coverage diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..c75bb0e --- /dev/null +++ b/.npmignore @@ -0,0 +1,5 @@ +coverage +test +.nyc_output +docs +.eslintrc.js diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..1b0cca8 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,7 @@ +{ + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "singleQuote": true +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..e57b3bd --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "prettier.eslintIntegration": true, + "editor.formatOnSave": true +} diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index d3f827e..0000000 --- a/Gruntfile.js +++ /dev/null @@ -1,97 +0,0 @@ -module.exports = function (grunt) { - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - browserify: { - dist: { - files: { - 'dist/react-infinite-scroll.js': ['src/umd.js'] - }, - } - }, - uglify: { - options: { - banner: '/*! <%= pkg.name %> - v <%= pkg.version %> - <%= pkg.author %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' - }, - dist: { - files: { - 'dist/react-infinite-scroll.min.js': ['dist/react-infinite-scroll.js'] - } - } - }, - clean: ['dist/react-infinite-scroll.js'], - mochaTest: { - all: { - options: { - reporter: 'spec' - }, - src: ['test/**/*.js', '!test/mock/**'] - } - }, - jshint: { - options: { - indent: 2, - camelcase: true, - nonew: true, - plusplus: true, - quotmark: true, - bitwise: true, - forin: true, - curly: true, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - undef: true, - unused: true, - regexp: true, - trailing: true, - node: true, - browser: true - }, - gruntfile: { - files: { - src: ['Gruntfile.js'] - } - }, - dev: { - files: { - src: ['src/**/*.js'] - }, - options: { - debug: true, - devel: true - } - }, - dist: { - files: { - src: ['src/**/*.js'] - } - }, - test: { - files: { - src: ['test/**/*.js'] - }, - options: { - globals: { - describe: true, - it: true, - before: true, - after: true, - beforeEach: true, - afterEach: true - } - } - } - } - }); - - grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-browserify'); - grunt.loadNpmTasks('grunt-contrib-uglify'); - grunt.loadNpmTasks('grunt-contrib-clean'); - - grunt.registerTask('lint', ['jshint']); - grunt.registerTask('dist', ['browserify', 'uglify', 'clean']); - grunt.registerTask('default', ['jshint', 'dist']); -}; \ No newline at end of file diff --git a/LICENSE b/LICENSE index cd2cd3d..2014a14 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,6 @@ The MIT License (MIT) +Copyright (c) 2016 Dan Bovey Copyright (c) 2013 guillaumervls Permission is hereby granted, free of charge, to any person obtaining a copy of diff --git a/README.md b/README.md index bb4dfdf..8fee7f3 100644 --- a/README.md +++ b/README.md @@ -1,103 +1,134 @@ -React Infinite Scroll -===================== +# React Infinite Scroller -*React infinite scroll component* +[![npm](https://img.shields.io/npm/dt/react-infinite-scroller.svg?style=flat-square)](https://www.npmjs.com/package/react-infinite-scroller) +[![npm](https://img.shields.io/npm/v/react-infinite-scroller.svg?style=flat-square)](https://www.npmjs.com/package/react-infinite-scroller) +[![npm](https://img.shields.io/npm/l/react-infinite-scroller.svg?style=flat-square)](https://github.com/danbovey/react-infinite-scroller/blob/master/LICENSE) -Demo: http://jsfiddle.net/mb9vJ/2 +Infinitely load a grid or list of items in React. This component allows you to create a simple, lightweight infinite scrolling page or element by supporting both window and scrollable elements. -# Getting started +- ⏬ Ability to use window or a scrollable element +- 📏 No need to specify item heights +- 💬 Support for "chat history" (reverse) mode +- ✅ Fully unit tested and used in hundreds of production sites around the + world! +- 📦 Lightweight alternative to other available React scroll libs ~ 2.2KB + minified & gzipped -### Classic : +--- -The "ready to use" [script file](https://raw.github.com/guillaumervls/react-infinite-scroll/master/dist/react-infinite-scroll.min.js) -is in the `dist` folder. +- [Demo](https://danbovey.uk/react-infinite-scroller/demo/) +- [Demo Source](https://github.com/danbovey/react-infinite-scroller/blob/master/docs/src/index.js) -Then : -```html - - -``` - -### [Browserify](https://github.com/substack/node-browserify) : -̀ -Install : `npm install react-infinite-scroll` +## Installation -Then : -```javascript -InfiniteScroll = require('react-infinite-scroll')(React); +``` +npm install react-infinite-scroller --save +``` +``` +yarn add react-infinite-scroller ``` -### Also works with AMD (e.g [RequireJS](http://requirejs.org)) - -In this case, it will depend on `react`. +## How to use +```js +import InfiniteScroll from 'react-infinite-scroller'; +``` -# Use in JSX +### Window scroll events -```html +```js Loading ...}> - {items} // <-- This is the "stuff" you want to load + loader={
Loading ...
} +> + {items} // <-- This is the content you want to load
``` -- `pageStart` : The page number corresponding to the initial `items`, defaults to `0` - which means that for the first loading, `loadMore` will be called with `1` - -- `loadMore(pageToLoad)` : This function is called when the user scrolls down - and we need to load stuff - -- `hasMore` : Boolean stating if we should keep listening to scroll event and - trying to load more stuff - -- `loader` : Loader element to be displayed while loading stuff - You can use - `InfiniteScroll.setDefaultLoader(loader);` to set a defaut loader - for all your `InfiniteScroll` components - -- `threshold` : The distance between the bottom of the page and the bottom of the - window's viewport that triggers the loading of new stuff - - *Defaults to `250`* - - -## Changelog - -### v0.1.0 - -`loader` now takes a React component -(no more component constructor or object `{component:... , props:... , ...}`). - - -## (Re)build - -``` -npm install -grunt dist +### DOM scroll events + +```js +
+ Loading ...
} + useWindow={false} + > + {items} + + ``` -### Licence +### Custom parent element + +You can define a custom `parentNode` element to base the scroll calulations on. + +```js +
this.scrollParentRef = ref}> +
+ Loading ...
} + useWindow={false} + getScrollParent={() => this.scrollParentRef} + > + {items} + +
+ +``` -**The MIT License (MIT)** +## Props + +| Name | Required | Type | Default | Description | +| :---------------- | :------- | :----------- | :-------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `children`       | Yes | `Node`   |           | Anything that can be rendered (same as PropType's Node) | +| `loadMore`       | Yes | `Function`   |           | A callback when more items are requested by the user. Receives a single parameter specifying the page to load e.g. `function handleLoadMore(page) { /* load more items here */ }` } | +| `element` | | `Component` | `'div'` | Name of the element that the component should render as. | +| `hasMore` | | `Boolean` | `false` | Whether there are more items to be loaded. Event listeners are removed if `false`. | +| `initialLoad` | | `Boolean` | `true` | Whether the component should load the first set of items. | +| `isReverse` | | `Boolean` | `false` | Whether new items should be loaded when user scrolls to the top of the scrollable area. | +| `loader` | | `Component` | | A React component to render while more items are loading. The parent component must have a unique key prop. | +| `pageStart` | | `Number` | `0` | The number of the first page to load, With the default of `0`, the first page is `1`. | +| `getScrollParent` | | `Function` | | Override method to return a different scroll listener if it's not the immediate parent of InfiniteScroll. | +| `threshold` | | `Number` | `250` | The distance in pixels before the end of the items that will trigger a call to `loadMore`. | +| `useCapture` | | `Boolean` | `false` | Proxy to the `useCapture` option of the added event listeners. | +| `useWindow` | | `Boolean` | `true` | Add scroll listeners to the window, or else, the component's `parentNode`. | + +## Troubleshooting + +### Double or non-stop calls to `loadMore` + +If you experience double or non-stop calls to your `loadMore` callback, make +sure you have your CSS layout working properly before adding this component in. +Calculations are made based on the height of the container (the element the +component creates to wrap the items), so the height of the container must equal +the entire height of the items. + +```css +.my-container { + overflow: auto; +} +``` -*Copyright (c) 2013 guillaumervls* +Some people have found success using [react-infinite-scroll-component](https://github.com/ankeetmaini/react-infinite-scroll-component). -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: +### But you should just add an `isLoading` prop! -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +This component doesn't make any assumptions about what you do in terms of API +calls. It's up to you to store whether you are currently loading items from an +API in your state/reducers so that you don't make overlapping API calls. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +```js +loadMore() { + if(!this.state.isLoading) { + this.props.fetchItems(); + } +} +``` diff --git a/dist/InfiniteScroll.js b/dist/InfiniteScroll.js new file mode 100644 index 0000000..462ef57 --- /dev/null +++ b/dist/InfiniteScroll.js @@ -0,0 +1,437 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function() { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function(Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; +})(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; +} + +function _objectWithoutProperties(obj, keys) { + var target = {}; + for (var i in obj) { + if (keys.indexOf(i) >= 0) continue; + if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; + target[i] = obj[i]; + } + return target; +} + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } +} + +function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError( + "this hasn't been initialised - super() hasn't been called" + ); + } + return call && (typeof call === 'object' || typeof call === 'function') + ? call + : self; +} + +function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError( + 'Super expression must either be null or a function, not ' + + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); +} + +var InfiniteScroll = (function(_Component) { + _inherits(InfiniteScroll, _Component); + + function InfiniteScroll(props) { + _classCallCheck(this, InfiniteScroll); + + var _this = _possibleConstructorReturn( + this, + (InfiniteScroll.__proto__ || Object.getPrototypeOf(InfiniteScroll)).call( + this, + props + ) + ); + + _this.scrollListener = _this.scrollListener.bind(_this); + _this.eventListenerOptions = _this.eventListenerOptions.bind(_this); + _this.mousewheelListener = _this.mousewheelListener.bind(_this); + return _this; + } + + _createClass(InfiniteScroll, [ + { + key: 'componentDidMount', + value: function componentDidMount() { + this.pageLoaded = this.props.pageStart; + this.options = this.eventListenerOptions(); + this.attachScrollListener(); + } + }, + { + key: 'componentDidUpdate', + value: function componentDidUpdate() { + if (this.props.isReverse && this.loadMore) { + var parentElement = this.getParentElement(this.scrollComponent); + parentElement.scrollTop = + parentElement.scrollHeight - + this.beforeScrollHeight + + this.beforeScrollTop; + this.loadMore = false; + } + this.attachScrollListener(); + } + }, + { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.detachScrollListener(); + this.detachMousewheelListener(); + } + }, + { + key: 'isPassiveSupported', + value: function isPassiveSupported() { + var passive = false; + + var testOptions = { + get passive() { + passive = true; + } + }; + + try { + document.addEventListener('test', null, testOptions); + document.removeEventListener('test', null, testOptions); + } catch (e) { + // ignore + } + return passive; + } + }, + { + key: 'eventListenerOptions', + value: function eventListenerOptions() { + var options = this.props.useCapture; + + if (this.isPassiveSupported()) { + options = { + useCapture: this.props.useCapture, + passive: true + }; + } else { + options = { + passive: false + }; + } + return options; + } + + // Set a defaut loader for all your `InfiniteScroll` components + }, + { + key: 'setDefaultLoader', + value: function setDefaultLoader(loader) { + this.defaultLoader = loader; + } + }, + { + key: 'detachMousewheelListener', + value: function detachMousewheelListener() { + var scrollEl = window; + if (this.props.useWindow === false) { + scrollEl = this.scrollComponent.parentNode; + } + + scrollEl.removeEventListener( + 'mousewheel', + this.mousewheelListener, + this.options ? this.options : this.props.useCapture + ); + } + }, + { + key: 'detachScrollListener', + value: function detachScrollListener() { + var scrollEl = window; + if (this.props.useWindow === false) { + scrollEl = this.getParentElement(this.scrollComponent); + } + + scrollEl.removeEventListener( + 'scroll', + this.scrollListener, + this.options ? this.options : this.props.useCapture + ); + scrollEl.removeEventListener( + 'resize', + this.scrollListener, + this.options ? this.options : this.props.useCapture + ); + } + }, + { + key: 'getParentElement', + value: function getParentElement(el) { + var scrollParent = + this.props.getScrollParent && this.props.getScrollParent(); + if (scrollParent != null) { + return scrollParent; + } + return el && el.parentNode; + } + }, + { + key: 'filterProps', + value: function filterProps(props) { + return props; + } + }, + { + key: 'attachScrollListener', + value: function attachScrollListener() { + var parentElement = this.getParentElement(this.scrollComponent); + + if (!this.props.hasMore || !parentElement) { + return; + } + + var scrollEl = window; + if (this.props.useWindow === false) { + scrollEl = parentElement; + } + + scrollEl.addEventListener( + 'mousewheel', + this.mousewheelListener, + this.options ? this.options : this.props.useCapture + ); + scrollEl.addEventListener( + 'scroll', + this.scrollListener, + this.options ? this.options : this.props.useCapture + ); + scrollEl.addEventListener( + 'resize', + this.scrollListener, + this.options ? this.options : this.props.useCapture + ); + + if (this.props.initialLoad) { + this.scrollListener(); + } + } + }, + { + key: 'mousewheelListener', + value: function mousewheelListener(e) { + // Prevents Chrome hangups + // See: https://stackoverflow.com/questions/47524205/random-high-content-download-time-in-chrome/47684257#47684257 + if (e.deltaY === 1 && !this.isPassiveSupported()) { + e.preventDefault(); + } + } + }, + { + key: 'scrollListener', + value: function scrollListener() { + var el = this.scrollComponent; + var scrollEl = window; + var parentNode = this.getParentElement(el); + + var offset = void 0; + if (this.props.useWindow) { + var doc = + document.documentElement || + document.body.parentNode || + document.body; + var scrollTop = + scrollEl.pageYOffset !== undefined + ? scrollEl.pageYOffset + : doc.scrollTop; + if (this.props.isReverse) { + offset = scrollTop; + } else { + offset = this.calculateOffset(el, scrollTop); + } + } else if (this.props.isReverse) { + offset = parentNode.scrollTop; + } else { + offset = + el.scrollHeight - parentNode.scrollTop - parentNode.clientHeight; + } + + // Here we make sure the element is visible as well as checking the offset + if ( + offset < Number(this.props.threshold) && + el && + el.offsetParent !== null + ) { + this.detachScrollListener(); + this.beforeScrollHeight = parentNode.scrollHeight; + this.beforeScrollTop = parentNode.scrollTop; + // Call loadMore after detachScrollListener to allow for non-async loadMore functions + if (typeof this.props.loadMore === 'function') { + this.props.loadMore((this.pageLoaded += 1)); + this.loadMore = true; + } + } + } + }, + { + key: 'calculateOffset', + value: function calculateOffset(el, scrollTop) { + if (!el) { + return 0; + } + + return ( + this.calculateTopPosition(el) + + (el.offsetHeight - scrollTop - window.innerHeight) + ); + } + }, + { + key: 'calculateTopPosition', + value: function calculateTopPosition(el) { + if (!el) { + return 0; + } + return el.offsetTop + this.calculateTopPosition(el.offsetParent); + } + }, + { + key: 'render', + value: function render() { + var _this2 = this; + + var renderProps = this.filterProps(this.props); + + var children = renderProps.children, + element = renderProps.element, + hasMore = renderProps.hasMore, + initialLoad = renderProps.initialLoad, + isReverse = renderProps.isReverse, + loader = renderProps.loader, + loadMore = renderProps.loadMore, + pageStart = renderProps.pageStart, + ref = renderProps.ref, + threshold = renderProps.threshold, + useCapture = renderProps.useCapture, + useWindow = renderProps.useWindow, + getScrollParent = renderProps.getScrollParent, + props = _objectWithoutProperties(renderProps, [ + 'children', + 'element', + 'hasMore', + 'initialLoad', + 'isReverse', + 'loader', + 'loadMore', + 'pageStart', + 'ref', + 'threshold', + 'useCapture', + 'useWindow', + 'getScrollParent' + ]); + + props.ref = function(node) { + _this2.scrollComponent = node; + if (ref) { + ref(node); + } + }; + + var childrenArray = [children]; + if (hasMore) { + if (loader) { + isReverse + ? childrenArray.unshift(loader) + : childrenArray.push(loader); + } else if (this.defaultLoader) { + isReverse + ? childrenArray.unshift(this.defaultLoader) + : childrenArray.push(this.defaultLoader); + } + } + return _react2.default.createElement(element, props, childrenArray); + } + } + ]); + + return InfiniteScroll; +})(_react.Component); + +InfiniteScroll.propTypes = { + children: _propTypes2.default.node.isRequired, + element: _propTypes2.default.node, + hasMore: _propTypes2.default.bool, + initialLoad: _propTypes2.default.bool, + isReverse: _propTypes2.default.bool, + loader: _propTypes2.default.node, + loadMore: _propTypes2.default.func.isRequired, + pageStart: _propTypes2.default.number, + ref: _propTypes2.default.func, + getScrollParent: _propTypes2.default.func, + threshold: _propTypes2.default.number, + useCapture: _propTypes2.default.bool, + useWindow: _propTypes2.default.bool +}; +InfiniteScroll.defaultProps = { + element: 'div', + hasMore: false, + initialLoad: true, + pageStart: 0, + ref: null, + threshold: 250, + useWindow: true, + isReverse: false, + useCapture: false, + loader: null, + getScrollParent: null +}; +exports.default = InfiniteScroll; +module.exports = exports['default']; diff --git a/dist/react-infinite-scroll.min.js b/dist/react-infinite-scroll.min.js deleted file mode 100644 index a85de9a..0000000 --- a/dist/react-infinite-scroll.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! react-infinite-scroll - v 0.1.3 - guillaumervls 2014-04-07 */ -!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g + + + + + + + React Infinite Scroller + + + + + + + + + + +
+

Demo

+

+ The source code to this demo can be found in the repo's + docs folder. + + Below, the component infinite scrolls React's Github issues. +

+
+ +
+
+
+ + + + + diff --git a/docs/gulpfile.js b/docs/gulpfile.js new file mode 100644 index 0000000..a1c51b0 --- /dev/null +++ b/docs/gulpfile.js @@ -0,0 +1,17 @@ +var gulp = require('gulp'); +var rename = require('gulp-rename'); +var source = require('vinyl-source-stream') +var buffer = require('vinyl-buffer') +var browserify = require('browserify'); +var babelify = require('babelify'); + +gulp.task('js', function() { + return browserify('src/index.js').transform(babelify, {presets: ["es2015", "react"]}) + .bundle() + .pipe(source('index.js')) + .pipe(buffer()) + .pipe(rename('script.js')) + .pipe(gulp.dest('./js')); +}); + +gulp.task('default', gulp.series('js')); diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..2884345 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,219 @@ + + + + + + + + React Infinite Scroller + + + + + + + + + + +
+

+ + npm + + + React Version + + + npm + + + npm + +

+ +

Infinitely load content using a React Component. This fork maintains a simple, lightweight infinite scroll + package that supports both window and scrollable elements.

+ +

+ + Installation +

+ +
npm i react-infinite-scroller
+ +

+ + How to use +

+ +
import InfiniteScroll from 'react-infinite-scroller'
+ +

+ + Window scroll events +

+ +
+
<InfiniteScroll
+    pageStart={0}
+    loadMore={loadFunc}
+    hasMore={true || false}
+    loader={<div className="loader">Loading ...</div>}>
+  {items} // <-- This is the content you want to load
+</InfiniteScroll>
+
+ +

+ + DOM scroll events +

+ +
+
<div style="height:700px;overflow:auto;">
+  <InfiniteScroll
+      pageStart={0}
+      loadMore={loadFunc}
+      hasMore={true || false}
+      loader={<div className="loader">Loading ...</div>}
+      useWindow={false}>
+    {items}
+  </InfiniteScroll>
+</div>
+
+ +

+ + Props +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDefaultDescription
elementString'div'Name of the element that the component should render as.
hasMoreBooleanfalseWhether there are more items to be loaded. Event listeners are removed if false. +
initialLoadBooleantrueWhether the component should load the first set of items.
loadMoreFunctionA callback when more items are requested by the user.
pageStartObject0The number of the first page to load, With the default of 0, the first page is + 1. +
thresholdNumber250The distance in pixels before the end of the items that will trigger a call to + loadMore. +
useWindowBooleantrueAdd scroll listeners to the window, or else, the component's parentNode.
+ + +
+ + + + + + + + + + diff --git a/docs/js/script.js b/docs/js/script.js new file mode 100644 index 0000000..6f18630 --- /dev/null +++ b/docs/js/script.js @@ -0,0 +1,38468 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 1: rel 2: next + var m = p.match(/\s*(.+)\s*=\s*"?([^"]+)"?/) + if (m) acc[m[1]] = m[2]; + return acc; +} + +function parseLink(link) { + try { + var m = link.match(/]*)>(.*)/) + , linkUrl = m[1] + , parts = m[2].split(';') + , parsedUrl = url.parse(linkUrl) + , qry = qs.parse(parsedUrl.query); + + parts.shift(); + + var info = parts + .reduce(createObjects, {}); + + info = xtend(qry, info); + info.url = linkUrl; + return info; + } catch (e) { + return null; + } +} + +function checkHeader(linkHeader){ + if (!linkHeader) return false; + + if (linkHeader.length > PARSE_LINK_HEADER_MAXLEN) { + if (PARSE_LINK_HEADER_THROW_ON_MAXLEN_EXCEEDED) { + throw new Error('Input string too long, it should be under ' + PARSE_LINK_HEADER_MAXLEN + ' characters.'); + } else { + return false; + } + } + return true; +} + +module.exports = function (linkHeader) { + if (!checkHeader(linkHeader)) return null; + + return linkHeader.split(/,\s* 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],3:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],4:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],5:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],6:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":4,"./encode":5}],7:[function(require,module,exports){ +(function (process){ +/** + * @license React + * react-dom.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { + + 'use strict'; + +/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ +if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === + 'function' +) { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); +} + var React = require('react'); +var Scheduler = require('scheduler'); + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var suppressWarning = false; +function setSuppressWarning(newSuppressWarning) { + { + suppressWarning = newSuppressWarning; + } +} // In DEV, calls to console.warn and console.error get replaced +// by calls to these methods by a Babel plugin. +// +// In PROD (or in packages without access to React internals), +// they are left as they are instead. + +function warn(format) { + { + if (!suppressWarning) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } + } +} +function error(format) { + { + if (!suppressWarning) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +var FunctionComponent = 0; +var ClassComponent = 1; +var IndeterminateComponent = 2; // Before we know whether it is function or class + +var HostRoot = 3; // Root of a host tree. Could be nested inside another node. + +var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. + +var HostComponent = 5; +var HostText = 6; +var Fragment = 7; +var Mode = 8; +var ContextConsumer = 9; +var ContextProvider = 10; +var ForwardRef = 11; +var Profiler = 12; +var SuspenseComponent = 13; +var MemoComponent = 14; +var SimpleMemoComponent = 15; +var LazyComponent = 16; +var IncompleteClassComponent = 17; +var DehydratedFragment = 18; +var SuspenseListComponent = 19; +var ScopeComponent = 21; +var OffscreenComponent = 22; +var LegacyHiddenComponent = 23; +var CacheComponent = 24; +var TracingMarkerComponent = 25; + +// ----------------------------------------------------------------------------- +var enableClientRenderFallbackOnTextMismatch = true; // Recoil still uses useMutableSource in www, need to delete +// the react-reconciler package. + +var enableNewReconciler = false; // Support legacy Primer support on internal FB www + +var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics. + +var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber + +var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz +// React DOM Chopping Block +// +// Similar to main Chopping Block but only flags related to React DOM. These are +// grouped because we will likely batch all of them into a single major release. +// ----------------------------------------------------------------------------- +// Disable support for comment nodes as React DOM containers. Already disabled +// in open source, but www codebase still relies on it. Need to remove. + +var disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection. +// and client rendering, mostly to allow JSX attributes to apply to the custom +// element's object properties instead of only HTML attributes. +// https://github.com/facebook/react/issues/11347 + +var enableCustomElementPropertySupport = false; // Disables children for