mirror of
https://github.com/gosticks/react-table.git
synced 2026-08-19 08:20:30 +00:00
Compare commits
+1
-1
@@ -1,3 +1,3 @@
|
||||
module.exports = {
|
||||
extends: 'react-tools'
|
||||
extends: 'react-tools',
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Codesandbox!**
|
||||
Use a new [react-table codesandbox](codesandbox.io/s/X6npLXPRW) to reproduce the issue.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
name: Questions, Support & Help
|
||||
about: Looking for help? Need a question answered?
|
||||
|
||||
---
|
||||
|
||||
STOP!!!
|
||||
|
||||
Github issues is no place for general support. We encourage you to use our public support forum at https://spectrum.chat/react-table.
|
||||
|
||||
NOTE: If a support/help/question issue is opened, it will be closed immediately and be redirected to the forum. Thanks for helping us keep our issues clean and productive!
|
||||
@@ -1,8 +1,11 @@
|
||||
node_modules/
|
||||
lib/
|
||||
es/
|
||||
docs/build
|
||||
react-table.js
|
||||
react-table.min.js
|
||||
react-table.css
|
||||
*.log
|
||||
.idea
|
||||
.DS_Store
|
||||
.history
|
||||
|
||||
+79
-4
@@ -1,81 +1,156 @@
|
||||
## 6.7.5
|
||||
## 6.10.3
|
||||
|
||||
- Further improve `normalizeComponent` function
|
||||
|
||||
## 6.10.2
|
||||
|
||||
- Fixed regression found in `normalizeComponent` function fix
|
||||
|
||||
## 6.10.1
|
||||
|
||||
- Fixed issues with `normalizeComponent` function
|
||||
|
||||
## 6.10.0
|
||||
|
||||
- Rebased volatile commits out of 6.9.0
|
||||
- Merged (hopefully) non-breaking fixes after rebasing and reverting.
|
||||
|
||||
## 6.9.0
|
||||
|
||||
This version has been reverted due to some major bugs that were introduced with it.
|
||||
|
||||
## 6.8.6
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- Since `resolveData` is now capable of materializing data on it's own, the `data` prop is no longer required as a prop-type.
|
||||
|
||||
## 6.8.4
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- Only run `resolveData` prop when `data` prop has changed, not any others.
|
||||
|
||||
## 6.8.3
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- Allow the `resolveData` prop to alter or materialize new data when the `data` prop changes.
|
||||
|
||||
## 6.8.1
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- Updated eslint and code formatting
|
||||
|
||||
## 6.7.5
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- Now passes `column` to `getResizerProps` (#667)
|
||||
- NOTE: `getResizerProps` is now only called if the column is resizable
|
||||
- Fixes the `className` ordering in defaultProps for ThComponent (#673)
|
||||
- NOTE: user supplied classNames now come at the end so they can extend the defaults
|
||||
|
||||
## 6.7.4
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- Fix Prop types for columns
|
||||
|
||||
## 6.7.3
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- Fix the rest of the proptypes
|
||||
|
||||
## 6.7.2
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- `getPropTypes` proptype check
|
||||
|
||||
## 6.7.1
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- `eslint-config` moved to dev deps
|
||||
|
||||
## 6.7.0
|
||||
|
||||
## 6.7.0-alpha-0
|
||||
|
||||
#### New Features
|
||||
|
||||
- Expose page/pageSize to rows/cells
|
||||
- Supply sort direction to custom sort methods
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- README updates
|
||||
- Linter cleanup
|
||||
- Added PropTypes node module
|
||||
- Deps, linting and style upgrades
|
||||
|
||||
## 6.6.0
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- moved repo to react-tools
|
||||
- Doc examples moved to codesandbox.io
|
||||
- README updates
|
||||
- CSS refacting for rt-tfoot to match rt-thead
|
||||
- CSS more specific for input and select
|
||||
|
||||
## 6.5.3
|
||||
## 6.5.3
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- `onClick` proxying and eslint
|
||||
|
||||
## 6.5.2
|
||||
|
||||
#### New Features
|
||||
|
||||
- Provide onClick handleOriginal function - #406
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- README updates
|
||||
- `makePathArray` in utils - #326
|
||||
- Various fixes: #294, #376, #398, #415,
|
||||
- Various fixes: #294, #376, #398, #415,
|
||||
|
||||
## 6.5.1
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
- `defaultExpanded` now works correctly - #372
|
||||
- `column.getProps().rest` props are now applied correctly
|
||||
- `makeTemplateComponent` now supports `displayName` - #289
|
||||
|
||||
## 6.5.0
|
||||
|
||||
##### New Features
|
||||
|
||||
- `column.filterAll` - defaults to `false`, but when set to `true` will provide the entire array of rows to `filterMethod` as opposed to one row at a time. This allows for more fine-grained filtering using any method you can dream up. See the [Custom Filtering example](https://react-table.js.org/#/story/custom-filtering) for more info.
|
||||
|
||||
## 6.4.0
|
||||
|
||||
##### New Features
|
||||
|
||||
- `PadRowComponent` - the content rendered inside of a padding row. Defaults to a react component that renders ` `
|
||||
|
||||
## 6.3.0
|
||||
|
||||
##### New Features
|
||||
|
||||
- `defaultSortDesc` - allows you to set the default sorting direction for all columns to descending.
|
||||
- `column.defaultSortDesc` - allows you to set the default sorting direction for a specific column. Falls back to the global `defaultSortDesc` when not set at all.
|
||||
|
||||
## 6.0.0
|
||||
|
||||
##### New Features
|
||||
|
||||
- New Renderers:
|
||||
- `Aggregated` - Custom renderer for aggregated cells
|
||||
- `Pivot` - Custom renderer for Pivoted Cells (utilizes `Expander` and `PivotValue`)
|
||||
@@ -91,8 +166,8 @@
|
||||
- Prevent transitions while column resizing for a smoother resize effect.
|
||||
- Disable text selection while resizing columns.
|
||||
|
||||
|
||||
##### Breaking API Changes
|
||||
|
||||
- New Renderers:
|
||||
- `Cell` - deprecates and replaces `render`
|
||||
- `Header` - deprecates and replaces `header`
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
## What version of React-Table are you using?
|
||||
Your bug may already be fixed in the latest release. Run `yarn upgrade react-table`!
|
||||
Place your version here...
|
||||
|
||||
## What bug are you experiencing, or what feature are you proposing?
|
||||
Please include a detailed explanation here...
|
||||
|
||||
## Use https://codesandbox.io/s/X6npLXPRW (by clicking the "Fork" button) to reproduce the issue.
|
||||
Then paste a link to your newly forked codesandbox here...
|
||||
|
||||
## What are the steps to reproduce the issue?
|
||||
1. list the steps
|
||||
2. to reproduce
|
||||
3. the issue
|
||||
+197
-192
@@ -5,83 +5,83 @@ You can find the most recent version of this guide [here](https://github.com/fac
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Updating to New Releases](#updating-to-new-releases)
|
||||
- [Sending Feedback](#sending-feedback)
|
||||
- [Folder Structure](#folder-structure)
|
||||
- [Available Scripts](#available-scripts)
|
||||
- [npm start](#npm-start)
|
||||
- [npm test](#npm-test)
|
||||
- [npm run build](#npm-run-build)
|
||||
- [npm run eject](#npm-run-eject)
|
||||
- [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
|
||||
- [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
|
||||
- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
|
||||
- [Debugging in the Editor](#debugging-in-the-editor)
|
||||
- [Changing the Page `<title>`](#changing-the-page-title)
|
||||
- [Installing a Dependency](#installing-a-dependency)
|
||||
- [Importing a Component](#importing-a-component)
|
||||
- [Adding a Stylesheet](#adding-a-stylesheet)
|
||||
- [Post-Processing CSS](#post-processing-css)
|
||||
- [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
|
||||
- [Adding Images and Fonts](#adding-images-and-fonts)
|
||||
- [Using the `public` Folder](#using-the-public-folder)
|
||||
- [Changing the HTML](#changing-the-html)
|
||||
- [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
|
||||
- [When to Use the `public` Folder](#when-to-use-the-public-folder)
|
||||
- [Using Global Variables](#using-global-variables)
|
||||
- [Adding Bootstrap](#adding-bootstrap)
|
||||
- [Using a Custom Theme](#using-a-custom-theme)
|
||||
- [Adding Flow](#adding-flow)
|
||||
- [Adding Custom Environment Variables](#adding-custom-environment-variables)
|
||||
- [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
|
||||
- [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
|
||||
- [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
|
||||
- [Can I Use Decorators?](#can-i-use-decorators)
|
||||
- [Integrating with an API Backend](#integrating-with-an-api-backend)
|
||||
- [Node](#node)
|
||||
- [Ruby on Rails](#ruby-on-rails)
|
||||
- [Proxying API Requests in Development](#proxying-api-requests-in-development)
|
||||
- [Using HTTPS in Development](#using-https-in-development)
|
||||
- [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
|
||||
- [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
|
||||
- [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
|
||||
- [Running Tests](#running-tests)
|
||||
- [Filename Conventions](#filename-conventions)
|
||||
- [Command Line Interface](#command-line-interface)
|
||||
- [Version Control Integration](#version-control-integration)
|
||||
- [Writing Tests](#writing-tests)
|
||||
- [Testing Components](#testing-components)
|
||||
- [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
|
||||
- [Initializing Test Environment](#initializing-test-environment)
|
||||
- [Focusing and Excluding Tests](#focusing-and-excluding-tests)
|
||||
- [Coverage Reporting](#coverage-reporting)
|
||||
- [Continuous Integration](#continuous-integration)
|
||||
- [Disabling jsdom](#disabling-jsdom)
|
||||
- [Snapshot Testing](#snapshot-testing)
|
||||
- [Editor Integration](#editor-integration)
|
||||
- [Developing Components in Isolation](#developing-components-in-isolation)
|
||||
- [Making a Progressive Web App](#making-a-progressive-web-app)
|
||||
- [Deployment](#deployment)
|
||||
- [Static Server](#static-server)
|
||||
- [Other Solutions](#other-solutions)
|
||||
- [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
|
||||
- [Building for Relative Paths](#building-for-relative-paths)
|
||||
- [Azure](#azure)
|
||||
- [Firebase](#firebase)
|
||||
- [GitHub Pages](#github-pages)
|
||||
- [Heroku](#heroku)
|
||||
- [Modulus](#modulus)
|
||||
- [Netlify](#netlify)
|
||||
- [Now](#now)
|
||||
- [S3 and CloudFront](#s3-and-cloudfront)
|
||||
- [Surge](#surge)
|
||||
- [Advanced Configuration](#advanced-configuration)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
|
||||
- [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
|
||||
- [`npm run build` silently fails](#npm-run-build-silently-fails)
|
||||
- [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
|
||||
- [Something Missing?](#something-missing)
|
||||
* [Updating to New Releases](#updating-to-new-releases)
|
||||
* [Sending Feedback](#sending-feedback)
|
||||
* [Folder Structure](#folder-structure)
|
||||
* [Available Scripts](#available-scripts)
|
||||
* [npm start](#npm-start)
|
||||
* [npm test](#npm-test)
|
||||
* [npm run build](#npm-run-build)
|
||||
* [npm run eject](#npm-run-eject)
|
||||
* [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
|
||||
* [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
|
||||
* [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
|
||||
* [Debugging in the Editor](#debugging-in-the-editor)
|
||||
* [Changing the Page `<title>`](#changing-the-page-title)
|
||||
* [Installing a Dependency](#installing-a-dependency)
|
||||
* [Importing a Component](#importing-a-component)
|
||||
* [Adding a Stylesheet](#adding-a-stylesheet)
|
||||
* [Post-Processing CSS](#post-processing-css)
|
||||
* [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
|
||||
* [Adding Images and Fonts](#adding-images-and-fonts)
|
||||
* [Using the `public` Folder](#using-the-public-folder)
|
||||
* [Changing the HTML](#changing-the-html)
|
||||
* [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
|
||||
* [When to Use the `public` Folder](#when-to-use-the-public-folder)
|
||||
* [Using Global Variables](#using-global-variables)
|
||||
* [Adding Bootstrap](#adding-bootstrap)
|
||||
* [Using a Custom Theme](#using-a-custom-theme)
|
||||
* [Adding Flow](#adding-flow)
|
||||
* [Adding Custom Environment Variables](#adding-custom-environment-variables)
|
||||
* [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
|
||||
* [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
|
||||
* [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
|
||||
* [Can I Use Decorators?](#can-i-use-decorators)
|
||||
* [Integrating with an API Backend](#integrating-with-an-api-backend)
|
||||
* [Node](#node)
|
||||
* [Ruby on Rails](#ruby-on-rails)
|
||||
* [Proxying API Requests in Development](#proxying-api-requests-in-development)
|
||||
* [Using HTTPS in Development](#using-https-in-development)
|
||||
* [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
|
||||
* [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
|
||||
* [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
|
||||
* [Running Tests](#running-tests)
|
||||
* [Filename Conventions](#filename-conventions)
|
||||
* [Command Line Interface](#command-line-interface)
|
||||
* [Version Control Integration](#version-control-integration)
|
||||
* [Writing Tests](#writing-tests)
|
||||
* [Testing Components](#testing-components)
|
||||
* [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
|
||||
* [Initializing Test Environment](#initializing-test-environment)
|
||||
* [Focusing and Excluding Tests](#focusing-and-excluding-tests)
|
||||
* [Coverage Reporting](#coverage-reporting)
|
||||
* [Continuous Integration](#continuous-integration)
|
||||
* [Disabling jsdom](#disabling-jsdom)
|
||||
* [Snapshot Testing](#snapshot-testing)
|
||||
* [Editor Integration](#editor-integration)
|
||||
* [Developing Components in Isolation](#developing-components-in-isolation)
|
||||
* [Making a Progressive Web App](#making-a-progressive-web-app)
|
||||
* [Deployment](#deployment)
|
||||
* [Static Server](#static-server)
|
||||
* [Other Solutions](#other-solutions)
|
||||
* [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
|
||||
* [Building for Relative Paths](#building-for-relative-paths)
|
||||
* [Azure](#azure)
|
||||
* [Firebase](#firebase)
|
||||
* [GitHub Pages](#github-pages)
|
||||
* [Heroku](#heroku)
|
||||
* [Modulus](#modulus)
|
||||
* [Netlify](#netlify)
|
||||
* [Now](#now)
|
||||
* [S3 and CloudFront](#s3-and-cloudfront)
|
||||
* [Surge](#surge)
|
||||
* [Advanced Configuration](#advanced-configuration)
|
||||
* [Troubleshooting](#troubleshooting)
|
||||
* [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
|
||||
* [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
|
||||
* [`npm run build` silently fails](#npm-run-build-silently-fails)
|
||||
* [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
|
||||
* [Something Missing?](#something-missing)
|
||||
|
||||
## Updating to New Releases
|
||||
|
||||
@@ -207,7 +207,7 @@ To configure the syntax highlighting in your favorite text editor, head to the [
|
||||
|
||||
## Displaying Lint Output in the Editor
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.2.0` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.2.0` and higher.
|
||||
|
||||
Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
|
||||
|
||||
@@ -215,24 +215,24 @@ They are not required for linting. You should see the linter output right in you
|
||||
|
||||
You would need to install an ESLint plugin for your editor first.
|
||||
|
||||
>**A note for Atom `linter-eslint` users**
|
||||
> **A note for Atom `linter-eslint` users**
|
||||
|
||||
>If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked:
|
||||
> If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked:
|
||||
|
||||
><img src="http://i.imgur.com/yVNNHJM.png" width="300">
|
||||
> <img src="http://i.imgur.com/yVNNHJM.png" width="300">
|
||||
|
||||
> **For Visual Studio Code users**
|
||||
|
||||
>**For Visual Studio Code users**
|
||||
> VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line:
|
||||
|
||||
>VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line:
|
||||
|
||||
>```js
|
||||
{
|
||||
// ...
|
||||
"extends": "react-app"
|
||||
}
|
||||
```
|
||||
> ```js
|
||||
> {
|
||||
> // ...
|
||||
> "extends": "react-app"
|
||||
> }
|
||||
> ```
|
||||
|
||||
````
|
||||
Then add this block to the `package.json` file of your project:
|
||||
|
||||
```js
|
||||
@@ -242,9 +242,9 @@ Then add this block to the `package.json` file of your project:
|
||||
"extends": "react-app"
|
||||
}
|
||||
}
|
||||
```
|
||||
````
|
||||
|
||||
Finally, you will need to install some packages *globally*:
|
||||
Finally, you will need to install some packages _globally_:
|
||||
|
||||
```sh
|
||||
npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@4.0.0 eslint-plugin-flowtype@2.21.0
|
||||
@@ -265,17 +265,19 @@ Then add the block below to your `launch.json` file and put it inside the `.vsco
|
||||
```json
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [{
|
||||
"name": "Chrome",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"url": "http://localhost:3000",
|
||||
"webRoot": "${workspaceRoot}/src",
|
||||
"userDataDir": "${workspaceRoot}/.vscode/chrome",
|
||||
"sourceMapPathOverrides": {
|
||||
"webpack:///src/*": "${webRoot}/*"
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Chrome",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"url": "http://localhost:3000",
|
||||
"webRoot": "${workspaceRoot}/src",
|
||||
"userDataDir": "${workspaceRoot}/.vscode/chrome",
|
||||
"sourceMapPathOverrides": {
|
||||
"webpack:///src/*": "${webRoot}/*"
|
||||
}
|
||||
}
|
||||
}]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -309,7 +311,7 @@ For example:
|
||||
### `Button.js`
|
||||
|
||||
```js
|
||||
import React, { Component } from 'react';
|
||||
import React, { Component } from "react";
|
||||
|
||||
class Button extends Component {
|
||||
render() {
|
||||
@@ -322,10 +324,9 @@ export default Button; // Don’t forget to use export default!
|
||||
|
||||
### `DangerButton.js`
|
||||
|
||||
|
||||
```js
|
||||
import React, { Component } from 'react';
|
||||
import Button from './Button'; // Import a component from another file
|
||||
import React, { Component } from "react";
|
||||
import Button from "./Button"; // Import a component from another file
|
||||
|
||||
class DangerButton extends Component {
|
||||
render() {
|
||||
@@ -363,8 +364,8 @@ This project setup uses [Webpack](https://webpack.github.io/) for handling all a
|
||||
### `Button.js`
|
||||
|
||||
```js
|
||||
import React, { Component } from 'react';
|
||||
import './Button.css'; // Tell Webpack that Button.js uses these styles
|
||||
import React, { Component } from "react";
|
||||
import "./Button.css"; // Tell Webpack that Button.js uses these styles
|
||||
|
||||
class Button extends Component {
|
||||
render() {
|
||||
@@ -403,11 +404,11 @@ becomes this:
|
||||
display: flex;
|
||||
-webkit-box-orient: horizontal;
|
||||
-webkit-box-direction: normal;
|
||||
-ms-flex-direction: row;
|
||||
flex-direction: row;
|
||||
-ms-flex-direction: row;
|
||||
flex-direction: row;
|
||||
-webkit-box-align: center;
|
||||
-ms-flex-align: center;
|
||||
align-items: center;
|
||||
-ms-flex-align: center;
|
||||
align-items: center;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -436,7 +437,7 @@ Then in `package.json`, add the following lines to `scripts`:
|
||||
"test": "react-scripts test --env=jsdom",
|
||||
```
|
||||
|
||||
>Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation.
|
||||
> Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation.
|
||||
|
||||
Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated.
|
||||
|
||||
@@ -477,8 +478,8 @@ You can **`import` an image right in a JavaScript module**. This tells Webpack t
|
||||
Here is an example:
|
||||
|
||||
```js
|
||||
import React from 'react';
|
||||
import logo from './logo.png'; // Tell Webpack this JS file uses this image
|
||||
import React from "react";
|
||||
import logo from "./logo.png"; // Tell Webpack this JS file uses this image
|
||||
|
||||
console.log(logo); // /logo.84287d09.png
|
||||
|
||||
@@ -509,7 +510,7 @@ An alternative way of handling static assets is described in the next section.
|
||||
|
||||
## Using the `public` Folder
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.5.0` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.5.0` and higher.
|
||||
|
||||
### Changing the HTML
|
||||
|
||||
@@ -530,7 +531,7 @@ This mechanism provides a number of benefits:
|
||||
|
||||
However there is an **escape hatch** that you can use to add an asset outside of the module system.
|
||||
|
||||
If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`.
|
||||
If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`.
|
||||
|
||||
Inside `index.html`, you can use it like this:
|
||||
|
||||
@@ -596,19 +597,19 @@ npm install react-bootstrap --save
|
||||
npm install bootstrap@3 --save
|
||||
```
|
||||
|
||||
Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file:
|
||||
Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your `src/index.js` file:
|
||||
|
||||
```js
|
||||
import 'bootstrap/dist/css/bootstrap.css';
|
||||
import 'bootstrap/dist/css/bootstrap-theme.css';
|
||||
import "bootstrap/dist/css/bootstrap.css";
|
||||
import "bootstrap/dist/css/bootstrap-theme.css";
|
||||
// Put any other imports below so that CSS from your
|
||||
// components takes precedence over default styles.
|
||||
```
|
||||
|
||||
Import required React Bootstrap components within ```src/App.js``` file or your custom component files:
|
||||
Import required React Bootstrap components within `src/App.js` file or your custom component files:
|
||||
|
||||
```js
|
||||
import { Navbar, Jumbotron, Button } from 'react-bootstrap';
|
||||
import { Navbar, Jumbotron, Button } from "react-bootstrap";
|
||||
```
|
||||
|
||||
Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap.
|
||||
@@ -632,10 +633,10 @@ Recent versions of [Flow](http://flowtype.org/) work with Create React App proje
|
||||
|
||||
To add Flow to a Create React App project, follow these steps:
|
||||
|
||||
1. Run `npm install --save-dev flow-bin` (or `yarn add --dev flow-bin`).
|
||||
2. Add `"flow": "flow"` to the `scripts` section of your `package.json`.
|
||||
3. Run `npm run flow -- init` (or `yarn flow -- init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory.
|
||||
4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`).
|
||||
1. Run `npm install --save-dev flow-bin` (or `yarn add --dev flow-bin`).
|
||||
2. Add `"flow": "flow"` to the `scripts` section of your `package.json`.
|
||||
3. Run `npm run flow -- init` (or `yarn flow -- init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory.
|
||||
4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`).
|
||||
|
||||
Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors.
|
||||
You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience.
|
||||
@@ -645,7 +646,7 @@ To learn more about Flow, check out [its documentation](https://flowtype.org/).
|
||||
|
||||
## Adding Custom Environment Variables
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.2.3` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.2.3` and higher.
|
||||
|
||||
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By
|
||||
default you will have `NODE_ENV` defined for you, and any other environment variables starting with
|
||||
@@ -653,7 +654,7 @@ default you will have `NODE_ENV` defined for you, and any other environment vari
|
||||
|
||||
**The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them.
|
||||
|
||||
>Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running.
|
||||
> Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running.
|
||||
|
||||
These environment variables will be defined for you on `process.env`. For example, having an environment
|
||||
variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`.
|
||||
@@ -699,7 +700,7 @@ a `.env` file. Both of these ways are described in the next few sections.
|
||||
Having access to the `NODE_ENV` is also useful for performing actions conditionally:
|
||||
|
||||
```js
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
analytics.disable();
|
||||
}
|
||||
```
|
||||
@@ -708,7 +709,7 @@ When you compile the app with `npm run build`, the minification step will strip
|
||||
|
||||
### Referencing Environment Variables in the HTML
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.9.0` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.9.0` and higher.
|
||||
|
||||
You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example:
|
||||
|
||||
@@ -742,7 +743,7 @@ REACT_APP_SECRET_CODE=abcdef npm start
|
||||
|
||||
### Adding Development Environment Variables In `.env`
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.5.0` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.5.0` and higher.
|
||||
|
||||
To define permanent environment variables, create a file called `.env` in the root of your project:
|
||||
|
||||
@@ -753,8 +754,8 @@ REACT_APP_SECRET_CODE=abcdef
|
||||
These variables will act as the defaults if the machine does not explicitly set them.<br>
|
||||
Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details.
|
||||
|
||||
>Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need
|
||||
these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars).
|
||||
> Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need
|
||||
> these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars).
|
||||
|
||||
## Can I Use Decorators?
|
||||
|
||||
@@ -779,6 +780,7 @@ These tutorials will help you to integrate your app with an API backend running
|
||||
using `fetch()` to access it.
|
||||
|
||||
### Node
|
||||
|
||||
Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/).
|
||||
You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo).
|
||||
|
||||
@@ -789,7 +791,7 @@ You can find the companion GitHub repository [here](https://github.com/fullstack
|
||||
|
||||
## Proxying API Requests in Development
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.2.3` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.2.3` and higher.
|
||||
|
||||
People often serve the front-end React app from the same host and port as their backend implementation.<br>
|
||||
For example, a production setup might look like this after the app is deployed:
|
||||
@@ -826,7 +828,7 @@ If the `proxy` option is **not** flexible enough for you, alternatively you can:
|
||||
|
||||
## Using HTTPS in Development
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.4.0` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.4.0` and higher.
|
||||
|
||||
You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS.
|
||||
|
||||
@@ -891,8 +893,7 @@ Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data
|
||||
|
||||
## Running Tests
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.3.0` and higher.<br>
|
||||
>[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030)
|
||||
> Note: this feature is available with `react-scripts@0.3.0` and higher.<br> >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030)
|
||||
|
||||
Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try.
|
||||
|
||||
@@ -937,9 +938,9 @@ To create tests, add `it()` (or `test()`) blocks with the name of the test and i
|
||||
Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this:
|
||||
|
||||
```js
|
||||
import sum from './sum';
|
||||
import sum from "./sum";
|
||||
|
||||
it('sums numbers', () => {
|
||||
it("sums numbers", () => {
|
||||
expect(sum(1, 2)).toEqual(3);
|
||||
expect(sum(2, 2)).toEqual(4);
|
||||
});
|
||||
@@ -955,12 +956,12 @@ There is a broad spectrum of component testing techniques. They range from a “
|
||||
Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components:
|
||||
|
||||
```js
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import App from './App';
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import App from "./App";
|
||||
|
||||
it('renders without crashing', () => {
|
||||
const div = document.createElement('div');
|
||||
it("renders without crashing", () => {
|
||||
const div = document.createElement("div");
|
||||
ReactDOM.render(<App />, div);
|
||||
});
|
||||
```
|
||||
@@ -976,11 +977,11 @@ npm install --save-dev enzyme react-addons-test-utils
|
||||
```
|
||||
|
||||
```js
|
||||
import React from 'react';
|
||||
import { shallow } from 'enzyme';
|
||||
import App from './App';
|
||||
import React from "react";
|
||||
import { shallow } from "enzyme";
|
||||
import App from "./App";
|
||||
|
||||
it('renders without crashing', () => {
|
||||
it("renders without crashing", () => {
|
||||
shallow(<App />);
|
||||
});
|
||||
```
|
||||
@@ -992,11 +993,11 @@ You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testi
|
||||
Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
|
||||
|
||||
```js
|
||||
import React from 'react';
|
||||
import { shallow } from 'enzyme';
|
||||
import App from './App';
|
||||
import React from "react";
|
||||
import { shallow } from "enzyme";
|
||||
import App from "./App";
|
||||
|
||||
it('renders welcome message', () => {
|
||||
it("renders welcome message", () => {
|
||||
const wrapper = shallow(<App />);
|
||||
const welcome = <h2>Welcome to React</h2>;
|
||||
// expect(wrapper.contains(welcome)).to.equal(true);
|
||||
@@ -1010,7 +1011,7 @@ Nevertheless you can use a third-party assertion library like [Chai](http://chai
|
||||
Additionally, you might find [jest-enzyme](https://github.com/blainekasten/enzyme-matchers) helpful to simplify your tests with readable matchers. The above `contains` code can be written simpler with jest-enzyme.
|
||||
|
||||
```js
|
||||
expect(wrapper).toContainReact(welcome)
|
||||
expect(wrapper).toContainReact(welcome);
|
||||
```
|
||||
|
||||
To setup jest-enzyme with Create React App, follow the instructions for [initializing your test environment](#initializing-test-environment) to import `jest-enzyme`.
|
||||
@@ -1021,10 +1022,9 @@ npm install --save-dev jest-enzyme
|
||||
|
||||
```js
|
||||
// src/setupTests.js
|
||||
import 'jest-enzyme';
|
||||
import "jest-enzyme";
|
||||
```
|
||||
|
||||
|
||||
### Using Third Party Assertion Libraries
|
||||
|
||||
We recommend that you use `expect()` for assertions and `jest.fn()` for spies. If you are having issues with them please [file those against Jest](https://github.com/facebook/jest/issues/new), and we’ll fix them. We intend to keep making them better for React, supporting, for example, [pretty-printing React elements as JSX](https://github.com/facebook/jest/pull/1566).
|
||||
@@ -1032,28 +1032,29 @@ We recommend that you use `expect()` for assertions and `jest.fn()` for spies. I
|
||||
However, if you are used to other libraries, such as [Chai](http://chaijs.com/) and [Sinon](http://sinonjs.org/), or if you have existing code using them that you’d like to port over, you can import them normally like this:
|
||||
|
||||
```js
|
||||
import sinon from 'sinon';
|
||||
import { expect } from 'chai';
|
||||
import sinon from "sinon";
|
||||
import { expect } from "chai";
|
||||
```
|
||||
|
||||
and then use them in your tests like you normally do.
|
||||
|
||||
### Initializing Test Environment
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.4.0` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.4.0` and higher.
|
||||
|
||||
If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a `src/setupTests.js` to your project. It will be automatically executed before running your tests.
|
||||
|
||||
For example:
|
||||
|
||||
#### `src/setupTests.js`
|
||||
|
||||
```js
|
||||
const localStorageMock = {
|
||||
getItem: jest.fn(),
|
||||
setItem: jest.fn(),
|
||||
clear: jest.fn()
|
||||
};
|
||||
global.localStorage = localStorageMock
|
||||
global.localStorage = localStorageMock;
|
||||
```
|
||||
|
||||
### Focusing and Excluding Tests
|
||||
@@ -1079,10 +1080,12 @@ When creating a build of your application with `npm run build` linter warnings a
|
||||
Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
|
||||
|
||||
### On CI servers
|
||||
|
||||
#### Travis CI
|
||||
|
||||
1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page.
|
||||
1. Add a `.travis.yml` file to your git repository.
|
||||
1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page.
|
||||
1. Add a `.travis.yml` file to your git repository.
|
||||
|
||||
```
|
||||
language: node_js
|
||||
node_js:
|
||||
@@ -1095,10 +1098,12 @@ script:
|
||||
- npm test
|
||||
- npm run build
|
||||
```
|
||||
1. Trigger your first build with a git push.
|
||||
1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
|
||||
|
||||
1. Trigger your first build with a git push.
|
||||
1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
|
||||
|
||||
### On your own environment
|
||||
|
||||
##### Windows (cmd.exe)
|
||||
|
||||
```cmd
|
||||
@@ -1123,7 +1128,7 @@ CI=true npm run build
|
||||
|
||||
The test command will force Jest to run tests once instead of launching the watcher.
|
||||
|
||||
> If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.
|
||||
> If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.
|
||||
|
||||
The build command will check for linter warnings and fail if any are found.
|
||||
|
||||
@@ -1236,14 +1241,14 @@ You don’t necessarily need a static server in order to run a Create React App
|
||||
Here’s a programmatic example using [Node](https://nodejs.org/) and [Express](http://expressjs.com/):
|
||||
|
||||
```javascript
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const express = require("express");
|
||||
const path = require("path");
|
||||
const app = express();
|
||||
|
||||
app.use(express.static('./build'));
|
||||
app.use(express.static("./build"));
|
||||
|
||||
app.get('/', function (req, res) {
|
||||
res.sendFile(path.join(__dirname, './build', 'index.html'));
|
||||
app.get("/", function(req, res) {
|
||||
res.sendFile(path.join(__dirname, "./build", "index.html"));
|
||||
});
|
||||
|
||||
app.listen(9000);
|
||||
@@ -1296,7 +1301,7 @@ This will let Create React App correctly infer the root path to use in the gener
|
||||
|
||||
#### Serving the Same Build from Different Paths
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.9.0` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.9.0` and higher.
|
||||
|
||||
If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`:
|
||||
|
||||
@@ -1373,7 +1378,7 @@ For more information see [Add Firebase to your JavaScript Project](https://fireb
|
||||
|
||||
### GitHub Pages
|
||||
|
||||
>Note: this feature is available with `react-scripts@0.2.0` and higher.
|
||||
> Note: this feature is available with `react-scripts@0.2.0` and higher.
|
||||
|
||||
#### Step 1: Add `homepage` to `package.json`
|
||||
|
||||
@@ -1493,9 +1498,9 @@ Choose `build` as the path to deploy.
|
||||
|
||||
With this setup Netlify will build and deploy when you push to git or open a pull request:
|
||||
|
||||
1. [Start a new netlify project](https://app.netlify.com/signup)
|
||||
2. Pick your Git hosting service and select your repository
|
||||
3. Click `Build your site`
|
||||
1. [Start a new netlify project](https://app.netlify.com/signup)
|
||||
2. Pick your Git hosting service and select your repository
|
||||
3. Click `Build your site`
|
||||
|
||||
**Support for client-side routing:**
|
||||
|
||||
@@ -1511,22 +1516,22 @@ When you build the project, Create React App will place the `public` folder cont
|
||||
|
||||
[now](https://zeit.co/now) offers a zero-configuration single-command deployment.
|
||||
|
||||
1. Install the `now` command-line tool either via the recommended [desktop tool](https://zeit.co/download) or via node with `npm install -g now`.
|
||||
1. Install the `now` command-line tool either via the recommended [desktop tool](https://zeit.co/download) or via node with `npm install -g now`.
|
||||
|
||||
2. Install `serve` by running `npm install --save serve`.
|
||||
2. Install `serve` by running `npm install --save serve`.
|
||||
|
||||
3. Add this line to `scripts` in `package.json`:
|
||||
|
||||
3. Add this line to `scripts` in `package.json`:
|
||||
|
||||
```
|
||||
"now-start": "serve build/",
|
||||
```
|
||||
|
||||
4. Run `now` from your project directory. You will see a **now.sh** URL in your output like this:
|
||||
|
||||
|
||||
4. Run `now` from your project directory. You will see a **now.sh** URL in your output like this:
|
||||
|
||||
```
|
||||
> Ready! https://your-project-dirname-tpspyhtdtk.now.sh (copied to clipboard)
|
||||
```
|
||||
|
||||
|
||||
Paste that URL into your browser when the build is complete, and you will see your deployed app.
|
||||
|
||||
Details are available in [this article.](https://zeit.co/blog/now-static)
|
||||
@@ -1537,7 +1542,7 @@ See this [blog post](https://medium.com/@omgwtfmarc/deploying-create-react-app-t
|
||||
|
||||
### Surge
|
||||
|
||||
Install the Surge CLI if you haven’t already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account. You just need to specify the *build* folder and your custom domain, and you are done.
|
||||
Install the Surge CLI if you haven’t already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account. You just need to specify the _build_ folder and your custom domain, and you are done.
|
||||
|
||||
```sh
|
||||
email: email@domain.com
|
||||
@@ -1560,14 +1565,14 @@ Note that in order to support routers that use HTML5 `pushState` API, you may wa
|
||||
|
||||
You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env).
|
||||
|
||||
Variable | Development | Production | Usage
|
||||
:--- | :---: | :---: | :---
|
||||
BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely.
|
||||
HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host.
|
||||
PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port.
|
||||
HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode.
|
||||
PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.
|
||||
CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default.
|
||||
| Variable | Development | Production | Usage |
|
||||
| :--------- | :--------------------: | :----------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely. |
|
||||
| HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host. |
|
||||
| PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port. |
|
||||
| HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode. |
|
||||
| PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. |
|
||||
| CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default. |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
@@ -1607,7 +1612,7 @@ You can find [other installation methods](https://facebook.github.io/watchman/do
|
||||
|
||||
If this still doesn’t help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
|
||||
|
||||
There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
|
||||
There are also reports that _uninstalling_ Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
|
||||
|
||||
### `npm run build` silently fails
|
||||
|
||||
|
||||
+33
-29
@@ -1,14 +1,14 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import React from 'react'
|
||||
import React from 'react';
|
||||
//
|
||||
import ReactStory, { defaultProps } from 'react-story'
|
||||
import CodeSandbox from './CodeSandbox.js'
|
||||
import './stories/utils/prism.css'
|
||||
import '../../react-table.css'
|
||||
import ReactStory, { defaultProps } from 'react-story';
|
||||
import CodeSandbox from './CodeSandbox.js';
|
||||
import './stories/utils/prism.css';
|
||||
import '../../react-table.css';
|
||||
|
||||
import Readme from './stories/Readme.js'
|
||||
import HOCReadme from './stories/HOCReadme.js'
|
||||
import Readme from './stories/Readme.js';
|
||||
import HOCReadme from './stories/HOCReadme.js';
|
||||
|
||||
// import Test from './stories/test.js'
|
||||
|
||||
@@ -17,17 +17,17 @@ import HOCReadme from './stories/HOCReadme.js'
|
||||
const stories = [
|
||||
{ name: 'Readme', component: Readme },
|
||||
{ name: 'HOC Readme', component: HOCReadme },
|
||||
|
||||
|
||||
// { name: 'Tester', component: Test },
|
||||
{ name: 'Simple Table', component: CodeSandbox('X6npLXPRW') },
|
||||
{
|
||||
name: 'Cell Renderers & Custom Components',
|
||||
component: CodeSandbox('OyRL04Z4Y'),
|
||||
component: CodeSandbox('OyRL04Z4Y')
|
||||
},
|
||||
{ name: 'Default Sorting', component: CodeSandbox('gLwmmjzA3') },
|
||||
{
|
||||
name: 'Custom Sorting',
|
||||
component: CodeSandbox('VGx67J35'),
|
||||
component: CodeSandbox('VGx67J35')
|
||||
},
|
||||
{ name: 'Custom Column Widths', component: CodeSandbox('o2OORXNXN') },
|
||||
{ name: 'Custom Component Props', component: CodeSandbox('nZW3L0wp4') },
|
||||
@@ -36,17 +36,17 @@ const stories = [
|
||||
{ name: 'Pivoting & Aggregation', component: CodeSandbox('oNY9z8xN') },
|
||||
{
|
||||
name: 'Pivoting & Aggregation w/ Sub Components',
|
||||
component: CodeSandbox('p0kEVBgQ'),
|
||||
component: CodeSandbox('p0kEVBgQ')
|
||||
},
|
||||
{
|
||||
name: '100k Rows w/ Pivoting & Sub Components',
|
||||
component: CodeSandbox('DRmKj0XyK'),
|
||||
component: CodeSandbox('DRmKj0XyK')
|
||||
},
|
||||
{ name: 'Pivoting Options', component: CodeSandbox('kZKmNBK6r') },
|
||||
{ name: 'Functional Rendering', component: CodeSandbox('VPZ0Bzv8X') },
|
||||
{
|
||||
name: 'Custom Expander Position',
|
||||
component: CodeSandbox('1jj2XrPEV'),
|
||||
component: CodeSandbox('1jj2XrPEV')
|
||||
},
|
||||
{ name: 'Custom "No Data" Text', component: CodeSandbox('RgRpRDv80') },
|
||||
{ name: 'Footers', component: CodeSandbox('KOqQXn3p8') },
|
||||
@@ -55,49 +55,52 @@ const stories = [
|
||||
{ name: 'Editable Table', component: CodeSandbox('n5r19gzQP') },
|
||||
{
|
||||
name: 'Fixed Header w/ Vertical Scroll',
|
||||
component: CodeSandbox('7LY0gjA8O'),
|
||||
component: CodeSandbox('7LY0gjA8O')
|
||||
},
|
||||
{
|
||||
name: 'Multiple Pagers (Top and Bottom)',
|
||||
component: CodeSandbox('VEZ8OgvX'),
|
||||
component: CodeSandbox('VEZ8OgvX')
|
||||
},
|
||||
|
||||
{ name: 'Tree Table (HOC)', component: CodeSandbox('lxmr4wynzq') },
|
||||
{ name: 'Select Table (HOC)', component: CodeSandbox('7yq5ylw09j') },
|
||||
{ name: 'Select Tree Table (HOC)', component: CodeSandbox('2p7jp4klwp') },
|
||||
]
|
||||
{ name: 'Foldable Table (HOC)', component: CodeSandbox('8pkrj5yorl') },
|
||||
{ name: 'Advanced Expand Table (HOC)', component: CodeSandbox('y2m39jz8v1') }
|
||||
];
|
||||
|
||||
export default class App extends React.Component {
|
||||
render () {
|
||||
render() {
|
||||
return (
|
||||
<ReactStory
|
||||
style={{
|
||||
display: 'block',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
height: '100%'
|
||||
}}
|
||||
pathPrefix='story/'
|
||||
StoryWrapper={props =>
|
||||
pathPrefix="story/"
|
||||
StoryWrapper={props => (
|
||||
<defaultProps.StoryWrapper
|
||||
css={{
|
||||
padding: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flexDirection: 'column'
|
||||
}}
|
||||
>
|
||||
<a
|
||||
href='//github.com/react-tools/react-table'
|
||||
href="//github.com/react-tools/react-table"
|
||||
style={{
|
||||
display: 'block',
|
||||
textAlign: 'center',
|
||||
borderBottom: 'solid 3px #cccccc',
|
||||
borderBottom: 'solid 3px #cccccc'
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src='https://github.com/react-tools/media/raw/master/logo-react-table.png'
|
||||
alt='React Table Logo'
|
||||
src="https://github.com/react-tools/media/raw/master/logo-react-table.png"
|
||||
alt="React Table Logo"
|
||||
style={{
|
||||
width: '150px',
|
||||
padding: '10px',
|
||||
padding: '10px'
|
||||
}}
|
||||
/>
|
||||
</a>
|
||||
@@ -105,12 +108,13 @@ export default class App extends React.Component {
|
||||
{...props}
|
||||
style={{
|
||||
flex: '1 0 auto',
|
||||
position: 'relative',
|
||||
position: 'relative'
|
||||
}}
|
||||
/>
|
||||
</defaultProps.StoryWrapper>}
|
||||
</defaultProps.StoryWrapper>
|
||||
)}
|
||||
stories={stories}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+9
-10
@@ -1,22 +1,21 @@
|
||||
import React from 'react'
|
||||
import React from "react";
|
||||
|
||||
export default id => () => {
|
||||
return (
|
||||
<iframe
|
||||
src={`https://codesandbox.io/embed/${id}?autoresize=1&hidenavigation=1&view=${global.innerWidth <
|
||||
1000
|
||||
? 'preview'
|
||||
: 'split'}`}
|
||||
src={`https://codesandbox.io/embed/${id}?autoresize=1&hidenavigation=1&view=${
|
||||
global.innerWidth < 1000 ? "preview" : "split"
|
||||
}`}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: `100%`,
|
||||
height: `100%`,
|
||||
border: 0,
|
||||
overflow: `hidden`,
|
||||
overflow: `hidden`
|
||||
}}
|
||||
sandbox='allow-modals allow-forms allow-popups allow-scripts allow-same-origin'
|
||||
sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
|
||||
/>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import React from 'react';
|
||||
import { render } from 'react-dom';
|
||||
import { makeData, Logo, Tips } from './Utils';
|
||||
import { advancedExpandTableHOC } from '../../../../lib/hoc/advancedExpandTable';
|
||||
|
||||
// Import React Table
|
||||
import ReactTable from 'react-table';
|
||||
import 'react-table/react-table.css';
|
||||
|
||||
const columns = [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
Cell: props => {
|
||||
const {
|
||||
// react table props
|
||||
columnProps: { rest: { showRowSubComponent } },
|
||||
nestingPath
|
||||
} = props;
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
onClick={e => showRowSubComponent({ nestingPath: nestingPath }, e)}
|
||||
>
|
||||
SHOW SUBCOMPONENT {props.value}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
id: 'lastName',
|
||||
accessor: d => d.lastName
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
Cell: props => {
|
||||
const {
|
||||
// react table props
|
||||
columnProps: { rest: { toggleRowSubComponent } },
|
||||
nestingPath
|
||||
} = props;
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
onClick={e =>
|
||||
toggleRowSubComponent({ nestingPath: nestingPath }, e)
|
||||
}
|
||||
>
|
||||
TOGGLE SUBCOMPONENT {props.value}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
Header: 'Stats',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits'
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
const AdvancedExpandReactTable = advancedExpandTableHOC(ReactTable);
|
||||
|
||||
class App extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
data: makeData()
|
||||
};
|
||||
}
|
||||
render() {
|
||||
const { data } = this.state;
|
||||
return (
|
||||
<div>
|
||||
<AdvancedExpandReactTable
|
||||
data={data}
|
||||
columns={columns}
|
||||
defaultPageSize={10}
|
||||
className='-striped -highlight'
|
||||
SubComponent={({ row, nestingPath, toggleRowSubComponent }) => {
|
||||
return (
|
||||
<div style={{ padding: '20px' }}>
|
||||
<button
|
||||
onClick={e => toggleRowSubComponent({ nestingPath }, e)}
|
||||
>
|
||||
CLOSE SUBCOMPONENT {row.firstName} {row.lastName}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<br />
|
||||
<Tips />
|
||||
<Logo />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
render(<App />, document.getElementById('root'));
|
||||
@@ -1,88 +1,94 @@
|
||||
import React from "react";
|
||||
|
||||
|
||||
import React from 'react';
|
||||
|
||||
export default (Component) => {
|
||||
|
||||
export default Component => {
|
||||
const wrapper = class RTCheckboxTable extends React.Component {
|
||||
// we only need a Component so we can get the 'ref' - pure components can't get a 'ref'
|
||||
|
||||
rowSelector = (row) =>
|
||||
{
|
||||
if(!row || !row.hasOwnProperty(this.props.keyField)) return null;
|
||||
rowSelector = row => {
|
||||
if (!row || !row.hasOwnProperty(this.props.keyField)) return null;
|
||||
const checked = this.props.isSelected(row[this.props.keyField]);
|
||||
return (
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={checked}
|
||||
onClick={(e)=>{
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onClick={e => {
|
||||
const { shiftKey } = e;
|
||||
e.stopPropagation();
|
||||
this.props.toggleSelection(row[this.props.keyField],shiftKey,row);
|
||||
}}
|
||||
onChange={()=>{}}
|
||||
value=''
|
||||
this.props.toggleSelection(row[this.props.keyField], shiftKey, row);
|
||||
}}
|
||||
onChange={() => {}}
|
||||
value=""
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
headSelector = (row) =>
|
||||
{
|
||||
headSelector = row => {
|
||||
const checked = this.props.selectAll;
|
||||
return (
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={checked}
|
||||
onClick={(e)=>{
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
this.props.toggleAll();
|
||||
}}
|
||||
onChange={()=>{}}
|
||||
value=''
|
||||
}}
|
||||
onChange={() => {}}
|
||||
value=""
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// this is so we can expose the underlying ReactTable to get at the sortedData for selectAll
|
||||
getWrappedInstance = ()=>this.wrappedInstance
|
||||
};
|
||||
|
||||
render()
|
||||
{
|
||||
const { columns:originalCols, isSelected, toggleSelection, toggleAll, keyField, selectAll, ...rest } = this.props;
|
||||
const { rowSelector, headSelector, } = this;
|
||||
// this is so we can expose the underlying ReactTable to get at the sortedData for selectAll
|
||||
getWrappedInstance = () => this.wrappedInstance;
|
||||
|
||||
render() {
|
||||
const {
|
||||
columns: originalCols,
|
||||
isSelected,
|
||||
toggleSelection,
|
||||
toggleAll,
|
||||
keyField,
|
||||
selectAll,
|
||||
...rest
|
||||
} = this.props;
|
||||
const { rowSelector, headSelector } = this;
|
||||
const select = {
|
||||
id: '_selector',
|
||||
accessor: ()=>'x', // this value is not important
|
||||
id: "_selector",
|
||||
accessor: () => "x", // this value is not important
|
||||
Header: headSelector,
|
||||
Cell: (ci) => { return rowSelector(ci.original); },
|
||||
Cell: ci => {
|
||||
return rowSelector(ci.original);
|
||||
},
|
||||
width: 30,
|
||||
filterable: false,
|
||||
sortable: false,
|
||||
resizable: false,
|
||||
style: { textAlign: 'center' },
|
||||
}
|
||||
const columns = [
|
||||
select,
|
||||
...originalCols,
|
||||
];
|
||||
style: { textAlign: "center" }
|
||||
};
|
||||
const columns = [select, ...originalCols];
|
||||
const extra = {
|
||||
columns,
|
||||
columns
|
||||
};
|
||||
return (
|
||||
<Component {...rest} {...extra} ref={(r)=>this.wrappedInstance=r}/>
|
||||
)
|
||||
<Component {...rest} {...extra} ref={r => (this.wrappedInstance = r)} />
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
wrapper.displayName = 'RTCheckboxTable';
|
||||
wrapper.defaultProps =
|
||||
{
|
||||
keyField: '_id',
|
||||
isSelected: (key)=>{ console.log('No isSelected handler provided:',{key})},
|
||||
wrapper.displayName = "RTCheckboxTable";
|
||||
wrapper.defaultProps = {
|
||||
keyField: "_id",
|
||||
isSelected: key => {
|
||||
console.log("No isSelected handler provided:", { key });
|
||||
},
|
||||
selectAll: false,
|
||||
toggleSelection: (key, shift, row)=>{ console.log('No toggleSelection handler provided:', { key, shift, row }) },
|
||||
toggleAll: () => { console.log('No toggleAll handler provided.') },
|
||||
}
|
||||
|
||||
toggleSelection: (key, shift, row) => {
|
||||
console.log("No toggleSelection handler provided:", { key, shift, row });
|
||||
},
|
||||
toggleAll: () => {
|
||||
console.log("No toggleAll handler provided.");
|
||||
}
|
||||
};
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,38 +1,34 @@
|
||||
import React from "react";
|
||||
import shortid from "shortid";
|
||||
|
||||
import React from 'react';
|
||||
import shortid from 'shortid';
|
||||
import ReactTable from "../../../../lib/index";
|
||||
import "../../../../react-table.css";
|
||||
|
||||
import ReactTable from '../../../../lib/index'
|
||||
import '../../../../react-table.css'
|
||||
|
||||
import checkboxTableHOC from './checkboxHOC';
|
||||
import checkboxTableHOC from "./checkboxHOC";
|
||||
|
||||
const CheckboxTable = checkboxTableHOC(ReactTable);
|
||||
|
||||
async function getData()
|
||||
{
|
||||
const result = await ( await fetch('/au_500_tree.json') ).json();
|
||||
async function getData() {
|
||||
const result = await (await fetch("/au_500_tree.json")).json();
|
||||
// we are adding a unique ID to the data for tracking the selected records
|
||||
return result.map((item)=>{
|
||||
return result.map(item => {
|
||||
const _id = shortid.generate();
|
||||
return {
|
||||
_id,
|
||||
...item,
|
||||
}
|
||||
...item
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getColumns(data)
|
||||
{
|
||||
function getColumns(data) {
|
||||
const columns = [];
|
||||
const sample = data[0];
|
||||
for(let key in sample)
|
||||
{
|
||||
if(key==='_id') continue;
|
||||
for (let key in sample) {
|
||||
if (key === "_id") continue;
|
||||
columns.push({
|
||||
accessor: key,
|
||||
Header: key,
|
||||
})
|
||||
Header: key
|
||||
});
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
@@ -40,46 +36,42 @@ function getColumns(data)
|
||||
export class ComponentTest extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state =
|
||||
{
|
||||
this.state = {
|
||||
data: null,
|
||||
columns: null,
|
||||
selection: [],
|
||||
selectAll: false,
|
||||
selectAll: false
|
||||
};
|
||||
}
|
||||
componentDidMount()
|
||||
{
|
||||
getData().then((data)=>{
|
||||
componentDidMount() {
|
||||
getData().then(data => {
|
||||
const columns = getColumns(data);
|
||||
this.setState({ data, columns });
|
||||
});
|
||||
}
|
||||
toggleSelection = (key,shift,row) => {
|
||||
toggleSelection = (key, shift, row) => {
|
||||
/*
|
||||
Implementation of how to manage the selection state is up to the developer.
|
||||
This implementation uses an array stored in the component state.
|
||||
Other implementations could use object keys, a Javascript Set, or Redux... etc.
|
||||
*/
|
||||
// start off with the existing state
|
||||
let selection = [
|
||||
...this.state.selection
|
||||
];
|
||||
let selection = [...this.state.selection];
|
||||
const keyIndex = selection.indexOf(key);
|
||||
// check to see if the key exists
|
||||
if(keyIndex>=0) {
|
||||
if (keyIndex >= 0) {
|
||||
// it does exist so we will remove it using destructing
|
||||
selection = [
|
||||
...selection.slice(0,keyIndex),
|
||||
...selection.slice(keyIndex+1)
|
||||
]
|
||||
...selection.slice(0, keyIndex),
|
||||
...selection.slice(keyIndex + 1)
|
||||
];
|
||||
} else {
|
||||
// it does not exist so add it
|
||||
selection.push(key);
|
||||
}
|
||||
// update the state
|
||||
this.setState({selection});
|
||||
}
|
||||
this.setState({ selection });
|
||||
};
|
||||
toggleAll = () => {
|
||||
/*
|
||||
'toggleAll' is a tricky concept with any filterable table
|
||||
@@ -99,58 +91,54 @@ export class ComponentTest extends React.Component {
|
||||
That can then be iterrated to get all the currently visible records and set
|
||||
the selection state.
|
||||
*/
|
||||
const selectAll = this.state.selectAll?false:true;
|
||||
const selectAll = this.state.selectAll ? false : true;
|
||||
const selection = [];
|
||||
if(selectAll)
|
||||
{
|
||||
if (selectAll) {
|
||||
// we need to get at the internals of ReactTable
|
||||
const wrappedInstance = this.checkboxTable.getWrappedInstance();
|
||||
// the 'sortedData' property contains the currently accessible records based on the filter and sort
|
||||
const currentRecords = wrappedInstance.getResolvedState().sortedData;
|
||||
// we just push all the IDs onto the selection array
|
||||
currentRecords.forEach((item)=>{
|
||||
currentRecords.forEach(item => {
|
||||
selection.push(item._original._id);
|
||||
})
|
||||
});
|
||||
}
|
||||
this.setState({selectAll,selection})
|
||||
}
|
||||
isSelected = (key) => {
|
||||
this.setState({ selectAll, selection });
|
||||
};
|
||||
isSelected = key => {
|
||||
/*
|
||||
Instead of passing our external selection state we provide an 'isSelected'
|
||||
callback and detect the selection state ourselves. This allows any implementation
|
||||
for selection (either an array, object keys, or even a Javascript Set object).
|
||||
*/
|
||||
return this.state.selection.includes(key);
|
||||
}
|
||||
};
|
||||
logSelection = () => {
|
||||
console.log('selection:',this.state.selection);
|
||||
}
|
||||
render(){
|
||||
console.log("selection:", this.state.selection);
|
||||
};
|
||||
render() {
|
||||
const { toggleSelection, toggleAll, isSelected, logSelection } = this;
|
||||
const { data, columns, selectAll } = this.state;
|
||||
const extraProps =
|
||||
{
|
||||
const extraProps = {
|
||||
selectAll,
|
||||
isSelected,
|
||||
toggleAll,
|
||||
toggleSelection,
|
||||
}
|
||||
toggleSelection
|
||||
};
|
||||
return (
|
||||
<div style={{ padding: '10px'}}>
|
||||
<div style={{ padding: "10px" }}>
|
||||
<h1>react-table - Checkbox Table</h1>
|
||||
<button onClick={logSelection}>Log Selection to Console</button>
|
||||
{` (${this.state.selection.length}) selected`}
|
||||
{
|
||||
data?
|
||||
{data ? (
|
||||
<CheckboxTable
|
||||
data={data}
|
||||
columns={columns}
|
||||
ref={(r)=>this.checkboxTable = r}
|
||||
ref={r => (this.checkboxTable = r)}
|
||||
className="-striped -highlight"
|
||||
{...extraProps}
|
||||
/>
|
||||
:null
|
||||
}
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,59 +1,58 @@
|
||||
|
||||
import React from 'react'
|
||||
import React from "react";
|
||||
|
||||
export default class ComponentTest extends React.component {
|
||||
render () {
|
||||
return <div>Bozo</div>
|
||||
render() {
|
||||
return <div>Bozo</div>;
|
||||
}
|
||||
}
|
||||
|
||||
// import ReactTable from '../../../../lib/index'
|
||||
// import '../../../../react-table.css'
|
||||
//
|
||||
//
|
||||
// console.log('ReactTable:',ReactTable)
|
||||
//
|
||||
//
|
||||
// const data = [
|
||||
// {one:"1.1",two:"1.2"},
|
||||
// {one:"2.1",two:"2.2"},
|
||||
// {one:"3.1",two:"3.2"},
|
||||
// {one:"4.1",two:"4.2"},
|
||||
// ]
|
||||
//
|
||||
//
|
||||
// const columns = [
|
||||
// {accessor:'one', Header: 'One'},
|
||||
// {accessor:'two', Header: 'Two'},
|
||||
// ]
|
||||
//
|
||||
//
|
||||
// class ExpanderComponent extends React.Component {
|
||||
// render()
|
||||
// {
|
||||
// return (
|
||||
// <div className={`rt-expander ${this.props.isExpanded ? '-open' : ''}`}>
|
||||
// •
|
||||
// </div>
|
||||
// </div>
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// class SubComponent extends React.Component {
|
||||
// render()
|
||||
// {
|
||||
// return <div>Nothing</div>
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// export default class ComponentTest extends React.Component {
|
||||
// render()
|
||||
// {
|
||||
// const rtProps = {
|
||||
// data,
|
||||
// columns,
|
||||
// // ExpanderComponent: (props)=><ExpanderComponent {...props} />,
|
||||
// // ExpanderComponent: (props, closeExpanded)=><ExpanderComponent {...props, closeExpanded} />,
|
||||
// // SubComponent: (props)=><SubComponent {...props} />,
|
||||
// // multiSort: false,
|
||||
// }
|
||||
// return (
|
||||
// <ReactTable
|
||||
// <ReactTable
|
||||
// {...rtProps}
|
||||
// />
|
||||
// )
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import React from 'react'
|
||||
import ReactTable from '../../../../lib/index'
|
||||
import FoldableTableHOC from '../../../../lib/hoc/foldableTable'
|
||||
import selectTableHOC from '../../../../lib/hoc/selectTable'
|
||||
|
||||
const FoldableTable = FoldableTableHOC(selectTableHOC(ReactTable))
|
||||
|
||||
export default class FoldableTableCustomState extends React.Component {
|
||||
constructor(props, context) {
|
||||
super(props, context)
|
||||
|
||||
this.state = { folded: {}, seleted: {}, selectedAll: false }
|
||||
}
|
||||
|
||||
getData = () => [{
|
||||
id: 1,
|
||||
first_name: 'Jeanette',
|
||||
'last_name': 'Penddreth',
|
||||
email: 'jpenddreth0@census.gov',
|
||||
'gender': 'Female',
|
||||
ip_address: '26.58.193.2',
|
||||
}, {
|
||||
'id': 2,
|
||||
'first_name': 'Giavani',
|
||||
last_name: 'Frediani',
|
||||
'email': 'gfrediani1@senate.gov',
|
||||
'gender': 'Male',
|
||||
'ip_address': '229.179.4.212',
|
||||
}, {
|
||||
'id': 3,
|
||||
first_name: 'Noell',
|
||||
last_name: 'Bea',
|
||||
'email': 'nbea2@imageshack.us',
|
||||
gender: 'Female',
|
||||
ip_address: '180.66.162.255',
|
||||
}, {
|
||||
'id': 4,
|
||||
'first_name': 'Willard',
|
||||
'last_name': 'Valek',
|
||||
email: 'wvalek3@vk.com',
|
||||
'gender': 'Male',
|
||||
ip_address: '67.76.188.26',
|
||||
}];
|
||||
|
||||
toggleSelection = (key, shift, row) => {
|
||||
const { selected } = this.state
|
||||
let newSelected = Object.assign({}, selected)
|
||||
newSelected[key] = !newSelected[key]
|
||||
this.setState(p => ({ selected: newSelected }))
|
||||
};
|
||||
|
||||
toggleAll = () => {
|
||||
const { selectedAll } = this.state
|
||||
|
||||
if (selectedAll) { this.setState(p => { return { selectedAll: false, seleted: {} } }); }
|
||||
else {
|
||||
const data = this.getData()
|
||||
|
||||
let newSelected = {}
|
||||
data.forEach(d => newSelected[d.id] = true)
|
||||
this.setState(p => ({ selectedAll: true, seleted: newSelected }))
|
||||
}
|
||||
}
|
||||
|
||||
isSelected = key => this.state.seleted[key];
|
||||
|
||||
render() {
|
||||
return (<FoldableTable
|
||||
//SelectTable props
|
||||
keyField='id'
|
||||
toggleSelection={this.toggleSelection}
|
||||
toggleAll={this.toggleAll}
|
||||
isSelected={this.isSelected}
|
||||
selectAll={this.state.selectedAll}
|
||||
selectType='checkbox'
|
||||
|
||||
onFoldChange={newFolded => this.setState(p => { return { folded: newFolded } })}
|
||||
folded={this.state.folded}
|
||||
|
||||
data={this.getData()}
|
||||
columns={[{
|
||||
Header: "Name",
|
||||
foldable: true,
|
||||
columns: [
|
||||
{
|
||||
Header: "First Name",
|
||||
accessor: "first_name"
|
||||
},
|
||||
{
|
||||
Header: "Last Name",
|
||||
accessor: "last_name"
|
||||
}
|
||||
]
|
||||
}, {
|
||||
Header: "Info",
|
||||
foldable: true,
|
||||
columns: [
|
||||
{
|
||||
Header: "Email",
|
||||
accessor: "email"
|
||||
},
|
||||
{
|
||||
Header: "Gender",
|
||||
accessor: "gender"
|
||||
}
|
||||
]
|
||||
}]
|
||||
}></FoldableTable>)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import React from 'react'
|
||||
import ReactTable from '../../../../lib/index'
|
||||
import FoldableTableHOC from '../../../../lib/hoc/foldableTable'
|
||||
|
||||
const FoldableTable = FoldableTableHOC(ReactTable)
|
||||
|
||||
export default class FoldableTableWithHeader extends React.Component {
|
||||
|
||||
getData = () => [{
|
||||
id: 1,
|
||||
first_name: 'Jeanette',
|
||||
last_name: 'Penddreth',
|
||||
'email': 'jpenddreth0@census.gov',
|
||||
gender: 'Female',
|
||||
'ip_address': '26.58.193.2',
|
||||
}, {
|
||||
'id': 2,
|
||||
first_name: 'Giavani',
|
||||
last_name: 'Frediani',
|
||||
email: 'gfrediani1@senate.gov',
|
||||
gender: 'Male',
|
||||
'ip_address': '229.179.4.212',
|
||||
}, {
|
||||
'id': 3,
|
||||
'first_name': 'Noell',
|
||||
last_name: 'Bea',
|
||||
'email': 'nbea2@imageshack.us',
|
||||
'gender': 'Female',
|
||||
ip_address: '180.66.162.255',
|
||||
}, {
|
||||
'id': 4,
|
||||
'first_name': 'Willard',
|
||||
'last_name': 'Valek',
|
||||
email: 'wvalek3@vk.com',
|
||||
'gender': 'Male',
|
||||
ip_address: '67.76.188.26',
|
||||
}];
|
||||
|
||||
render() {
|
||||
return (<FoldableTable
|
||||
data={this.getData()}
|
||||
columns={[{
|
||||
Header: "Name",
|
||||
foldable: true,
|
||||
columns: [
|
||||
{
|
||||
Header: "First Name",
|
||||
accessor: "first_name"
|
||||
},
|
||||
{
|
||||
Header: "Last Name",
|
||||
accessor: "last_name"
|
||||
}
|
||||
]
|
||||
}, {
|
||||
Header: "Info",
|
||||
foldable: true,
|
||||
columns: [
|
||||
{
|
||||
Header: "Email",
|
||||
accessor: "email"
|
||||
},
|
||||
{
|
||||
Header: "Gender",
|
||||
accessor: "gender"
|
||||
}
|
||||
]
|
||||
}]
|
||||
}></FoldableTable>)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import React from 'react';
|
||||
import ReactTable from '../../../../lib/index';
|
||||
import FoldableTableHOC from '../../../../lib/hoc/foldableTable';
|
||||
|
||||
const FoldableTable = FoldableTableHOC(ReactTable);
|
||||
|
||||
export default class FoldableTableWithoutHeader extends React.Component {
|
||||
|
||||
getData = () => [{
|
||||
"id": 1,
|
||||
"first_name": "Jeanette",
|
||||
"last_name": "Penddreth",
|
||||
"email": "jpenddreth0@census.gov",
|
||||
"gender": "Female",
|
||||
"ip_address": "26.58.193.2"
|
||||
}, {
|
||||
"id": 2,
|
||||
"first_name": "Giavani",
|
||||
"last_name": "Frediani",
|
||||
"email": "gfrediani1@senate.gov",
|
||||
"gender": "Male",
|
||||
"ip_address": "229.179.4.212"
|
||||
}, {
|
||||
"id": 3,
|
||||
"first_name": "Noell",
|
||||
"last_name": "Bea",
|
||||
"email": "nbea2@imageshack.us",
|
||||
"gender": "Female",
|
||||
"ip_address": "180.66.162.255"
|
||||
}, {
|
||||
"id": 4,
|
||||
"first_name": "Willard",
|
||||
"last_name": "Valek",
|
||||
"email": "wvalek3@vk.com",
|
||||
"gender": "Male",
|
||||
"ip_address": "67.76.188.26"
|
||||
}];
|
||||
|
||||
render() {
|
||||
return <FoldableTable
|
||||
data={this.getData()}
|
||||
columns={[
|
||||
{
|
||||
Header: "First Name",
|
||||
accessor: "first_name"
|
||||
},
|
||||
{
|
||||
Header: "Last Name",
|
||||
accessor: "last_name",
|
||||
foldable: true,
|
||||
},
|
||||
{
|
||||
Header: "Email",
|
||||
accessor: "email",
|
||||
foldable: true,
|
||||
},
|
||||
{
|
||||
Header: "Gender",
|
||||
accessor: "gender",
|
||||
foldable: true,
|
||||
}
|
||||
]}></FoldableTable>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
|
||||
import React from 'react'
|
||||
import '../../../../react-table.css'
|
||||
|
||||
import FoldableTableWithHeader from './FoldableTableWithHeader'
|
||||
import FoldableTableWithoutHeader from './FoldableTableWithoutHeader'
|
||||
import FoldableTableCustomState from './FoldableTableCustomState'
|
||||
|
||||
class FaldableComponentTest extends React.Component {
|
||||
render() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>- Sample With Header Columns</p>
|
||||
<br />
|
||||
<FoldableTableWithHeader />
|
||||
<br /> <br />
|
||||
<p>- Sample With Normal Columns</p>
|
||||
<br />
|
||||
<FoldableTableWithoutHeader />
|
||||
<br /> <br />
|
||||
<p>- Custom State and selectedTable</p>
|
||||
<br />
|
||||
<FoldableTableCustomState />
|
||||
</div >
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default FaldableComponentTest
|
||||
@@ -3,9 +3,11 @@
|
||||
import TreeTable from './treetable'
|
||||
import SelectTable from './selecttable'
|
||||
import SelectTreeTable from './selecttreetable'
|
||||
import FoldableTable from './foldabletable';
|
||||
|
||||
export {
|
||||
TreeTable,
|
||||
SelectTable,
|
||||
SelectTreeTable,
|
||||
FoldableTable
|
||||
}
|
||||
|
||||
@@ -1,38 +1,34 @@
|
||||
import React from "react";
|
||||
import shortid from "shortid";
|
||||
|
||||
import React from 'react';
|
||||
import shortid from 'shortid';
|
||||
import ReactTable from "../../../../lib/index";
|
||||
import "../../../../react-table.css";
|
||||
|
||||
import ReactTable from '../../../../lib/index'
|
||||
import '../../../../react-table.css'
|
||||
|
||||
import selectTableHOC from '../../../../lib/hoc/selectTable'
|
||||
import selectTableHOC from "../../../../lib/hoc/selectTable";
|
||||
|
||||
const SelectTable = selectTableHOC(ReactTable);
|
||||
|
||||
async function getData()
|
||||
{
|
||||
const result = await ( await fetch('/au_500_tree.json') ).json();
|
||||
async function getData() {
|
||||
const result = await (await fetch("/au_500_tree.json")).json();
|
||||
// we are adding a unique ID to the data for tracking the selected records
|
||||
return result.map((item)=>{
|
||||
return result.map(item => {
|
||||
const _id = shortid.generate();
|
||||
return {
|
||||
_id,
|
||||
...item,
|
||||
}
|
||||
...item
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getColumns(data)
|
||||
{
|
||||
function getColumns(data) {
|
||||
const columns = [];
|
||||
const sample = data[0];
|
||||
for(let key in sample)
|
||||
{
|
||||
if(key==='_id') continue;
|
||||
for (let key in sample) {
|
||||
if (key === "_id") continue;
|
||||
columns.push({
|
||||
accessor: key,
|
||||
Header: key,
|
||||
})
|
||||
Header: key
|
||||
});
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
@@ -40,53 +36,49 @@ function getColumns(data)
|
||||
export class ComponentTest extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state =
|
||||
{
|
||||
this.state = {
|
||||
data: null,
|
||||
columns: null,
|
||||
selection: [],
|
||||
selectAll: false,
|
||||
selectType: 'checkbox',
|
||||
selectType: "checkbox"
|
||||
};
|
||||
}
|
||||
componentDidMount()
|
||||
{
|
||||
getData().then((data)=>{
|
||||
componentDidMount() {
|
||||
getData().then(data => {
|
||||
const columns = getColumns(data);
|
||||
this.setState({ data, columns });
|
||||
});
|
||||
}
|
||||
toggleSelection = (key,shift,row) => {
|
||||
toggleSelection = (key, shift, row) => {
|
||||
/*
|
||||
Implementation of how to manage the selection state is up to the developer.
|
||||
This implementation uses an array stored in the component state.
|
||||
Other implementations could use object keys, a Javascript Set, or Redux... etc.
|
||||
*/
|
||||
// start off with the existing state
|
||||
if (this.state.selectType === 'radio') {
|
||||
if (this.state.selectType === "radio") {
|
||||
let selection = [];
|
||||
if (selection.indexOf(key)<0) selection.push(key);
|
||||
this.setState({selection});
|
||||
if (selection.indexOf(key) < 0) selection.push(key);
|
||||
this.setState({ selection });
|
||||
} else {
|
||||
let selection = [
|
||||
...this.state.selection
|
||||
];
|
||||
let selection = [...this.state.selection];
|
||||
const keyIndex = selection.indexOf(key);
|
||||
// check to see if the key exists
|
||||
if(keyIndex>=0) {
|
||||
if (keyIndex >= 0) {
|
||||
// it does exist so we will remove it using destructing
|
||||
selection = [
|
||||
...selection.slice(0,keyIndex),
|
||||
...selection.slice(keyIndex+1)
|
||||
]
|
||||
...selection.slice(0, keyIndex),
|
||||
...selection.slice(keyIndex + 1)
|
||||
];
|
||||
} else {
|
||||
// it does not exist so add it
|
||||
selection.push(key);
|
||||
}
|
||||
// update the state
|
||||
this.setState({selection});
|
||||
this.setState({ selection });
|
||||
}
|
||||
}
|
||||
};
|
||||
toggleAll = () => {
|
||||
/*
|
||||
'toggleAll' is a tricky concept with any filterable table
|
||||
@@ -106,66 +98,73 @@ export class ComponentTest extends React.Component {
|
||||
That can then be iterrated to get all the currently visible records and set
|
||||
the selection state.
|
||||
*/
|
||||
const selectAll = this.state.selectAll?false:true;
|
||||
const selectAll = this.state.selectAll ? false : true;
|
||||
const selection = [];
|
||||
if(selectAll)
|
||||
{
|
||||
if (selectAll) {
|
||||
// we need to get at the internals of ReactTable
|
||||
const wrappedInstance = this.selectTable.getWrappedInstance();
|
||||
// the 'sortedData' property contains the currently accessible records based on the filter and sort
|
||||
const currentRecords = wrappedInstance.getResolvedState().sortedData;
|
||||
// we just push all the IDs onto the selection array
|
||||
currentRecords.forEach((item)=>{
|
||||
if(item._original)
|
||||
{
|
||||
currentRecords.forEach(item => {
|
||||
if (item._original) {
|
||||
selection.push(item._original._id);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
this.setState({selectAll,selection})
|
||||
}
|
||||
isSelected = (key) => {
|
||||
this.setState({ selectAll, selection });
|
||||
};
|
||||
isSelected = key => {
|
||||
/*
|
||||
Instead of passing our external selection state we provide an 'isSelected'
|
||||
callback and detect the selection state ourselves. This allows any implementation
|
||||
for selection (either an array, object keys, or even a Javascript Set object).
|
||||
*/
|
||||
return this.state.selection.includes(key);
|
||||
}
|
||||
};
|
||||
logSelection = () => {
|
||||
console.log('selection:',this.state.selection);
|
||||
}
|
||||
console.log("selection:", this.state.selection);
|
||||
};
|
||||
toggleType = () => {
|
||||
this.setState({ selectType: this.state.selectType === 'radio' ? 'checkbox' : 'radio', selection: [], selectAll: false, });
|
||||
}
|
||||
render(){
|
||||
const { toggleSelection, toggleAll, isSelected, logSelection, toggleType } = this;
|
||||
this.setState({
|
||||
selectType: this.state.selectType === "radio" ? "checkbox" : "radio",
|
||||
selection: [],
|
||||
selectAll: false
|
||||
});
|
||||
};
|
||||
render() {
|
||||
const {
|
||||
toggleSelection,
|
||||
toggleAll,
|
||||
isSelected,
|
||||
logSelection,
|
||||
toggleType
|
||||
} = this;
|
||||
const { data, columns, selectAll, selectType } = this.state;
|
||||
const extraProps =
|
||||
{
|
||||
const extraProps = {
|
||||
selectAll,
|
||||
isSelected,
|
||||
toggleAll,
|
||||
toggleSelection,
|
||||
selectType,
|
||||
}
|
||||
selectType
|
||||
};
|
||||
return (
|
||||
<div style={{ padding: '10px'}}>
|
||||
<div style={{ padding: "10px" }}>
|
||||
<h1>react-table - Select Table</h1>
|
||||
<button onClick={toggleType}>Select Type: <strong>{selectType}</strong></button>
|
||||
<button onClick={toggleType}>
|
||||
Select Type: <strong>{selectType}</strong>
|
||||
</button>
|
||||
<button onClick={logSelection}>Log Selection to Console</button>
|
||||
{` (${this.state.selection.length}) selected`}
|
||||
{
|
||||
data?
|
||||
{data ? (
|
||||
<SelectTable
|
||||
data={data}
|
||||
columns={columns}
|
||||
ref={(r)=>this.selectTable = r}
|
||||
ref={r => (this.selectTable = r)}
|
||||
className="-striped -highlight"
|
||||
{...extraProps}
|
||||
/>
|
||||
:null
|
||||
}
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,49 +1,43 @@
|
||||
import React from "react";
|
||||
import shortid from "shortid";
|
||||
|
||||
import React from 'react';
|
||||
import shortid from 'shortid';
|
||||
import ReactTable from "../../../../lib/index";
|
||||
import "../../../../react-table.css";
|
||||
|
||||
import ReactTable from '../../../../lib/index'
|
||||
import '../../../../react-table.css'
|
||||
|
||||
import selectTableHOC from '../../../../lib/hoc/selectTable'
|
||||
import treeTableHOC from '../../../../lib/hoc/treeTable'
|
||||
import selectTableHOC from "../../../../lib/hoc/selectTable";
|
||||
import treeTableHOC from "../../../../lib/hoc/treeTable";
|
||||
|
||||
const SelectTreeTable = selectTableHOC(treeTableHOC(ReactTable));
|
||||
|
||||
async function getData()
|
||||
{
|
||||
const result = await ( await fetch('/au_500_tree.json') ).json();
|
||||
async function getData() {
|
||||
const result = await (await fetch("/au_500_tree.json")).json();
|
||||
// we are adding a unique ID to the data for tracking the selected records
|
||||
return result.map((item)=>{
|
||||
return result.map(item => {
|
||||
const _id = shortid.generate();
|
||||
return {
|
||||
_id,
|
||||
...item,
|
||||
}
|
||||
...item
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getColumns(data)
|
||||
{
|
||||
function getColumns(data) {
|
||||
const columns = [];
|
||||
const sample = data[0];
|
||||
for(let key in sample)
|
||||
{
|
||||
if(key==='_id') continue;
|
||||
for (let key in sample) {
|
||||
if (key === "_id") continue;
|
||||
columns.push({
|
||||
accessor: key,
|
||||
Header: key,
|
||||
})
|
||||
Header: key
|
||||
});
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
function getNodes(data,node=[])
|
||||
{
|
||||
data.forEach((item)=>{
|
||||
if(item.hasOwnProperty('_subRows') && item._subRows)
|
||||
{
|
||||
node = getNodes(item._subRows,node);
|
||||
function getNodes(data, node = []) {
|
||||
data.forEach(item => {
|
||||
if (item.hasOwnProperty("_subRows") && item._subRows) {
|
||||
node = getNodes(item._subRows, node);
|
||||
} else {
|
||||
node.push(item._original);
|
||||
}
|
||||
@@ -54,54 +48,50 @@ function getNodes(data,node=[])
|
||||
export class ComponentTest extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state =
|
||||
{
|
||||
this.state = {
|
||||
data: null,
|
||||
columns: null,
|
||||
selection: [],
|
||||
selectAll: false,
|
||||
selectType: 'checkbox',
|
||||
selectType: "checkbox"
|
||||
};
|
||||
}
|
||||
componentDidMount()
|
||||
{
|
||||
getData().then((data)=>{
|
||||
componentDidMount() {
|
||||
getData().then(data => {
|
||||
const columns = getColumns(data);
|
||||
const pivotBy = ['state','post'];
|
||||
const pivotBy = ["state", "post"];
|
||||
this.setState({ data, columns, pivotBy });
|
||||
});
|
||||
}
|
||||
toggleSelection = (key,shift,row) => {
|
||||
toggleSelection = (key, shift, row) => {
|
||||
/*
|
||||
Implementation of how to manage the selection state is up to the developer.
|
||||
This implementation uses an array stored in the component state.
|
||||
Other implementations could use object keys, a Javascript Set, or Redux... etc.
|
||||
*/
|
||||
// start off with the existing state
|
||||
if (this.state.selectType === 'radio') {
|
||||
if (this.state.selectType === "radio") {
|
||||
let selection = [];
|
||||
if (selection.indexOf(key)<0) selection.push(key);
|
||||
this.setState({selection});
|
||||
if (selection.indexOf(key) < 0) selection.push(key);
|
||||
this.setState({ selection });
|
||||
} else {
|
||||
let selection = [
|
||||
...this.state.selection
|
||||
];
|
||||
let selection = [...this.state.selection];
|
||||
const keyIndex = selection.indexOf(key);
|
||||
// check to see if the key exists
|
||||
if(keyIndex>=0) {
|
||||
if (keyIndex >= 0) {
|
||||
// it does exist so we will remove it using destructing
|
||||
selection = [
|
||||
...selection.slice(0,keyIndex),
|
||||
...selection.slice(keyIndex+1)
|
||||
]
|
||||
...selection.slice(0, keyIndex),
|
||||
...selection.slice(keyIndex + 1)
|
||||
];
|
||||
} else {
|
||||
// it does not exist so add it
|
||||
selection.push(key);
|
||||
}
|
||||
// update the state
|
||||
this.setState({selection});
|
||||
this.setState({ selection });
|
||||
}
|
||||
}
|
||||
};
|
||||
toggleAll = () => {
|
||||
/*
|
||||
'toggleAll' is a tricky concept with any filterable table
|
||||
@@ -121,10 +111,9 @@ export class ComponentTest extends React.Component {
|
||||
That can then be iterrated to get all the currently visible records and set
|
||||
the selection state.
|
||||
*/
|
||||
const selectAll = this.state.selectAll?false:true;
|
||||
const selectAll = this.state.selectAll ? false : true;
|
||||
const selection = [];
|
||||
if(selectAll)
|
||||
{
|
||||
if (selectAll) {
|
||||
// we need to get at the internals of ReactTable
|
||||
const wrappedInstance = this.selectTable.getWrappedInstance();
|
||||
// the 'sortedData' property contains the currently accessible records based on the filter and sort
|
||||
@@ -132,41 +121,59 @@ export class ComponentTest extends React.Component {
|
||||
// we need to get all the 'real' (original) records out to get at their IDs
|
||||
const nodes = getNodes(currentRecords);
|
||||
// we just push all the IDs onto the selection array
|
||||
nodes.forEach((item)=>{
|
||||
nodes.forEach(item => {
|
||||
selection.push(item._id);
|
||||
})
|
||||
});
|
||||
}
|
||||
this.setState({selectAll,selection})
|
||||
}
|
||||
isSelected = (key) => {
|
||||
this.setState({ selectAll, selection });
|
||||
};
|
||||
isSelected = key => {
|
||||
/*
|
||||
Instead of passing our external selection state we provide an 'isSelected'
|
||||
callback and detect the selection state ourselves. This allows any implementation
|
||||
for selection (either an array, object keys, or even a Javascript Set object).
|
||||
*/
|
||||
return this.state.selection.includes(key);
|
||||
}
|
||||
};
|
||||
logSelection = () => {
|
||||
console.log('selection:',this.state.selection);
|
||||
}
|
||||
console.log("selection:", this.state.selection);
|
||||
};
|
||||
toggleType = () => {
|
||||
this.setState({ selectType: this.state.selectType === 'radio' ? 'checkbox' : 'radio', selection: [], selectAll: false, });
|
||||
}
|
||||
this.setState({
|
||||
selectType: this.state.selectType === "radio" ? "checkbox" : "radio",
|
||||
selection: [],
|
||||
selectAll: false
|
||||
});
|
||||
};
|
||||
toggleTree = () => {
|
||||
if(this.state.pivotBy.length) {
|
||||
this.setState({pivotBy:[],expanded:{}});
|
||||
if (this.state.pivotBy.length) {
|
||||
this.setState({ pivotBy: [], expanded: {} });
|
||||
} else {
|
||||
this.setState({pivotBy:['state','post'],expanded:{}});
|
||||
this.setState({ pivotBy: ["state", "post"], expanded: {} });
|
||||
}
|
||||
}
|
||||
onExpandedChange = (expanded) => {
|
||||
this.setState({expanded});
|
||||
}
|
||||
render(){
|
||||
const { toggleSelection, toggleAll, isSelected, logSelection, toggleType, toggleTree, onExpandedChange, } = this;
|
||||
const { data, columns, selectAll, selectType, pivotBy, expanded, } = this.state;
|
||||
const extraProps =
|
||||
{
|
||||
};
|
||||
onExpandedChange = expanded => {
|
||||
this.setState({ expanded });
|
||||
};
|
||||
render() {
|
||||
const {
|
||||
toggleSelection,
|
||||
toggleAll,
|
||||
isSelected,
|
||||
logSelection,
|
||||
toggleType,
|
||||
toggleTree,
|
||||
onExpandedChange
|
||||
} = this;
|
||||
const {
|
||||
data,
|
||||
columns,
|
||||
selectAll,
|
||||
selectType,
|
||||
pivotBy,
|
||||
expanded
|
||||
} = this.state;
|
||||
const extraProps = {
|
||||
selectAll,
|
||||
isSelected,
|
||||
toggleAll,
|
||||
@@ -175,39 +182,54 @@ export class ComponentTest extends React.Component {
|
||||
pivotBy,
|
||||
expanded,
|
||||
onExpandedChange,
|
||||
pageSize: 5,
|
||||
}
|
||||
pageSize: 5
|
||||
};
|
||||
return (
|
||||
<div style={{ padding: '10px'}}>
|
||||
<div style={{ padding: "10px" }}>
|
||||
<h1>react-table - Select Tree Table</h1>
|
||||
<p>This example combines two HOCs (the TreeTable and the SelectTable) to make a composite component.</p>
|
||||
<p>
|
||||
This example combines two HOCs (the TreeTable and the SelectTable) to
|
||||
make a composite component.
|
||||
</p>
|
||||
<p>We'll call it SelectTreeTable!</p>
|
||||
<p>Here is what the buttons do:</p>
|
||||
<ul>
|
||||
<li><strong>Toggle Tree:</strong> enables or disabled the pivotBy on the table.</li>
|
||||
<li><strong>Select Type:</strong> changes from 'checkbox' to 'radio' and back again.</li>
|
||||
<li><strong>Log Selection to Console:</strong> open your console to see what has been selected.</li>
|
||||
<li>
|
||||
<strong>Toggle Tree:</strong> enables or disabled the pivotBy on the
|
||||
table.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Select Type:</strong> changes from 'checkbox' to 'radio' and
|
||||
back again.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Log Selection to Console:</strong> open your console to see
|
||||
what has been selected.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
<strong>NOTE:</strong> the selection is maintained when toggling the tree on and off but is cleared
|
||||
when switching between select types (radio, checkbox).
|
||||
<strong>NOTE:</strong> the selection is maintained when toggling the
|
||||
tree on and off but is cleared when switching between select types
|
||||
(radio, checkbox).
|
||||
</p>
|
||||
<button onClick={toggleTree}>Toggle Tree [{pivotBy && pivotBy.length ? pivotBy.join(', ') : ''}]</button>
|
||||
<button onClick={toggleType}>Select Type: <strong>{selectType}</strong></button>
|
||||
<button onClick={toggleTree}>
|
||||
Toggle Tree [{pivotBy && pivotBy.length ? pivotBy.join(", ") : ""}]
|
||||
</button>
|
||||
<button onClick={toggleType}>
|
||||
Select Type: <strong>{selectType}</strong>
|
||||
</button>
|
||||
<button onClick={logSelection}>Log Selection to Console</button>
|
||||
{` (${this.state.selection.length}) selected`}
|
||||
{
|
||||
data?
|
||||
{data ? (
|
||||
<SelectTreeTable
|
||||
data={data}
|
||||
columns={columns}
|
||||
ref={(r)=>this.selectTable = r}
|
||||
ref={r => (this.selectTable = r)}
|
||||
className="-striped -highlight"
|
||||
freezeWhenExpanded={true}
|
||||
{...extraProps}
|
||||
/>
|
||||
:null
|
||||
}
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
import React from "react";
|
||||
|
||||
import React from 'react';
|
||||
import ReactTable from "../../../../lib/index";
|
||||
import "../../../../react-table.css";
|
||||
|
||||
import ReactTable from '../../../../lib/index'
|
||||
import '../../../../react-table.css'
|
||||
import treeTableHOC from "../../../../lib/hoc/treeTable";
|
||||
|
||||
import treeTableHOC from '../../../../lib/hoc/treeTable'
|
||||
|
||||
async function getData()
|
||||
{
|
||||
const result = await ( await fetch('/au_500_tree.json') ).json();
|
||||
async function getData() {
|
||||
const result = await (await fetch("/au_500_tree.json")).json();
|
||||
return result;
|
||||
}
|
||||
|
||||
function getColumns(data,pivotBy)
|
||||
{
|
||||
function getColumns(data, pivotBy) {
|
||||
const columns = [];
|
||||
const sample = data[0];
|
||||
for(let key in sample)
|
||||
{
|
||||
for (let key in sample) {
|
||||
columns.push({
|
||||
accessor: key,
|
||||
Header: key,
|
||||
})
|
||||
Header: key
|
||||
});
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
@@ -29,49 +25,43 @@ function getColumns(data,pivotBy)
|
||||
export class ComponentTest extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state =
|
||||
{
|
||||
this.state = {
|
||||
data: null,
|
||||
columns: null,
|
||||
pivotBy: null, // ["firstName", "lastName"],
|
||||
pivotBy: null // ["firstName", "lastName"],
|
||||
};
|
||||
}
|
||||
componentDidMount()
|
||||
{
|
||||
getData().then((data)=>{
|
||||
componentDidMount() {
|
||||
getData().then(data => {
|
||||
// console.log('cwm data:',data);
|
||||
const pivotBy = ['state','post','city'];
|
||||
const columns = getColumns(data,pivotBy);
|
||||
const pivotBy = ["state", "post", "city"];
|
||||
const columns = getColumns(data, pivotBy);
|
||||
// console.log('cwm cols:',columns);
|
||||
this.setState({data,columns,pivotBy});
|
||||
this.setState({ data, columns, pivotBy });
|
||||
});
|
||||
}
|
||||
showState = ()=>
|
||||
{
|
||||
console.log('state:',this.reactTable.getResolvedState());
|
||||
}
|
||||
render(){
|
||||
showState = () => {
|
||||
console.log("state:", this.reactTable.getResolvedState());
|
||||
};
|
||||
render() {
|
||||
const { data, columns, pivotBy } = this.state;
|
||||
const extraProps =
|
||||
{
|
||||
const extraProps = {
|
||||
data,
|
||||
columns,
|
||||
pivotBy,
|
||||
}
|
||||
pivotBy
|
||||
};
|
||||
const TreeTable = treeTableHOC(ReactTable);
|
||||
return (
|
||||
<div style={{ padding: '10px'}}>
|
||||
<div style={{ padding: "10px" }}>
|
||||
<h1>react-table - Tree Table</h1>
|
||||
{
|
||||
data?
|
||||
{data ? (
|
||||
<TreeTable
|
||||
ref={(r)=>this.reactTable=r}
|
||||
className="-striped -highlight"
|
||||
defaultPageSize={5}
|
||||
{...extraProps}
|
||||
/>
|
||||
:null
|
||||
}
|
||||
ref={r => (this.reactTable = r)}
|
||||
className="-striped -highlight"
|
||||
defaultPageSize={5}
|
||||
{...extraProps}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,58 +1,53 @@
|
||||
import React from "react";
|
||||
|
||||
|
||||
import React from 'react';
|
||||
|
||||
export default (Component) => {
|
||||
const wrapper = (componentProps) => {
|
||||
const TrComponent = (props) => {
|
||||
export default Component => {
|
||||
const wrapper = componentProps => {
|
||||
const TrComponent = props => {
|
||||
const { ri, ...rest } = props;
|
||||
if(ri && ri.groupedByPivot) {
|
||||
if (ri && ri.groupedByPivot) {
|
||||
const cell = props.children[ri.level];
|
||||
|
||||
cell.props.style.flex = 'unset';
|
||||
cell.props.style.width = '100%';
|
||||
cell.props.style.maxWidth = 'unset';
|
||||
cell.props.style.paddingLeft = `${componentProps.treeTableIndent*ri.level}px`;
|
||||
cell.props.style.backgroundColor = '#DDD';
|
||||
cell.props.style.borderBottom = '1px solid rgba(128,128,128,0.2)';
|
||||
|
||||
|
||||
cell.props.style.flex = "unset";
|
||||
cell.props.style.width = "100%";
|
||||
cell.props.style.maxWidth = "unset";
|
||||
cell.props.style.paddingLeft = `${componentProps.treeTableIndent *
|
||||
ri.level}px`;
|
||||
cell.props.style.backgroundColor = "#DDD";
|
||||
cell.props.style.borderBottom = "1px solid rgba(128,128,128,0.2)";
|
||||
|
||||
return <div {...rest}>{cell}</div>;
|
||||
}
|
||||
return <Component.defaultProps.TrComponent {...rest} />;
|
||||
}
|
||||
};
|
||||
|
||||
const getTrProps = (state,ri,ci,instance) => {
|
||||
return {ri};
|
||||
}
|
||||
const getTrProps = (state, ri, ci, instance) => {
|
||||
return { ri };
|
||||
};
|
||||
|
||||
const { columns, ...rest } = componentProps;
|
||||
const extra = {
|
||||
columns: columns.map((col)=>{
|
||||
columns: columns.map(col => {
|
||||
let column = col;
|
||||
if(rest.pivotBy && rest.pivotBy.includes(col.accessor))
|
||||
{
|
||||
if (rest.pivotBy && rest.pivotBy.includes(col.accessor)) {
|
||||
column = {
|
||||
accessor: col.accessor,
|
||||
width: `${componentProps.treeTableIndent}px`,
|
||||
show: false,
|
||||
Header: '',
|
||||
}
|
||||
Header: ""
|
||||
};
|
||||
}
|
||||
return column;
|
||||
}),
|
||||
TrComponent,
|
||||
getTrProps,
|
||||
getTrProps
|
||||
};
|
||||
|
||||
return (
|
||||
<Component {...rest} {...extra} />
|
||||
)
|
||||
}
|
||||
wrapper.displayName = 'RTTreeTable';
|
||||
wrapper.defaultProps =
|
||||
{
|
||||
treeTableRowBackground: '#EEE',
|
||||
treeTableIndent: 10,
|
||||
}
|
||||
|
||||
return <Component {...rest} {...extra} />;
|
||||
};
|
||||
wrapper.displayName = "RTTreeTable";
|
||||
wrapper.defaultProps = {
|
||||
treeTableRowBackground: "#EEE",
|
||||
treeTableIndent: 10
|
||||
};
|
||||
return wrapper;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import namor from "namor";
|
||||
|
||||
const range = len => {
|
||||
@@ -20,7 +19,9 @@ const newPerson = () => {
|
||||
status:
|
||||
statusChance > 0.66
|
||||
? "relationship"
|
||||
: statusChance > 0.33 ? "complicated" : "single"
|
||||
: statusChance > 0.33
|
||||
? "complicated"
|
||||
: "single"
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
+4
-2
@@ -1,5 +1,7 @@
|
||||
html, body, #root {
|
||||
height: 100%
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
|
||||
+5
-8
@@ -1,10 +1,7 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
//
|
||||
import './index.css'
|
||||
import App from './App.js'
|
||||
import "./index.css";
|
||||
import App from "./App.js";
|
||||
|
||||
ReactDOM.render(
|
||||
<App />,
|
||||
document.getElementById('root')
|
||||
)
|
||||
ReactDOM.render(<App />, document.getElementById("root"));
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
/* eslint-disable */
|
||||
import React from 'react'
|
||||
import marked from 'marked'
|
||||
import React from "react";
|
||||
import marked from "marked";
|
||||
//
|
||||
import HOCReadme from '!raw!../../../src/hoc/README.md'
|
||||
import 'github-markdown-css/github-markdown.css'
|
||||
import './utils/prism.js'
|
||||
import HOCReadme from "!raw!../../../src/hoc/README.md";
|
||||
import "github-markdown-css/github-markdown.css";
|
||||
import "./utils/prism.js";
|
||||
|
||||
export default class HOCStory extends React.Component {
|
||||
render () {
|
||||
render() {
|
||||
return (
|
||||
<div style={{ padding: '10px' }}>
|
||||
<div style={{ padding: "10px" }}>
|
||||
<span
|
||||
className='markdown-body'
|
||||
className="markdown-body"
|
||||
dangerouslySetInnerHTML={{ __html: marked(HOCReadme) }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
componentDidMount () {
|
||||
global.Prism && global.Prism.highlightAll()
|
||||
componentDidMount() {
|
||||
global.Prism && global.Prism.highlightAll();
|
||||
}
|
||||
}
|
||||
|
||||
+11
-11
@@ -1,23 +1,23 @@
|
||||
/* eslint-disable import/no-webpack-loader-syntax */
|
||||
import React from 'react'
|
||||
import marked from 'marked'
|
||||
import React from "react";
|
||||
import marked from "marked";
|
||||
//
|
||||
import Readme from '!raw!../../../README.md'
|
||||
import 'github-markdown-css/github-markdown.css'
|
||||
import './utils/prism.js'
|
||||
import Readme from "!raw!../../../README.md";
|
||||
import "github-markdown-css/github-markdown.css";
|
||||
import "./utils/prism.js";
|
||||
|
||||
export default class Story extends React.Component {
|
||||
render () {
|
||||
render() {
|
||||
return (
|
||||
<div style={{ padding: '10px' }}>
|
||||
<div style={{ padding: "10px" }}>
|
||||
<span
|
||||
className='markdown-body'
|
||||
className="markdown-body"
|
||||
dangerouslySetInnerHTML={{ __html: marked(Readme) }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
componentDidMount () {
|
||||
global.Prism && global.Prism.highlightAll()
|
||||
componentDidMount() {
|
||||
global.Prism && global.Prism.highlightAll();
|
||||
}
|
||||
}
|
||||
|
||||
+14
-18
@@ -1,31 +1,27 @@
|
||||
import React from "react";
|
||||
|
||||
import React from 'react'
|
||||
|
||||
import ReactTable from '../../../lib/index'
|
||||
import '../../../react-table.css'
|
||||
import ReactTable from "../../../lib/index";
|
||||
import "../../../react-table.css";
|
||||
|
||||
const data = [
|
||||
{ one: '1.1', two: '1.2' },
|
||||
{ one: '2.1', two: '2.2' },
|
||||
{ one: '3.1', two: '3.2' },
|
||||
{ one: '4.1', two: '4.2' },
|
||||
]
|
||||
{ one: "1.1", two: "1.2" },
|
||||
{ one: "2.1", two: "2.2" },
|
||||
{ one: "3.1", two: "3.2" },
|
||||
{ one: "4.1", two: "4.2" }
|
||||
];
|
||||
|
||||
const columns = [
|
||||
{ accessor: 'one', Header: 'One' },
|
||||
{ accessor: 'two', Header: 'Two' },
|
||||
]
|
||||
{ accessor: "one", Header: "One" },
|
||||
{ accessor: "two", Header: "Two" }
|
||||
];
|
||||
|
||||
export default class Story extends React.Component {
|
||||
render () {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
Test
|
||||
<ReactTable
|
||||
data={data}
|
||||
columns={columns}
|
||||
/>
|
||||
<ReactTable data={data} columns={columns} />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 36 KiB After Width: | Height: | Size: 36 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 152 KiB |
Generated
+8279
File diff suppressed because it is too large
Load Diff
+80
-22
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-table",
|
||||
"version": "6.7.4",
|
||||
"version": "6.11.2",
|
||||
"description": "A fast, lightweight, opinionated table and datagrid built on React",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/react-tools/react-table#readme",
|
||||
@@ -15,24 +15,29 @@
|
||||
"datagrid"
|
||||
],
|
||||
"main": "lib/index.js",
|
||||
"module": "es/index.js",
|
||||
"files": [
|
||||
"src/",
|
||||
"es/",
|
||||
"lib/",
|
||||
"react-table.js",
|
||||
"react-table.min.js",
|
||||
"react-table.css",
|
||||
"media/*.png"
|
||||
],
|
||||
"scripts": {
|
||||
"build:node": "babel src --out-dir lib --source-maps inline",
|
||||
"build:css": "rimraf react-table.css && stylus src/index.styl --compress -o react-table.css && yarn run css:autoprefix",
|
||||
"build:cjs": "babel src --out-dir lib --source-maps inline --copy-files",
|
||||
"build:es": "cross-env BABEL_ENV=es babel src --out-dir es --source-maps inline",
|
||||
"build:umd": "cross-env BABEL_ENV=umd rollup -c",
|
||||
"build:umd-min": "cross-env BABEL_ENV=umd NODE_ENV=production rollup -c",
|
||||
"build:css": "rimraf react-table.css && stylus src/index.styl --compress -o react-table.css && yarn css:autoprefix",
|
||||
"css:autoprefix": "postcss --use autoprefixer react-table.css -r",
|
||||
"watch": "npm-run-all --parallel watch:*",
|
||||
"watch:node": "onchange 'src/**/*.js' -i -- npm run build:node",
|
||||
"watch:css": "onchange 'src/**/*.styl' -i -- npm run build:css",
|
||||
"watch:js": "onchange 'src/**/*.js' -i -- yarn build:cjs",
|
||||
"watch:css": "onchange 'src/**/*.styl' -i -- yarn build:css",
|
||||
"test": "eslint src",
|
||||
"umd": "rimraf react-table.js && webpack --config umd.webpack.js",
|
||||
"build": "npm-run-all build:*",
|
||||
"prepublish": "npm run build && npm run umd",
|
||||
"prepublish": "yarn build",
|
||||
"postpublish": "git push --tags",
|
||||
"docs": "yarn watch & cd docs && yarn && yarn start",
|
||||
"docs:build": "yarn build && cd docs && yarn && yarn build"
|
||||
@@ -41,15 +46,20 @@
|
||||
"classnames": "^2.2.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^15.x.x || ^16.x.x"
|
||||
"prop-types": "^15.5.0",
|
||||
"react": "^16.x.x",
|
||||
"react-dom": "^16.x.x"
|
||||
},
|
||||
"devDependencies": {
|
||||
"autoprefixer": "^6.7.0",
|
||||
"babel-cli": "6.14.0",
|
||||
"babel-eslint": "6.1.2",
|
||||
"babel-preset-es2015": "6.14.0",
|
||||
"babel-preset-react": "6.11.1",
|
||||
"babel-preset-stage-2": "6.13.0",
|
||||
"babel-plugin-external-helpers": "^6.22.0",
|
||||
"babel-plugin-transform-class-properties": "^6.24.1",
|
||||
"babel-plugin-transform-object-rest-spread": "^6.26.0",
|
||||
"babel-preset-env": "^1.6.1",
|
||||
"babel-preset-react": "^6.24.1",
|
||||
"cross-env": "^5.1.4",
|
||||
"eslint": "^4.1.1",
|
||||
"eslint-config-react-tools": "^1.0.10",
|
||||
"eslint-plugin-class-property": "^1.0.6",
|
||||
@@ -57,23 +67,71 @@
|
||||
"eslint-plugin-jsx-a11y": "^6.0.2",
|
||||
"eslint-plugin-react": "^7.4.0",
|
||||
"match-sorter": "^1.8.0",
|
||||
"npm-run-all": "^3.1.1",
|
||||
"npm-run-all": "^4.1.2",
|
||||
"onchange": "^3.0.2",
|
||||
"postcss-cli": "^2.6.0",
|
||||
"prop-types": "^15.6.0",
|
||||
"react": "^15.4.2",
|
||||
"react-dom": "^15.4.2",
|
||||
"prop-types": "^15.7.2",
|
||||
"react": "^16.3.2",
|
||||
"react-dom": "^16.3.2",
|
||||
"react-json-tree": "^0.10.9",
|
||||
"rimraf": "^2.6.1",
|
||||
"rollup": "^0.55.3",
|
||||
"rollup-plugin-babel": "^3.0.3",
|
||||
"rollup-plugin-commonjs": "^8.3.0",
|
||||
"rollup-plugin-node-resolve": "^3.0.2",
|
||||
"rollup-plugin-replace": "^2.0.0",
|
||||
"rollup-plugin-uglify": "^3.0.0",
|
||||
"standard": "^10.0.2",
|
||||
"stylus": "^0.54.5",
|
||||
"webpack": "^2.5.1"
|
||||
"stylus": "^0.54.5"
|
||||
},
|
||||
"babel": {
|
||||
"presets": [
|
||||
"es2015",
|
||||
"stage-2",
|
||||
"react"
|
||||
]
|
||||
"env": {
|
||||
"development": {
|
||||
"presets": [
|
||||
[
|
||||
"env",
|
||||
{
|
||||
"modules": "commonjs"
|
||||
}
|
||||
],
|
||||
"react"
|
||||
],
|
||||
"plugins": [
|
||||
"transform-object-rest-spread",
|
||||
"transform-class-properties"
|
||||
]
|
||||
},
|
||||
"es": {
|
||||
"presets": [
|
||||
[
|
||||
"env",
|
||||
{
|
||||
"modules": false
|
||||
}
|
||||
],
|
||||
"react"
|
||||
],
|
||||
"plugins": [
|
||||
"transform-object-rest-spread",
|
||||
"transform-class-properties"
|
||||
]
|
||||
},
|
||||
"umd": {
|
||||
"presets": [
|
||||
[
|
||||
"env",
|
||||
{
|
||||
"modules": false
|
||||
}
|
||||
],
|
||||
"react"
|
||||
],
|
||||
"plugins": [
|
||||
"transform-object-rest-spread",
|
||||
"transform-class-properties",
|
||||
"external-helpers"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import nodeResolve from 'rollup-plugin-node-resolve'
|
||||
import babel from 'rollup-plugin-babel'
|
||||
import replace from 'rollup-plugin-replace'
|
||||
import commonjs from 'rollup-plugin-commonjs'
|
||||
import uglify from 'rollup-plugin-uglify'
|
||||
|
||||
const env = process.env.NODE_ENV
|
||||
|
||||
const config = {
|
||||
input: 'src/index.js',
|
||||
output: {
|
||||
file: env === 'production' ? 'react-table.min.js' : 'react-table.js',
|
||||
format: 'umd',
|
||||
globals: {
|
||||
react: 'React',
|
||||
},
|
||||
name: 'ReactTable',
|
||||
exports: 'named',
|
||||
},
|
||||
external: ['react'],
|
||||
plugins: [
|
||||
nodeResolve(),
|
||||
babel({
|
||||
exclude: '**/node_modules/**',
|
||||
}),
|
||||
replace({
|
||||
'process.env.NODE_ENV': JSON.stringify(env),
|
||||
}),
|
||||
commonjs(),
|
||||
],
|
||||
}
|
||||
|
||||
if (env === 'production') {
|
||||
config.plugins.push(uglify({
|
||||
compress: {
|
||||
dead_code: true,
|
||||
warnings: false,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
export default config
|
||||
+59
-41
@@ -9,12 +9,14 @@ const emptyObj = () => ({})
|
||||
export default {
|
||||
// General
|
||||
data: [],
|
||||
resolveData: data => data,
|
||||
loading: false,
|
||||
showPagination: true,
|
||||
showPaginationTop: false,
|
||||
showPaginationBottom: true,
|
||||
showPageSizeOptions: true,
|
||||
pageSizeOptions: [5, 10, 20, 25, 50, 100],
|
||||
defaultPage: 0,
|
||||
defaultPageSize: 20,
|
||||
showPageJump: true,
|
||||
collapseOnSortingChange: true,
|
||||
@@ -33,9 +35,7 @@ export default {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultFilterMethod: (filter, row, column) => {
|
||||
const id = filter.pivotId || filter.id
|
||||
return row[id] !== undefined
|
||||
? String(row[id]).startsWith(filter.value)
|
||||
: true
|
||||
return row[id] !== undefined ? String(row[id]).startsWith(filter.value) : true
|
||||
},
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSortMethod: (a, b, desc) => {
|
||||
@@ -128,12 +128,14 @@ export default {
|
||||
PivotValue: undefined,
|
||||
Expander: undefined,
|
||||
Filter: undefined,
|
||||
Placeholder: undefined,
|
||||
// All Columns
|
||||
sortable: undefined, // use table default
|
||||
resizable: undefined, // use table default
|
||||
filterable: undefined, // use table default
|
||||
show: true,
|
||||
minWidth: 100,
|
||||
minResizeWidth: 11,
|
||||
// Cells only
|
||||
className: '',
|
||||
style: {},
|
||||
@@ -173,42 +175,67 @@ export default {
|
||||
pageText: 'Page',
|
||||
ofText: 'of',
|
||||
rowsText: 'rows',
|
||||
pageJumpText: 'jump to page',
|
||||
rowsSelectorText: 'rows per page',
|
||||
|
||||
// Components
|
||||
TableComponent: _.makeTemplateComponent('rt-table', 'Table'),
|
||||
TheadComponent: _.makeTemplateComponent('rt-thead', 'Thead'),
|
||||
TbodyComponent: _.makeTemplateComponent('rt-tbody', 'Tbody'),
|
||||
TrGroupComponent: _.makeTemplateComponent('rt-tr-group', 'TrGroup'),
|
||||
TrComponent: _.makeTemplateComponent('rt-tr', 'Tr'),
|
||||
ThComponent: ({ toggleSort, className, children, ...rest }) => (
|
||||
TableComponent: ({ children, className, ...rest }) => (
|
||||
<div
|
||||
className={classnames('rt-th', className)}
|
||||
onClick={e => (
|
||||
toggleSort && toggleSort(e)
|
||||
)}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className={classnames('rt-table', className)}
|
||||
role="grid"
|
||||
// tabIndex='0'
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
TdComponent: _.makeTemplateComponent('rt-td', 'Td'),
|
||||
TheadComponent: _.makeTemplateComponent('rt-thead', 'Thead'),
|
||||
TbodyComponent: _.makeTemplateComponent('rt-tbody', 'Tbody'),
|
||||
TrGroupComponent: ({ children, className, ...rest }) => (
|
||||
<div className={classnames('rt-tr-group', className)} role="rowgroup" {...rest}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
TrComponent: ({ children, className, ...rest }) => (
|
||||
<div className={classnames('rt-tr', className)} role="row" {...rest}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
ThComponent: ({
|
||||
toggleSort, className, children, ...rest
|
||||
}) => (
|
||||
// eslint-disable-next-line jsx-a11y/click-events-have-key-events
|
||||
<div
|
||||
className={classnames('rt-th', className)}
|
||||
onClick={e => toggleSort && toggleSort(e)}
|
||||
role="columnheader"
|
||||
tabIndex="-1" // Resolves eslint issues without implementing keyboard navigation incorrectly
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
TdComponent: ({
|
||||
toggleSort, className, children, ...rest
|
||||
}) => (
|
||||
<div className={classnames('rt-td', className)} role="gridcell" {...rest}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
TfootComponent: _.makeTemplateComponent('rt-tfoot', 'Tfoot'),
|
||||
FilterComponent: ({ filter, onChange }) => (
|
||||
FilterComponent: ({ filter, onChange, column }) => (
|
||||
<input
|
||||
type="text"
|
||||
style={{
|
||||
width: '100%',
|
||||
}}
|
||||
placeholder={column.Placeholder}
|
||||
value={filter ? filter.value : ''}
|
||||
onChange={event => onChange(event.target.value)}
|
||||
/>
|
||||
),
|
||||
ExpanderComponent: ({ isExpanded }) => (
|
||||
<div className={classnames('rt-expander', isExpanded && '-open')}>
|
||||
•
|
||||
</div>
|
||||
<div className={classnames('rt-expander', isExpanded && '-open')}>•</div>
|
||||
),
|
||||
PivotValueComponent: ({ subRows, value }) => (
|
||||
<span>
|
||||
@@ -216,34 +243,25 @@ export default {
|
||||
</span>
|
||||
),
|
||||
AggregatedComponent: ({ subRows, column }) => {
|
||||
const previewValues = subRows
|
||||
.filter(d => typeof d[column.id] !== 'undefined')
|
||||
.map((row, i) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<span key={i}>
|
||||
{row[column.id]}
|
||||
{i < subRows.length - 1 ? ', ' : ''}
|
||||
</span>
|
||||
))
|
||||
return (
|
||||
<span>
|
||||
{previewValues}
|
||||
const previewValues = subRows.filter(d => typeof d[column.id] !== 'undefined').map((row, i) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<span key={i}>
|
||||
{row[column.id]}
|
||||
{i < subRows.length - 1 ? ', ' : ''}
|
||||
</span>
|
||||
)
|
||||
))
|
||||
return <span>{previewValues}</span>
|
||||
},
|
||||
PivotComponent: undefined, // this is a computed default generated using
|
||||
// the ExpanderComponent and PivotValueComponent at run-time in methods.js
|
||||
PaginationComponent: Pagination,
|
||||
PreviousComponent: undefined,
|
||||
NextComponent: undefined,
|
||||
LoadingComponent: ({ className, loading, loadingText, ...rest }) => (
|
||||
<div
|
||||
className={classnames('-loading', { '-active': loading }, className)}
|
||||
{...rest}
|
||||
>
|
||||
<div className="-loading-inner">
|
||||
{loadingText}
|
||||
</div>
|
||||
LoadingComponent: ({
|
||||
className, loading, loadingText, ...rest
|
||||
}) => (
|
||||
<div className={classnames('-loading', { '-active': loading }, className)} {...rest}>
|
||||
<div className="-loading-inner">{loadingText}</div>
|
||||
</div>
|
||||
),
|
||||
NoDataComponent: _.makeTemplateComponent('rt-noData', 'NoData'),
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
|
||||
<div style="text-align:center;">
|
||||
<a href="https://github.com/react-tools/react-table" target="\_parent"><img src="https://github.com/react-tools/media/raw/master/logo-react-table.png" alt="React Table Logo" style="width:450px;"/></a>
|
||||
</div>
|
||||
|
||||
# ReactTable - expanding with HOCs
|
||||
This documentation is about expanding ReactTable using Higher Order Components/Functions.
|
||||
|
||||
## Covered in this README
|
||||
- A Brief explanation of HOCs and why they are a good approach for ReactTable enhancements
|
||||
- Documentation of the currently available HOCs
|
||||
- TreeTable
|
||||
- SelectTable
|
||||
- Documentation of the standard for writing HOCs with ReactTable
|
||||
|
||||
## What are HOCs and why use them with ReactTable
|
||||
HOCs (or Higher Order Components/Functions) are either a React Component (or a function that returns a React Component)
|
||||
that are used to enhance the functionality of an existing component. How much you can enhance depends on the props that
|
||||
the component exposes.
|
||||
|
||||
Fortunately, ReactTable exposes a LOT of functionality as props to the component. In some cases there are too many
|
||||
props to keep track of and that is where HOCs come in.
|
||||
|
||||
You can write a HOC that just focusses on the additional functionality you want to enhance and keep those enhancements to
|
||||
reuse over and over again when you need them. You don't have to edit the ReactSource code, just wrap ReactTable in one or
|
||||
more HOCs (more on some issues related to chaining HOCs later) that provide the additional functionality you want to expose.
|
||||
|
||||
The most obvious HOC is one that can add `checkbox` or select functionality. The HOC included provides `select` functionality
|
||||
that allows the developer to specify if they want a `checkbox` or `radio` style of select column. The implementation of the
|
||||
selection is recorded (e.g. in component state, Redux, etc.) and how to manage multiple selections. The HOC really only handles
|
||||
the rendering pieces.
|
||||
|
||||
But there is more documentation on the `select` HOC below.
|
||||
|
||||
|
||||
## Currently Available HOCs
|
||||
|
||||
### TreeTable
|
||||
TreeTable takes over the rendering of the generated pivot rows of ReactTable so that they appear more like an expandable Tree.
|
||||
|
||||
It accomplishes this by rendering a 100% wide div and then only rendering the cell that controls the pivot at that level.
|
||||
|
||||
Using it is as simple as doing the following:
|
||||
```javascript
|
||||
import ReactTable from 'react-table'
|
||||
import treeTableHOC from 'react-table/lib/hoc/treeTable'
|
||||
|
||||
const TreeTable = treeTableHOC(ReactTable)
|
||||
```
|
||||
After you have done the above, you can then use `TreeTable` just as you would `ReactTable` but it will render pivots using
|
||||
the Tree style described above.
|
||||
|
||||
|
||||
### SelectTable
|
||||
SelectTable is a little trickier. The HOCs attempt to avoid adding additional state and, as there is no internal ID for a row that
|
||||
can be relied on to be static (ReactTable just reuses indexes when rendering) the developer has to maintain the state outside of even
|
||||
the wrapped component. So it is largely based on callbacks.
|
||||
|
||||
You include the HOC in the same manner as you would for the treeTableHOC but then need to provide the following overrides:
|
||||
- isSelected - returns `true` if the key passed is selected otherwise it should return `false`
|
||||
- selectAll - a property that indicates if the selectAll is set (`true|false`)
|
||||
- toggleAll - called when the user clicks the `selectAll` checkbox/radio
|
||||
- toggleSelection - called when the use clicks a specific checkbox/radio in a row
|
||||
- selectType - either `checkbox|radio` to indicate what type of selection is required
|
||||
|
||||
In the case of `radio` there is no `selectAll` displayed but the developer is responsible for only making one selection in
|
||||
the controlling component's state. You could select multiple but it wouldn't make sense and you should use `checkbox` instead.
|
||||
|
||||
You also have to decide what `selectAll` means. Given ReactTable is a paged solution there are other records off-page. When someone
|
||||
selects the `selectAll` checkbox, should it mark every possible record, only what might be visible to due a Filter or only those items
|
||||
on the current page?
|
||||
|
||||
The example opts for the middle approach so it gets a `ref` to the ReactTable instance and pulls the `sortedData` out of the resolved
|
||||
state (then walks through those records and pulls their ID into the `selection` state of the controlling component).
|
||||
|
||||
You can also replace the input component that is used to render the select box and select all box:
|
||||
- SelectAllInputComponent - the checkbox in the top left corner
|
||||
- SelectInputComponent - the checkbox used on a row
|
||||
|
||||
### SelectTreeTable
|
||||
SelectTreeTable is a combination of TreeTable and SelectTable.
|
||||
|
||||
To function correctly the chain has to be in the correct order as follows (see the comments in the guid on HOCs below).
|
||||
|
||||
```Javascript
|
||||
const SelectTreeTable = selectTableHOC(treeTableHOC(ReactTable));
|
||||
```
|
||||
|
||||
In this particular instance it is (probably) because the functions need access to the state on the wrapped component to manage
|
||||
the selected items. Although that is not totally clearly the issue.
|
||||
|
||||
## HOC Guide for ReactTable
|
||||
There are a few rules required when writing a HOC for ReactTable (other than meeting the normal lint standards - which are
|
||||
still being developed).
|
||||
|
||||
Firstly, there are issues with `ref` when you write a HOC. Consider a deeply nested component wrapped in multiple HOCs...
|
||||
|
||||
A HOC in the middle of the chain requires access to the instance of the component it thinks it is wrapping but there is at
|
||||
least one other wrapper in the way. The challenge is: How do I get to the actual wrapped component?
|
||||
|
||||
Each HOC is required to be a React Class so that a `ref` can be obtained against each component:
|
||||
|
||||
```Javascript
|
||||
<Component ... ref={r => this.wrappedInstance = r} />
|
||||
```
|
||||
*NOTE:* "Component" can also be the `<ReactTable />` instance.
|
||||
|
||||
Then the following method needs
|
||||
to be placed on the class so that it exposes the correct instance of ReactTable:
|
||||
|
||||
```Javascript
|
||||
getWrappedInstance() {
|
||||
if (!this.wrappedInstance) console.warn('<component name here> - No wrapped instance')
|
||||
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance()
|
||||
else return this.wrappedInstance
|
||||
}
|
||||
```
|
||||
Essentially this will walk down the chain (if there are chained HOCs) and stop when it gets to the end and return the wrapped instance.
|
||||
|
||||
Finally, sometimes the chains need to be in a specific order to function correctly. It is not clear if this is just an architectural
|
||||
issue or if it would be better solved using a library like `recompose`. Anyone who is able to contribute a reliable solution to this
|
||||
is welcome to submit a PR.
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import React, { Component } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import set from 'lodash.set'
|
||||
import get from 'lodash.get'
|
||||
|
||||
/*
|
||||
AdvancedExpandTableHOC for ReactTable
|
||||
|
||||
HOC which allows any Cell in the row to toggle the row's
|
||||
SubComponent. Also allows the SubComponent to toggle itself.
|
||||
|
||||
Expand functions available to any SubComponent or Column Cell:
|
||||
toggleRowSubComponent
|
||||
showRowSubComponent
|
||||
hideRowSubComponent
|
||||
|
||||
Each Column Renderer (E.g. Cell ) gets the expand functions in its props
|
||||
And Each SubComponent gets the expand functions in its props
|
||||
|
||||
Expand functions takes the `rowInfo` given to each
|
||||
Column Renderer and SubComponent already by ReactTable.
|
||||
*/
|
||||
|
||||
export const subComponentWithToggle = (SubComponent, expandFuncs) => props => (
|
||||
<SubComponent {...props} {...expandFuncs} />
|
||||
)
|
||||
|
||||
// each cell in the column gets passed the function to toggle a sub component
|
||||
export const columnsWithToggle = (columns, expandFuncs) =>
|
||||
columns.map(column => {
|
||||
if (column.columns) {
|
||||
return {
|
||||
...column,
|
||||
columns: columnsWithToggle(column.columns, expandFuncs),
|
||||
}
|
||||
}
|
||||
return {
|
||||
...column,
|
||||
getProps () {
|
||||
return {
|
||||
...expandFuncs,
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
export const advancedExpandTableHOC = TableComponent =>
|
||||
class AdvancedExpandTable extends Component {
|
||||
// after initial render if we get new
|
||||
// data, columns, page changes, etc.
|
||||
// we reset expanded state.
|
||||
static getDerivedStateFromProps () {
|
||||
return {
|
||||
expanded: {},
|
||||
}
|
||||
}
|
||||
|
||||
constructor (props) {
|
||||
super(props)
|
||||
this.state = {
|
||||
expanded: {},
|
||||
}
|
||||
this.toggleRowSubComponent = this.toggleRowSubComponent.bind(this)
|
||||
this.showRowSubComponent = this.showRowSubComponent.bind(this)
|
||||
this.hideRowSubComponent = this.hideRowSubComponent.bind(this)
|
||||
this.getTdProps = this.getTdProps.bind(this)
|
||||
this.fireOnExpandedChange = this.fireOnExpandedChange.bind(this)
|
||||
this.expandFuncs = {
|
||||
toggleRowSubComponent: this.toggleRowSubComponent,
|
||||
showRowSubComponent: this.showRowSubComponent,
|
||||
hideRowSubComponent: this.hideRowSubComponent,
|
||||
}
|
||||
}
|
||||
|
||||
static propTypes = {
|
||||
columns: PropTypes.array.isRequired,
|
||||
SubComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element])
|
||||
.isRequired,
|
||||
onExpandedChange: PropTypes.func,
|
||||
};
|
||||
|
||||
static defaultProps = {
|
||||
onExpandedChange: null,
|
||||
};
|
||||
|
||||
static DisplayName = 'AdvancedExpandTable';
|
||||
|
||||
// since we pass the expand functions to each Cell,
|
||||
// we need to filter it out from being passed as an
|
||||
// actual DOM attribute. See getProps in columnsWithToggle above.
|
||||
static TdComponent ({
|
||||
toggleRowSubComponent,
|
||||
showRowSubComponent,
|
||||
hideRowSubComponent,
|
||||
...rest
|
||||
}) {
|
||||
return <TableComponent.defaultProps.TdComponent {...rest} />
|
||||
}
|
||||
|
||||
fireOnExpandedChange (rowInfo, e) {
|
||||
// fire callback once state has changed.
|
||||
if (this.props.onExpandedChange) {
|
||||
this.props.onExpandedChange(rowInfo, e)
|
||||
}
|
||||
}
|
||||
|
||||
resolveNewTableState (rowInfoOrNestingPath, e, expandType) {
|
||||
// derive nestingPath if only rowInfo is passed
|
||||
let nestingPath = rowInfoOrNestingPath
|
||||
|
||||
if (rowInfoOrNestingPath.nestingPath) {
|
||||
nestingPath = rowInfoOrNestingPath.nestingPath
|
||||
}
|
||||
|
||||
this.setState(
|
||||
prevState => {
|
||||
const isExpanded = get(prevState.expanded, nestingPath)
|
||||
// since we do not support nested rows, a shallow clone is okay.
|
||||
const newExpanded = { ...prevState.expanded }
|
||||
|
||||
switch (expandType) {
|
||||
case 'show':
|
||||
set(newExpanded, nestingPath, {})
|
||||
break
|
||||
case 'hide':
|
||||
set(newExpanded, nestingPath, false)
|
||||
break
|
||||
default:
|
||||
// toggle
|
||||
set(newExpanded, nestingPath, isExpanded ? false : {})
|
||||
}
|
||||
return {
|
||||
...prevState,
|
||||
expanded: newExpanded,
|
||||
}
|
||||
},
|
||||
() => this.fireOnExpandedChange(rowInfoOrNestingPath, e)
|
||||
)
|
||||
}
|
||||
|
||||
toggleRowSubComponent (rowInfo, e) {
|
||||
this.resolveNewTableState(rowInfo, e)
|
||||
}
|
||||
|
||||
showRowSubComponent (rowInfo, e) {
|
||||
this.resolveNewTableState(rowInfo, e, 'show')
|
||||
}
|
||||
|
||||
hideRowSubComponent (rowInfo, e) {
|
||||
this.resolveNewTableState(rowInfo, e, 'hide')
|
||||
}
|
||||
|
||||
getTdProps (tableState, rowInfo, column) {
|
||||
const { expander } = column
|
||||
|
||||
if (!expander) {
|
||||
// no overrides
|
||||
return {}
|
||||
}
|
||||
|
||||
return {
|
||||
// only override onClick for column Td
|
||||
onClick: e => {
|
||||
this.toggleRowSubComponent(rowInfo, e)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
getWrappedInstance () {
|
||||
if (!this.wrappedInstance) { console.warn('AdvancedExpandTable - No wrapped instance') }
|
||||
if (this.wrappedInstance.getWrappedInstance) {
|
||||
return this.wrappedInstance.getWrappedInstance()
|
||||
}
|
||||
return this.wrappedInstance
|
||||
}
|
||||
|
||||
render () {
|
||||
const {
|
||||
columns, SubComponent, onExpandedChange, ...rest
|
||||
} = this.props
|
||||
|
||||
const wrappedColumns = columnsWithToggle(columns, this.expandFuncs)
|
||||
const WrappedSubComponent = subComponentWithToggle(
|
||||
SubComponent,
|
||||
this.expandFuncs
|
||||
)
|
||||
|
||||
return (
|
||||
<TableComponent
|
||||
{...rest}
|
||||
columns={wrappedColumns}
|
||||
expanded={this.state.expanded}
|
||||
getTdProps={this.getTdProps}
|
||||
SubComponent={WrappedSubComponent}
|
||||
TdComponent={AdvancedExpandTable.TdComponent}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import React from 'react'
|
||||
import left from './left.svg'
|
||||
import right from './right.svg'
|
||||
|
||||
const defaultFoldIconComponent = ({ collapsed }) => {
|
||||
const style = { width: 25 }
|
||||
|
||||
if (collapsed) return <img src={right} style={style} alt="right" />
|
||||
return <img src={left} style={style} alt="left" />
|
||||
}
|
||||
|
||||
const defaultFoldButtonComponent = ({ header, collapsed, icon, onClick }) => {
|
||||
const style = {
|
||||
marginLeft: '0px',
|
||||
marginTop: '-5px',
|
||||
marginBottom: '-8px',
|
||||
float: 'left',
|
||||
cursor: 'pointer',
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={style} onClick={onClick}>
|
||||
{icon}
|
||||
</div>
|
||||
{!collapsed && <div>{header}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ReactTable => {
|
||||
const wrapper = class RTFoldableTable extends React.Component {
|
||||
static getDerivedStateFromProps(props, state) {
|
||||
if (state.resized !== props.resized) {
|
||||
return {
|
||||
resized: props.resized || [],
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
constructor(props, context) {
|
||||
super(props, context)
|
||||
|
||||
this.state = {
|
||||
folded: props.onFoldChange ? undefined : {},
|
||||
resized: props.resized || [],
|
||||
}
|
||||
}
|
||||
|
||||
onResizedChange = resized => {
|
||||
const { onResizedChange } = this.props
|
||||
if (onResizedChange) onResizedChange(resized)
|
||||
else {
|
||||
this.setState(p => ({ resized }))
|
||||
}
|
||||
}
|
||||
|
||||
removeResized = column => {
|
||||
const { id } = column
|
||||
if (!id) return
|
||||
|
||||
const { resized } = this.state
|
||||
if (!resized) return
|
||||
|
||||
const rs = resized.find(r => r.id === id)
|
||||
if (!rs) return
|
||||
|
||||
const newResized = resized.filter(r => r !== rs)
|
||||
this.onResizedChange(newResized)
|
||||
}
|
||||
|
||||
// this is so we can expose the underlying ReactTable.
|
||||
getWrappedInstance = () => {
|
||||
if (!this.wrappedInstance) console.warn('RTFoldableTable - No wrapped instance')
|
||||
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance()
|
||||
return this.wrappedInstance
|
||||
}
|
||||
|
||||
getCopiedKey = key => {
|
||||
const { foldableOriginalKey } = this.props
|
||||
return `${foldableOriginalKey}${key}`
|
||||
}
|
||||
|
||||
copyOriginals = column => {
|
||||
const { FoldedColumn } = this.props
|
||||
|
||||
// Stop copy if the column already copied
|
||||
if (column.original_Header) return
|
||||
|
||||
Object.keys(FoldedColumn).forEach(k => {
|
||||
const copiedKey = this.getCopiedKey(k)
|
||||
|
||||
if (k === 'Cell') column[copiedKey] = column[k] ? column[k] : c => c.value
|
||||
else column[copiedKey] = column[k]
|
||||
})
|
||||
|
||||
// Copy sub Columns
|
||||
if (column.columns && !column.original_Columns) column.original_Columns = column.columns
|
||||
|
||||
// Copy Header
|
||||
if (!column.original_Header) column.original_Header = column.Header
|
||||
}
|
||||
|
||||
restoreToOriginal = column => {
|
||||
const { FoldedColumn } = this.props
|
||||
|
||||
Object.keys(FoldedColumn).forEach(k => {
|
||||
// ignore header as handling by foldableHeaderRender
|
||||
if (k === 'Header') return
|
||||
|
||||
const copiedKey = this.getCopiedKey(k)
|
||||
column[k] = column[copiedKey]
|
||||
})
|
||||
|
||||
if (column.columns && column.original_Columns) column.columns = column.original_Columns
|
||||
}
|
||||
|
||||
getState = () => (this.props.onFoldChange ? this.props.folded : this.state.folded)
|
||||
|
||||
isFolded = col => {
|
||||
const folded = this.getState()
|
||||
return folded[col.id] === true
|
||||
}
|
||||
|
||||
foldingHandler = col => {
|
||||
if (!col || !col.id) return
|
||||
|
||||
const { onFoldChange } = this.props
|
||||
const folded = this.getState()
|
||||
const { id } = col
|
||||
|
||||
const newFold = Object.assign({}, folded)
|
||||
newFold[id] = !newFold[id]
|
||||
|
||||
// Remove the Resized if have
|
||||
this.removeResized(col)
|
||||
|
||||
if (onFoldChange) onFoldChange(newFold)
|
||||
else {
|
||||
this.setState(previous => ({ folded: newFold }))
|
||||
}
|
||||
}
|
||||
|
||||
foldableHeaderRender = cell => {
|
||||
const { FoldButtonComponent, FoldIconComponent } = this.props
|
||||
const { column } = cell
|
||||
const collapsed = this.isFolded(column)
|
||||
const icon = React.createElement(FoldIconComponent, { collapsed })
|
||||
const onClick = () => this.foldingHandler(column)
|
||||
|
||||
return React.createElement(FoldButtonComponent, {
|
||||
header: column.original_Header,
|
||||
collapsed,
|
||||
icon,
|
||||
onClick,
|
||||
})
|
||||
}
|
||||
|
||||
applyFoldableForColumn = column => {
|
||||
const collapsed = this.isFolded(column)
|
||||
const { FoldedColumn } = this.props
|
||||
|
||||
// Handle Column Header
|
||||
if (column.columns) {
|
||||
if (collapsed) {
|
||||
column.columns = [FoldedColumn]
|
||||
column.width = FoldedColumn.width
|
||||
column.style = FoldedColumn.style
|
||||
} else this.restoreToOriginal(column)
|
||||
}
|
||||
// Handle Normal Column.
|
||||
else if (collapsed) column = Object.assign(column, FoldedColumn)
|
||||
else {
|
||||
this.restoreToOriginal(column)
|
||||
}
|
||||
}
|
||||
|
||||
applyFoldableForColumns = columns =>
|
||||
columns.map((col, index) => {
|
||||
if (!col.foldable) return col
|
||||
|
||||
// If col don't have id then generate id based on index
|
||||
if (!col.id) col.id = `col_${index}`
|
||||
|
||||
this.copyOriginals(col)
|
||||
// Replace current header with internal header render.
|
||||
col.Header = c => this.foldableHeaderRender(c)
|
||||
// apply foldable
|
||||
this.applyFoldableForColumn(col)
|
||||
|
||||
// return the new column out
|
||||
return col
|
||||
})
|
||||
|
||||
render() {
|
||||
const {
|
||||
columns: originalCols,
|
||||
FoldButtonComponent,
|
||||
FoldIconComponent,
|
||||
FoldedColumn,
|
||||
...rest
|
||||
} = this.props
|
||||
const columns = this.applyFoldableForColumns([...originalCols])
|
||||
|
||||
const extra = {
|
||||
columns,
|
||||
onResizedChange: this.onResizedChange,
|
||||
resized: this.state.resized,
|
||||
}
|
||||
|
||||
return <ReactTable {...rest} {...extra} ref={r => (this.wrappedInstance = r)} />
|
||||
}
|
||||
}
|
||||
|
||||
wrapper.displayName = 'RTFoldableTable'
|
||||
wrapper.defaultProps = {
|
||||
FoldIconComponent: defaultFoldIconComponent,
|
||||
FoldButtonComponent: defaultFoldButtonComponent,
|
||||
foldableOriginalKey: 'original_',
|
||||
FoldedColumn: {
|
||||
Cell: c => '',
|
||||
width: 30,
|
||||
sortable: false,
|
||||
resizable: false,
|
||||
filterable: false,
|
||||
},
|
||||
}
|
||||
|
||||
return wrapper
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" ?><!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'><svg height="512px" id="Layer_1" style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M327.3,98.9l-2.1,1.8l-156.5,136c-5.3,4.6-8.6,11.5-8.6,19.2c0,7.7,3.4,14.6,8.6,19.2L324.9,411l2.6,2.3 c2.5,1.7,5.5,2.7,8.7,2.7c8.7,0,15.8-7.4,15.8-16.6h0V112.6h0c0-9.2-7.1-16.6-15.8-16.6C332.9,96,329.8,97.1,327.3,98.9z"/></svg>
|
||||
|
After Width: | Height: | Size: 583 B |
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" ?><!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'><svg height="512px" id="Layer_1" style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M184.7,413.1l2.1-1.8l156.5-136c5.3-4.6,8.6-11.5,8.6-19.2c0-7.7-3.4-14.6-8.6-19.2L187.1,101l-2.6-2.3 C182,97,179,96,175.8,96c-8.7,0-15.8,7.4-15.8,16.6h0v286.8h0c0,9.2,7.1,16.6,15.8,16.6C179.1,416,182.2,414.9,184.7,413.1z"/></svg>
|
||||
|
After Width: | Height: | Size: 585 B |
@@ -1,111 +1,119 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import React from 'react';
|
||||
import React from 'react'
|
||||
|
||||
const defaultSelectInputComponent = (props) => {
|
||||
const defaultSelectInputComponent = props => {
|
||||
return (
|
||||
<input
|
||||
type={props.selectType || 'checkbox'}
|
||||
checked={props.checked}
|
||||
onClick={(e)=>{
|
||||
const { shiftKey } = e;
|
||||
e.stopPropagation();
|
||||
props.onClick(props.id, shiftKey, props.row);
|
||||
}}
|
||||
onChange={()=>{}}
|
||||
<input
|
||||
type={props.selectType || 'checkbox'}
|
||||
aria-label={`${props.checked ? 'Un-select':'Select'} row with id:${props.id}` }
|
||||
checked={props.checked}
|
||||
id={props.id}
|
||||
onClick={e => {
|
||||
const { shiftKey } = e
|
||||
e.stopPropagation()
|
||||
props.onClick(props.id, shiftKey, props.row)
|
||||
}}
|
||||
onChange={() => {}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default (Component) => {
|
||||
|
||||
export default (Component, options) => {
|
||||
const wrapper = class RTSelectTable extends React.Component {
|
||||
|
||||
constructor(props)
|
||||
{
|
||||
super(props);
|
||||
constructor(props) {
|
||||
super(props)
|
||||
}
|
||||
|
||||
rowSelector(row) {
|
||||
if(!row || !row.hasOwnProperty(this.props.keyField)) return null;
|
||||
const { toggleSelection, selectType, keyField } = this.props;
|
||||
const checked = this.props.isSelected(row[this.props.keyField]);
|
||||
const inputProps =
|
||||
{
|
||||
if (!row || !row.hasOwnProperty(this.props.keyField)) return null
|
||||
const { toggleSelection, selectType, keyField } = this.props
|
||||
const checked = this.props.isSelected(row[this.props.keyField])
|
||||
const inputProps = {
|
||||
checked,
|
||||
onClick: toggleSelection,
|
||||
selectType,
|
||||
id: row[keyField],
|
||||
row,
|
||||
id: `select-${row[keyField]}`
|
||||
}
|
||||
return React.createElement(this.props.SelectInputComponent,inputProps);
|
||||
return React.createElement(this.props.SelectInputComponent, inputProps)
|
||||
}
|
||||
|
||||
headSelector(row) {
|
||||
const { selectType } = this.props;
|
||||
if (selectType === 'radio') return null;
|
||||
|
||||
const { toggleAll, selectAll: checked, SelectAllInputComponent, } = this.props;
|
||||
const inputProps =
|
||||
{
|
||||
const { selectType } = this.props
|
||||
if (selectType === 'radio') return null
|
||||
|
||||
const { toggleAll, selectAll: checked, SelectAllInputComponent } = this.props
|
||||
const inputProps = {
|
||||
checked,
|
||||
onClick: toggleAll,
|
||||
selectType,
|
||||
id: 'select-all'
|
||||
}
|
||||
|
||||
return React.createElement(SelectAllInputComponent,inputProps);
|
||||
|
||||
return React.createElement(SelectAllInputComponent, inputProps)
|
||||
}
|
||||
|
||||
|
||||
// this is so we can expose the underlying ReactTable to get at the sortedData for selectAll
|
||||
getWrappedInstance() {
|
||||
if (!this.wrappedInstance) console.warn('RTSelectTable - No wrapped instance');
|
||||
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance();
|
||||
if (!this.wrappedInstance) console.warn('RTSelectTable - No wrapped instance')
|
||||
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance()
|
||||
else return this.wrappedInstance
|
||||
}
|
||||
|
||||
render()
|
||||
{
|
||||
const {
|
||||
columns:originalCols, isSelected, toggleSelection, toggleAll, keyField, selectAll,
|
||||
selectType, SelectAllInputComponent, SelectInputComponent,
|
||||
...rest
|
||||
} = this.props;
|
||||
render() {
|
||||
const {
|
||||
columns: originalCols,
|
||||
isSelected,
|
||||
toggleSelection,
|
||||
toggleAll,
|
||||
keyField,
|
||||
selectAll,
|
||||
selectType,
|
||||
selectWidth,
|
||||
SelectAllInputComponent,
|
||||
SelectInputComponent,
|
||||
...rest
|
||||
} = this.props
|
||||
const select = {
|
||||
id: '_selector',
|
||||
accessor: ()=>'x', // this value is not important
|
||||
accessor: () => 'x', // this value is not important
|
||||
Header: this.headSelector.bind(this),
|
||||
Cell: (ci) => { return this.rowSelector.bind(this)(ci.original); },
|
||||
width: 30,
|
||||
Cell: ci => {
|
||||
return this.rowSelector.bind(this)(ci.original)
|
||||
},
|
||||
width: selectWidth || 30,
|
||||
filterable: false,
|
||||
sortable: false,
|
||||
resizable: false,
|
||||
style: { textAlign: 'center' },
|
||||
}
|
||||
const columns = [
|
||||
select,
|
||||
...originalCols,
|
||||
];
|
||||
|
||||
const columns = (options !== undefined && options.floatingLeft === true) ? [...originalCols, select] : [select, ...originalCols]
|
||||
const extra = {
|
||||
columns,
|
||||
};
|
||||
return (
|
||||
<Component {...rest} {...extra} ref={(r)=>this.wrappedInstance=r}/>
|
||||
)
|
||||
}
|
||||
return <Component {...rest} {...extra} ref={r => (this.wrappedInstance = r)} />
|
||||
}
|
||||
}
|
||||
|
||||
wrapper.displayName = 'RTSelectTable';
|
||||
wrapper.defaultProps =
|
||||
{
|
||||
wrapper.displayName = 'RTSelectTable'
|
||||
wrapper.defaultProps = {
|
||||
keyField: '_id',
|
||||
isSelected: (key)=>{ console.log('No isSelected handler provided:',{key})},
|
||||
isSelected: key => {
|
||||
console.log('No isSelected handler provided:', { key })
|
||||
},
|
||||
selectAll: false,
|
||||
toggleSelection: (key, shift, row)=>{ console.log('No toggleSelection handler provided:', { key, shift, row }) },
|
||||
toggleAll: () => { console.log('No toggleAll handler provided.') },
|
||||
selectType: 'check',
|
||||
toggleSelection: (key, shift, row) => {
|
||||
console.log('No toggleSelection handler provided:', { key, shift, row })
|
||||
},
|
||||
toggleAll: () => {
|
||||
console.log('No toggleAll handler provided.')
|
||||
},
|
||||
selectType: 'checkbox',
|
||||
SelectInputComponent: defaultSelectInputComponent,
|
||||
SelectAllInputComponent: defaultSelectInputComponent,
|
||||
}
|
||||
|
||||
return wrapper;
|
||||
|
||||
return wrapper
|
||||
}
|
||||
|
||||
+44
-45
@@ -2,79 +2,78 @@
|
||||
|
||||
import React from 'react'
|
||||
|
||||
export default (Component) => {
|
||||
export default Component => {
|
||||
const wrapper = class RTTreeTable extends React.Component {
|
||||
|
||||
constructor(props)
|
||||
{
|
||||
super(props);
|
||||
this.getWrappedInstance.bind(this);
|
||||
this.TrComponent.bind(this);
|
||||
this.getTrProps.bind(this);
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.getWrappedInstance.bind(this)
|
||||
this.TrComponent.bind(this)
|
||||
this.getTrProps.bind(this)
|
||||
}
|
||||
|
||||
// this is so we can expose the underlying ReactTable to get at the sortedData for selectAll
|
||||
getWrappedInstance = () => {
|
||||
if (!this.wrappedInstance) console.warn('RTTreeTable - No wrapped instance');
|
||||
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance();
|
||||
if (!this.wrappedInstance) console.warn('RTTreeTable - No wrapped instance')
|
||||
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance()
|
||||
else return this.wrappedInstance
|
||||
}
|
||||
|
||||
TrComponent = (props) => {
|
||||
const {
|
||||
ri,
|
||||
...rest
|
||||
} = props;
|
||||
if(ri && ri.groupedByPivot) {
|
||||
const cell = {...props.children[ri.level]};
|
||||
|
||||
cell.props.style.flex = 'unset';
|
||||
cell.props.style.width = '100%';
|
||||
cell.props.style.maxWidth = 'unset';
|
||||
cell.props.style.paddingLeft = `${this.props.treeTableIndent*ri.level}px`;
|
||||
TrComponent = props => {
|
||||
const { ri, ...rest } = props
|
||||
if (ri && ri.groupedByPivot) {
|
||||
const cell = { ...props.children[ri.level] }
|
||||
|
||||
cell.props.style.flex = 'unset'
|
||||
cell.props.style.width = '100%'
|
||||
cell.props.style.maxWidth = 'unset'
|
||||
cell.props.style.paddingLeft = `${this.props.treeTableIndent * ri.level}px`
|
||||
// cell.props.style.backgroundColor = '#DDD';
|
||||
cell.props.style.borderBottom = '1px solid rgba(128,128,128,0.2)';
|
||||
|
||||
return <div className={`rt-tr ${rest.className}`} style={rest.style}>{cell}</div>;
|
||||
cell.props.style.borderBottom = '1px solid rgba(128,128,128,0.2)'
|
||||
|
||||
return (
|
||||
<div className={`rt-tr ${rest.className}`} role="row" style={rest.style}>
|
||||
{cell}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return <Component.defaultProps.TrComponent {...rest} />;
|
||||
return <Component.defaultProps.TrComponent {...rest} />
|
||||
}
|
||||
|
||||
getTrProps = (state,ri,ci,instance) => {
|
||||
return {ri};
|
||||
getTrProps = (state, ri, ci, instance) => {
|
||||
return { ri }
|
||||
}
|
||||
|
||||
render() {
|
||||
const { columns, treeTableIndent, ...rest } = this.props;
|
||||
const { TrComponent, getTrProps } = this;
|
||||
const { columns, treeTableIndent, ...rest } = this.props
|
||||
const { TrComponent, getTrProps } = this
|
||||
const extra = {
|
||||
columns: columns.map((col)=>{
|
||||
let column = col;
|
||||
if(rest.pivotBy && rest.pivotBy.includes(col.accessor))
|
||||
{
|
||||
columns: columns.map(col => {
|
||||
let column = col
|
||||
if (rest.pivotBy && (rest.pivotBy.includes(col.accessor) || rest.pivotBy.includes(col.id))) {
|
||||
column = {
|
||||
id: col.id,
|
||||
accessor: col.accessor,
|
||||
width: `${treeTableIndent}px`,
|
||||
show: false,
|
||||
Header: '',
|
||||
Expander: col.Expander,
|
||||
PivotValue: col.PivotValue,
|
||||
Pivot: col.Pivot,
|
||||
}
|
||||
}
|
||||
return column;
|
||||
return column
|
||||
}),
|
||||
TrComponent,
|
||||
getTrProps,
|
||||
};
|
||||
|
||||
return (
|
||||
<Component {...rest} {...extra} ref={ r => this.wrappedInstance=r }/>
|
||||
)
|
||||
}
|
||||
|
||||
return <Component {...rest} {...extra} ref={r => (this.wrappedInstance = r)} />
|
||||
}
|
||||
}
|
||||
wrapper.displayName = 'RTTreeTable';
|
||||
wrapper.defaultProps =
|
||||
{
|
||||
wrapper.displayName = 'RTTreeTable'
|
||||
wrapper.defaultProps = {
|
||||
treeTableIndent: 10,
|
||||
}
|
||||
|
||||
return wrapper;
|
||||
|
||||
return wrapper
|
||||
}
|
||||
|
||||
+138
-277
@@ -34,7 +34,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
this.resizeColumnMoving = this.resizeColumnMoving.bind(this)
|
||||
|
||||
this.state = {
|
||||
page: 0,
|
||||
page: props.defaultPage,
|
||||
pageSize: props.defaultPageSize,
|
||||
sorted: props.defaultSorted,
|
||||
expanded: props.defaultExpanded,
|
||||
@@ -142,7 +142,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
const hasColumnFooter = allVisibleColumns.some(d => d.Footer)
|
||||
const hasFilters = filterable || allVisibleColumns.some(d => d.filterable)
|
||||
|
||||
const recurseRowsViewIndex = (rows, path = [], index = -1) => ([
|
||||
const recurseRowsViewIndex = (rows, path = [], index = -1) => [
|
||||
rows.map((row, i) => {
|
||||
index += 1
|
||||
const rowWithViewIndex = {
|
||||
@@ -154,14 +154,14 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
[rowWithViewIndex[subRowsKey], index] = recurseRowsViewIndex(
|
||||
rowWithViewIndex[subRowsKey],
|
||||
newPath,
|
||||
index,
|
||||
index
|
||||
)
|
||||
}
|
||||
return rowWithViewIndex
|
||||
}),
|
||||
index,
|
||||
])
|
||||
;[pageRows] = recurseRowsViewIndex(pageRows)
|
||||
];
|
||||
[pageRows] = recurseRowsViewIndex(pageRows)
|
||||
|
||||
const canPrevious = page > 0
|
||||
const canNext = page + 1 < pages
|
||||
@@ -170,7 +170,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
allVisibleColumns.map(d => {
|
||||
const resizedColumn = resized.find(x => x.id === d.id) || {}
|
||||
return _.getFirstDefined(resizedColumn.value, d.width, d.minWidth)
|
||||
}),
|
||||
})
|
||||
)
|
||||
|
||||
let rowIndex = -1
|
||||
@@ -188,44 +188,31 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
rowMinWidth,
|
||||
}
|
||||
|
||||
const rootProps = _.splitProps(
|
||||
getProps(finalState, undefined, undefined, this),
|
||||
)
|
||||
const tableProps = _.splitProps(
|
||||
getTableProps(finalState, undefined, undefined, this),
|
||||
)
|
||||
const tBodyProps = _.splitProps(
|
||||
getTbodyProps(finalState, undefined, undefined, this),
|
||||
)
|
||||
const rootProps = _.splitProps(getProps(finalState, undefined, undefined, this))
|
||||
const tableProps = _.splitProps(getTableProps(finalState, undefined, undefined, this))
|
||||
const tBodyProps = _.splitProps(getTbodyProps(finalState, undefined, undefined, this))
|
||||
const loadingProps = getLoadingProps(finalState, undefined, undefined, this)
|
||||
const noDataProps = getNoDataProps(finalState, undefined, undefined, this)
|
||||
|
||||
// Visual Components
|
||||
|
||||
const makeHeaderGroup = (column, i) => {
|
||||
const resizedValue = col =>
|
||||
(resized.find(x => x.id === col.id) || {}).value
|
||||
const resizedValue = col => (resized.find(x => x.id === col.id) || {}).value
|
||||
const flex = _.sum(
|
||||
column.columns.map(
|
||||
col => (col.width || resizedValue(col) ? 0 : col.minWidth),
|
||||
),
|
||||
column.columns.map(col => (col.width || resizedValue(col) ? 0 : col.minWidth))
|
||||
)
|
||||
const width = _.sum(
|
||||
column.columns.map(col =>
|
||||
_.getFirstDefined(resizedValue(col), col.width, col.minWidth),
|
||||
),
|
||||
column.columns.map(col => _.getFirstDefined(resizedValue(col), col.width, col.minWidth))
|
||||
)
|
||||
const maxWidth = _.sum(
|
||||
column.columns.map(col =>
|
||||
_.getFirstDefined(resizedValue(col), col.width, col.maxWidth),
|
||||
),
|
||||
column.columns.map(col => _.getFirstDefined(resizedValue(col), col.width, col.maxWidth))
|
||||
)
|
||||
|
||||
const theadGroupThProps = _.splitProps(
|
||||
getTheadGroupThProps(finalState, undefined, column, this),
|
||||
getTheadGroupThProps(finalState, undefined, column, this)
|
||||
)
|
||||
const columnHeaderProps = _.splitProps(
|
||||
column.getHeaderProps(finalState, undefined, column, this),
|
||||
column.getHeaderProps(finalState, undefined, column, this)
|
||||
)
|
||||
|
||||
const classes = [
|
||||
@@ -271,10 +258,10 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
|
||||
const makeHeaderGroups = () => {
|
||||
const theadGroupProps = _.splitProps(
|
||||
getTheadGroupProps(finalState, undefined, undefined, this),
|
||||
getTheadGroupProps(finalState, undefined, undefined, this)
|
||||
)
|
||||
const theadGroupTrProps = _.splitProps(
|
||||
getTheadGroupTrProps(finalState, undefined, undefined, this),
|
||||
getTheadGroupTrProps(finalState, undefined, undefined, this)
|
||||
)
|
||||
return (
|
||||
<TheadComponent
|
||||
@@ -299,30 +286,15 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
const makeHeader = (column, i) => {
|
||||
const resizedCol = resized.find(x => x.id === column.id) || {}
|
||||
const sort = sorted.find(d => d.id === column.id)
|
||||
const show =
|
||||
typeof column.show === 'function' ? column.show() : column.show
|
||||
const width = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.minWidth,
|
||||
)
|
||||
const maxWidth = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.maxWidth,
|
||||
)
|
||||
const theadThProps = _.splitProps(
|
||||
getTheadThProps(finalState, undefined, column, this),
|
||||
)
|
||||
const show = typeof column.show === 'function' ? column.show() : column.show
|
||||
const width = _.getFirstDefined(resizedCol.value, column.width, column.minWidth)
|
||||
const maxWidth = _.getFirstDefined(resizedCol.value, column.width, column.maxWidth)
|
||||
const theadThProps = _.splitProps(getTheadThProps(finalState, undefined, column, this))
|
||||
const columnHeaderProps = _.splitProps(
|
||||
column.getHeaderProps(finalState, undefined, column, this),
|
||||
column.getHeaderProps(finalState, undefined, column, this)
|
||||
)
|
||||
|
||||
const classes = [
|
||||
column.headerClassName,
|
||||
theadThProps.className,
|
||||
columnHeaderProps.className,
|
||||
]
|
||||
const classes = [column.headerClassName, theadThProps.className, columnHeaderProps.className]
|
||||
|
||||
const styles = {
|
||||
...column.headerStyle,
|
||||
@@ -336,13 +308,13 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
}
|
||||
|
||||
const isResizable = _.getFirstDefined(column.resizable, resizable, false)
|
||||
const resizer = isResizable
|
||||
? (<ResizerComponent
|
||||
const resizer = isResizable ? (
|
||||
<ResizerComponent
|
||||
onMouseDown={e => this.resizeColumnStart(e, column, false)}
|
||||
onTouchStart={e => this.resizeColumnStart(e, column, true)}
|
||||
{...getResizerProps('finalState', undefined, column, this)}
|
||||
/>)
|
||||
: null
|
||||
/>
|
||||
) : null
|
||||
|
||||
const isSortable = _.getFirstDefined(column.sortable, sortable, false)
|
||||
|
||||
@@ -355,9 +327,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
sort ? (sort.desc ? '-sort-desc' : '-sort-asc') : '',
|
||||
isSortable && '-cursor-pointer',
|
||||
!show && '-hidden',
|
||||
pivotBy &&
|
||||
pivotBy.slice(0, -1).includes(column.id) &&
|
||||
'rt-header-pivot',
|
||||
pivotBy && pivotBy.slice(0, -1).includes(column.id) && 'rt-header-pivot'
|
||||
)}
|
||||
style={{
|
||||
...styles,
|
||||
@@ -382,12 +352,8 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
}
|
||||
|
||||
const makeHeaders = () => {
|
||||
const theadProps = _.splitProps(
|
||||
getTheadProps(finalState, undefined, undefined, this),
|
||||
)
|
||||
const theadTrProps = _.splitProps(
|
||||
getTheadTrProps(finalState, undefined, undefined, this),
|
||||
)
|
||||
const theadProps = _.splitProps(getTheadProps(finalState, undefined, undefined, this))
|
||||
const theadTrProps = _.splitProps(getTheadTrProps(finalState, undefined, undefined, this))
|
||||
return (
|
||||
<TheadComponent
|
||||
className={classnames('-header', theadProps.className)}
|
||||
@@ -410,21 +376,13 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
|
||||
const makeFilter = (column, i) => {
|
||||
const resizedCol = resized.find(x => x.id === column.id) || {}
|
||||
const width = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.minWidth,
|
||||
)
|
||||
const maxWidth = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.maxWidth,
|
||||
)
|
||||
const width = _.getFirstDefined(resizedCol.value, column.width, column.minWidth)
|
||||
const maxWidth = _.getFirstDefined(resizedCol.value, column.width, column.maxWidth)
|
||||
const theadFilterThProps = _.splitProps(
|
||||
getTheadFilterThProps(finalState, undefined, column, this),
|
||||
getTheadFilterThProps(finalState, undefined, column, this)
|
||||
)
|
||||
const columnHeaderProps = _.splitProps(
|
||||
column.getHeaderProps(finalState, undefined, column, this),
|
||||
column.getHeaderProps(finalState, undefined, column, this)
|
||||
)
|
||||
|
||||
const classes = [
|
||||
@@ -448,11 +406,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
|
||||
const ResolvedFilterComponent = column.Filter || FilterComponent
|
||||
|
||||
const isFilterable = _.getFirstDefined(
|
||||
column.filterable,
|
||||
filterable,
|
||||
false,
|
||||
)
|
||||
const isFilterable = _.getFirstDefined(column.filterable, filterable, false)
|
||||
|
||||
return (
|
||||
<ThComponent
|
||||
@@ -468,14 +422,14 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
>
|
||||
{isFilterable
|
||||
? _.normalizeComponent(
|
||||
ResolvedFilterComponent,
|
||||
{
|
||||
column,
|
||||
filter,
|
||||
onChange: value => this.filterColumn(column, value),
|
||||
},
|
||||
defaultProps.column.Filter,
|
||||
)
|
||||
ResolvedFilterComponent,
|
||||
{
|
||||
column,
|
||||
filter,
|
||||
onChange: value => this.filterColumn(column, value),
|
||||
},
|
||||
defaultProps.column.Filter
|
||||
)
|
||||
: null}
|
||||
</ThComponent>
|
||||
)
|
||||
@@ -483,10 +437,10 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
|
||||
const makeFilters = () => {
|
||||
const theadFilterProps = _.splitProps(
|
||||
getTheadFilterProps(finalState, undefined, undefined, this),
|
||||
getTheadFilterProps(finalState, undefined, undefined, this)
|
||||
)
|
||||
const theadFilterTrProps = _.splitProps(
|
||||
getTheadFilterTrProps(finalState, undefined, undefined, this),
|
||||
getTheadFilterTrProps(finalState, undefined, undefined, this)
|
||||
)
|
||||
return (
|
||||
<TheadComponent
|
||||
@@ -513,7 +467,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
original: row[originalKey],
|
||||
row,
|
||||
index: row[indexKey],
|
||||
viewIndex: rowIndex += 1,
|
||||
viewIndex: (rowIndex += 1),
|
||||
pageSize,
|
||||
page,
|
||||
level: path.length,
|
||||
@@ -524,45 +478,23 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
}
|
||||
const isExpanded = _.get(expanded, rowInfo.nestingPath)
|
||||
const trGroupProps = getTrGroupProps(finalState, rowInfo, undefined, this)
|
||||
const trProps = _.splitProps(
|
||||
getTrProps(finalState, rowInfo, undefined, this),
|
||||
)
|
||||
const trProps = _.splitProps(getTrProps(finalState, rowInfo, undefined, this))
|
||||
return (
|
||||
<TrGroupComponent key={rowInfo.nestingPath.join('_')} {...trGroupProps}>
|
||||
<TrComponent
|
||||
className={classnames(
|
||||
trProps.className,
|
||||
row._viewIndex % 2 ? '-even' : '-odd',
|
||||
)}
|
||||
className={classnames(trProps.className, row._viewIndex % 2 ? '-even' : '-odd')}
|
||||
style={trProps.style}
|
||||
{...trProps.rest}
|
||||
>
|
||||
{allVisibleColumns.map((column, i2) => {
|
||||
const resizedCol = resized.find(x => x.id === column.id) || {}
|
||||
const show =
|
||||
typeof column.show === 'function' ? column.show() : column.show
|
||||
const width = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.minWidth,
|
||||
)
|
||||
const maxWidth = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.maxWidth,
|
||||
)
|
||||
const tdProps = _.splitProps(
|
||||
getTdProps(finalState, rowInfo, column, this),
|
||||
)
|
||||
const columnProps = _.splitProps(
|
||||
column.getProps(finalState, rowInfo, column, this),
|
||||
)
|
||||
const show = typeof column.show === 'function' ? column.show() : column.show
|
||||
const width = _.getFirstDefined(resizedCol.value, column.width, column.minWidth)
|
||||
const maxWidth = _.getFirstDefined(resizedCol.value, column.width, column.maxWidth)
|
||||
const tdProps = _.splitProps(getTdProps(finalState, rowInfo, column, this))
|
||||
const columnProps = _.splitProps(column.getProps(finalState, rowInfo, column, this))
|
||||
|
||||
const classes = [
|
||||
tdProps.className,
|
||||
column.className,
|
||||
columnProps.className,
|
||||
]
|
||||
const classes = [tdProps.className, column.className, columnProps.className]
|
||||
|
||||
const styles = {
|
||||
...tdProps.style,
|
||||
@@ -605,28 +537,20 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
{
|
||||
expanded: newExpanded,
|
||||
},
|
||||
() => (
|
||||
() =>
|
||||
onExpandedChange &&
|
||||
onExpandedChange(newExpanded, cellInfo.nestingPath, e)
|
||||
),
|
||||
onExpandedChange(newExpanded, cellInfo.nestingPath, e, cellInfo)
|
||||
)
|
||||
}
|
||||
|
||||
// Default to a standard cell
|
||||
let resolvedCell = _.normalizeComponent(
|
||||
column.Cell,
|
||||
cellInfo,
|
||||
value,
|
||||
)
|
||||
let resolvedCell = _.normalizeComponent(column.Cell, cellInfo, value)
|
||||
|
||||
// Resolve Renderers
|
||||
const ResolvedAggregatedComponent =
|
||||
column.Aggregated ||
|
||||
(!column.aggregate ? AggregatedComponent : column.Cell)
|
||||
const ResolvedExpanderComponent =
|
||||
column.Expander || ExpanderComponent
|
||||
const ResolvedPivotValueComponent =
|
||||
column.PivotValue || PivotValueComponent
|
||||
column.Aggregated || (!column.aggregate ? AggregatedComponent : column.Cell)
|
||||
const ResolvedExpanderComponent = column.Expander || ExpanderComponent
|
||||
const ResolvedPivotValueComponent = column.PivotValue || PivotValueComponent
|
||||
const DefaultResolvedPivotComponent =
|
||||
PivotComponent ||
|
||||
(props => (
|
||||
@@ -635,8 +559,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
<ResolvedPivotValueComponent {...props} />
|
||||
</div>
|
||||
))
|
||||
const ResolvedPivotComponent =
|
||||
column.Pivot || DefaultResolvedPivotComponent
|
||||
const ResolvedPivotComponent = column.Pivot || DefaultResolvedPivotComponent
|
||||
|
||||
// Is this cell expandable?
|
||||
if (cellInfo.pivoted || cellInfo.expander) {
|
||||
@@ -652,12 +575,11 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
|
||||
if (cellInfo.pivoted) {
|
||||
// Is this column a branch?
|
||||
isBranch =
|
||||
rowInfo.row[pivotIDKey] === column.id && cellInfo.subRows
|
||||
isBranch = rowInfo.row[pivotIDKey] === column.id && cellInfo.subRows
|
||||
// Should this column be blank?
|
||||
isPreview =
|
||||
pivotBy.indexOf(column.id) >
|
||||
pivotBy.indexOf(rowInfo.row[pivotIDKey]) && cellInfo.subRows
|
||||
pivotBy.indexOf(column.id) > pivotBy.indexOf(rowInfo.row[pivotIDKey]) &&
|
||||
cellInfo.subRows
|
||||
// Pivot Cell Render Override
|
||||
if (isBranch) {
|
||||
// isPivot
|
||||
@@ -667,31 +589,23 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
...cellInfo,
|
||||
value: row[pivotValKey],
|
||||
},
|
||||
row[pivotValKey],
|
||||
row[pivotValKey]
|
||||
)
|
||||
} else if (isPreview) {
|
||||
// Show the pivot preview
|
||||
resolvedCell = _.normalizeComponent(
|
||||
ResolvedAggregatedComponent,
|
||||
cellInfo,
|
||||
value,
|
||||
)
|
||||
resolvedCell = _.normalizeComponent(ResolvedAggregatedComponent, cellInfo, value)
|
||||
} else {
|
||||
resolvedCell = null
|
||||
}
|
||||
} else if (cellInfo.aggregated) {
|
||||
resolvedCell = _.normalizeComponent(
|
||||
ResolvedAggregatedComponent,
|
||||
cellInfo,
|
||||
value,
|
||||
)
|
||||
resolvedCell = _.normalizeComponent(ResolvedAggregatedComponent, cellInfo, value)
|
||||
}
|
||||
|
||||
if (cellInfo.expander) {
|
||||
resolvedCell = _.normalizeComponent(
|
||||
ResolvedExpanderComponent,
|
||||
cellInfo,
|
||||
row[pivotValKey],
|
||||
row[pivotValKey]
|
||||
)
|
||||
if (pivotBy) {
|
||||
if (cellInfo.groupedByPivot) {
|
||||
@@ -703,9 +617,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedOnExpanderClick = useOnExpanderClick
|
||||
? onExpanderClick
|
||||
: () => {}
|
||||
const resolvedOnExpanderClick = useOnExpanderClick ? onExpanderClick : () => {}
|
||||
|
||||
// If there are multiple onClick events, make sure they don't
|
||||
// override eachother. This should maybe be expanded to handle all
|
||||
@@ -733,9 +645,9 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
key={`${i2}-${column.id}`}
|
||||
className={classnames(
|
||||
classes,
|
||||
!show && 'hidden',
|
||||
!cellInfo.expandable && !show && 'hidden',
|
||||
cellInfo.expandable && 'rt-expandable',
|
||||
(isBranch || isPreview) && 'rt-pivot',
|
||||
(isBranch || isPreview) && 'rt-pivot'
|
||||
)}
|
||||
style={{
|
||||
...styles,
|
||||
@@ -754,44 +666,29 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
</TrComponent>
|
||||
{rowInfo.subRows &&
|
||||
isExpanded &&
|
||||
rowInfo.subRows.map((d, i) =>
|
||||
makePageRow(d, i, rowInfo.nestingPath),
|
||||
)}
|
||||
rowInfo.subRows.map((d, i) => makePageRow(d, i, rowInfo.nestingPath))}
|
||||
{SubComponent &&
|
||||
!rowInfo.subRows &&
|
||||
isExpanded &&
|
||||
SubComponent(rowInfo)}
|
||||
SubComponent(rowInfo, () => {
|
||||
const newExpanded = _.clone(expanded)
|
||||
|
||||
_.set(newExpanded, rowInfo.nestingPath, false)
|
||||
})}
|
||||
</TrGroupComponent>
|
||||
)
|
||||
}
|
||||
|
||||
const makePadColumn = (column, i) => {
|
||||
const resizedCol = resized.find(x => x.id === column.id) || {}
|
||||
const show =
|
||||
typeof column.show === 'function' ? column.show() : column.show
|
||||
const width = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.minWidth,
|
||||
)
|
||||
const show = typeof column.show === 'function' ? column.show() : column.show
|
||||
const width = _.getFirstDefined(resizedCol.value, column.width, column.minWidth)
|
||||
const flex = width
|
||||
const maxWidth = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.maxWidth,
|
||||
)
|
||||
const tdProps = _.splitProps(
|
||||
getTdProps(finalState, undefined, column, this),
|
||||
)
|
||||
const columnProps = _.splitProps(
|
||||
column.getProps(finalState, undefined, column, this),
|
||||
)
|
||||
const maxWidth = _.getFirstDefined(resizedCol.value, column.width, column.maxWidth)
|
||||
const tdProps = _.splitProps(getTdProps(finalState, undefined, column, this))
|
||||
const columnProps = _.splitProps(column.getProps(finalState, undefined, column, this))
|
||||
|
||||
const classes = [
|
||||
tdProps.className,
|
||||
column.className,
|
||||
columnProps.className,
|
||||
]
|
||||
const classes = [tdProps.className, column.className, columnProps.className]
|
||||
|
||||
const styles = {
|
||||
...tdProps.style,
|
||||
@@ -817,22 +714,15 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
}
|
||||
|
||||
const makePadRow = (row, i) => {
|
||||
const trGroupProps = getTrGroupProps(
|
||||
finalState,
|
||||
undefined,
|
||||
undefined,
|
||||
this,
|
||||
)
|
||||
const trProps = _.splitProps(
|
||||
getTrProps(finalState, undefined, undefined, this),
|
||||
)
|
||||
const trGroupProps = getTrGroupProps(finalState, undefined, undefined, this)
|
||||
const trProps = _.splitProps(getTrProps(finalState, undefined, undefined, this))
|
||||
return (
|
||||
<TrGroupComponent key={i} {...trGroupProps}>
|
||||
<TrGroupComponent key={`pad-${i}`} {...trGroupProps}>
|
||||
<TrComponent
|
||||
className={classnames(
|
||||
'-padRow',
|
||||
(pageRows.length + i) % 2 ? '-even' : '-odd',
|
||||
trProps.className,
|
||||
trProps.className
|
||||
)}
|
||||
style={trProps.style || {}}
|
||||
>
|
||||
@@ -844,26 +734,13 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
|
||||
const makeColumnFooter = (column, i) => {
|
||||
const resizedCol = resized.find(x => x.id === column.id) || {}
|
||||
const show =
|
||||
typeof column.show === 'function' ? column.show() : column.show
|
||||
const width = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.minWidth,
|
||||
)
|
||||
const maxWidth = _.getFirstDefined(
|
||||
resizedCol.value,
|
||||
column.width,
|
||||
column.maxWidth,
|
||||
)
|
||||
const tFootTdProps = _.splitProps(
|
||||
getTfootTdProps(finalState, undefined, undefined, this),
|
||||
)
|
||||
const columnProps = _.splitProps(
|
||||
column.getProps(finalState, undefined, column, this),
|
||||
)
|
||||
const show = typeof column.show === 'function' ? column.show() : column.show
|
||||
const width = _.getFirstDefined(resizedCol.value, column.width, column.minWidth)
|
||||
const maxWidth = _.getFirstDefined(resizedCol.value, column.width, column.maxWidth)
|
||||
const tFootTdProps = _.splitProps(getTfootTdProps(finalState, undefined, column, this))
|
||||
const columnProps = _.splitProps(column.getProps(finalState, undefined, column, this))
|
||||
const columnFooterProps = _.splitProps(
|
||||
column.getFooterProps(finalState, undefined, column, this),
|
||||
column.getFooterProps(finalState, undefined, column, this)
|
||||
)
|
||||
|
||||
const classes = [
|
||||
@@ -903,10 +780,8 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
}
|
||||
|
||||
const makeColumnFooters = () => {
|
||||
const tFootProps = getTfootProps(finalState, undefined, undefined, this)
|
||||
const tFootTrProps = _.splitProps(
|
||||
getTfootTrProps(finalState, undefined, undefined, this),
|
||||
)
|
||||
const tFootProps = _.splitProps(getTfootProps(finalState, undefined, undefined, this))
|
||||
const tFootTrProps = _.splitProps(getTfootTrProps(finalState, undefined, undefined, this))
|
||||
return (
|
||||
<TfootComponent
|
||||
className={tFootProps.className}
|
||||
@@ -927,9 +802,9 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
)
|
||||
}
|
||||
|
||||
const makePagination = () => {
|
||||
const makePagination = isTop => {
|
||||
const paginationProps = _.splitProps(
|
||||
getPaginationProps(finalState, undefined, undefined, this),
|
||||
getPaginationProps(finalState, undefined, undefined, this)
|
||||
)
|
||||
return (
|
||||
<PaginationComponent
|
||||
@@ -941,68 +816,54 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
|
||||
onPageSizeChange={this.onPageSizeChange}
|
||||
className={paginationProps.className}
|
||||
style={paginationProps.style}
|
||||
isTop={isTop}
|
||||
{...paginationProps.rest}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const makeTable = () => {
|
||||
const pagination = makePagination()
|
||||
return (
|
||||
<div
|
||||
className={classnames('ReactTable', className, rootProps.className)}
|
||||
style={{
|
||||
...style,
|
||||
...rootProps.style,
|
||||
}}
|
||||
{...rootProps.rest}
|
||||
const makeTable = () => (
|
||||
<div
|
||||
className={classnames('ReactTable', className, rootProps.className)}
|
||||
style={{
|
||||
...style,
|
||||
...rootProps.style,
|
||||
}}
|
||||
{...rootProps.rest}
|
||||
>
|
||||
{showPagination && showPaginationTop ? (
|
||||
<div className="pagination-top">{makePagination(true)}</div>
|
||||
) : null}
|
||||
<TableComponent
|
||||
className={classnames(tableProps.className, currentlyResizing ? 'rt-resizing' : '')}
|
||||
style={tableProps.style}
|
||||
{...tableProps.rest}
|
||||
>
|
||||
{showPagination && showPaginationTop
|
||||
? <div className="pagination-top">
|
||||
{pagination}
|
||||
</div>
|
||||
: null}
|
||||
<TableComponent
|
||||
className={classnames(
|
||||
tableProps.className,
|
||||
currentlyResizing ? 'rt-resizing' : '',
|
||||
)}
|
||||
style={tableProps.style}
|
||||
{...tableProps.rest}
|
||||
{hasHeaderGroups ? makeHeaderGroups() : null}
|
||||
{makeHeaders()}
|
||||
{hasFilters ? makeFilters() : null}
|
||||
<TbodyComponent
|
||||
className={classnames(tBodyProps.className)}
|
||||
style={{
|
||||
...tBodyProps.style,
|
||||
minWidth: `${rowMinWidth}px`,
|
||||
}}
|
||||
{...tBodyProps.rest}
|
||||
>
|
||||
{hasHeaderGroups ? makeHeaderGroups() : null}
|
||||
{makeHeaders()}
|
||||
{hasFilters ? makeFilters() : null}
|
||||
<TbodyComponent
|
||||
className={classnames(tBodyProps.className)}
|
||||
style={{
|
||||
...tBodyProps.style,
|
||||
minWidth: `${rowMinWidth}px`,
|
||||
}}
|
||||
{...tBodyProps.rest}
|
||||
>
|
||||
{pageRows.map((d, i) => makePageRow(d, i))}
|
||||
{padRows.map(makePadRow)}
|
||||
</TbodyComponent>
|
||||
{hasColumnFooter ? makeColumnFooters() : null}
|
||||
</TableComponent>
|
||||
{showPagination && showPaginationBottom
|
||||
? <div className="pagination-bottom">
|
||||
{pagination}
|
||||
</div>
|
||||
: null}
|
||||
{!pageRows.length &&
|
||||
<NoDataComponent {...noDataProps}>
|
||||
{_.normalizeComponent(noDataText)}
|
||||
</NoDataComponent>}
|
||||
<LoadingComponent
|
||||
loading={loading}
|
||||
loadingText={loadingText}
|
||||
{...loadingProps}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{pageRows.map((d, i) => makePageRow(d, i))}
|
||||
{padRows.map(makePadRow)}
|
||||
</TbodyComponent>
|
||||
{hasColumnFooter ? makeColumnFooters() : null}
|
||||
</TableComponent>
|
||||
{showPagination && showPaginationBottom ? (
|
||||
<div className="pagination-bottom">{makePagination(false)}</div>
|
||||
) : null}
|
||||
{!pageRows.length && (
|
||||
<NoDataComponent {...noDataProps}>{_.normalizeComponent(noDataText)}</NoDataComponent>
|
||||
)}
|
||||
<LoadingComponent loading={loading} loadingText={loadingText} {...loadingProps} />
|
||||
</div>
|
||||
)
|
||||
|
||||
// childProps are optionally passed to a function-as-a-child
|
||||
return children ? children(finalState, makeTable, this) : makeTable()
|
||||
|
||||
+6
-2
@@ -9,7 +9,7 @@ input-select-style()
|
||||
font-size: inherit
|
||||
border-radius: 3px
|
||||
font-weight: normal
|
||||
outline:none
|
||||
outline-width: 0
|
||||
|
||||
.ReactTable
|
||||
position:relative
|
||||
@@ -73,6 +73,9 @@ input-select-style()
|
||||
&:last-child
|
||||
border-right: 0
|
||||
|
||||
.rt-th:focus
|
||||
outline-width: 0
|
||||
|
||||
.rt-resizable-header
|
||||
overflow: visible
|
||||
&:last-child
|
||||
@@ -123,6 +126,7 @@ input-select-style()
|
||||
border-right:0
|
||||
.rt-expandable
|
||||
cursor: pointer
|
||||
text-overflow: clip
|
||||
.rt-tr-group
|
||||
flex: 1 0 auto
|
||||
display: flex
|
||||
@@ -226,7 +230,7 @@ input-select-style()
|
||||
background: alpha(black, .1)
|
||||
transition: all .1s ease
|
||||
cursor: pointer
|
||||
outline:none
|
||||
outline-width: 0
|
||||
|
||||
&[disabled]
|
||||
opacity: .5
|
||||
|
||||
+18
-22
@@ -1,26 +1,25 @@
|
||||
export default Base =>
|
||||
class extends Base {
|
||||
componentWillMount () {
|
||||
this.setStateWithData(this.getDataModel(this.getResolvedState()))
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.setStateWithData(this.getDataModel(this.getResolvedState(), true))
|
||||
}
|
||||
|
||||
componentDidMount () {
|
||||
this.fireFetchData()
|
||||
}
|
||||
|
||||
componentWillReceiveProps (nextProps, nextState) {
|
||||
const oldState = this.getResolvedState()
|
||||
const newState = this.getResolvedState(nextProps, nextState)
|
||||
componentDidUpdate (prevProps, prevState) {
|
||||
const oldState = this.getResolvedState(prevProps, prevState)
|
||||
const newState = this.getResolvedState(this.props, this.state)
|
||||
|
||||
// Do a deep compare of new and old `defaultOption` and
|
||||
// if they are different reset `option = defaultOption`
|
||||
const defaultableOptions = ['sorted', 'filtered', 'resized', 'expanded']
|
||||
defaultableOptions.forEach(x => {
|
||||
const defaultName = `default${x.charAt(0).toUpperCase() + x.slice(1)}`
|
||||
if (
|
||||
JSON.stringify(oldState[defaultName]) !==
|
||||
JSON.stringify(newState[defaultName])
|
||||
) {
|
||||
if (JSON.stringify(oldState[defaultName]) !== JSON.stringify(newState[defaultName])) {
|
||||
newState[x] = newState[defaultName]
|
||||
}
|
||||
})
|
||||
@@ -34,8 +33,7 @@ export default Base =>
|
||||
if (oldState[x] !== newState[x]) {
|
||||
const baseName = x.replace('able', '')
|
||||
const optionName = `${baseName}ed`
|
||||
const defaultName = `default${optionName.charAt(0).toUpperCase() +
|
||||
optionName.slice(1)}`
|
||||
const defaultName = `default${optionName.charAt(0).toUpperCase() + optionName.slice(1)}`
|
||||
newState[optionName] = newState[defaultName]
|
||||
}
|
||||
})
|
||||
@@ -48,7 +46,7 @@ export default Base =>
|
||||
oldState.sorted !== newState.sorted ||
|
||||
oldState.filtered !== newState.filtered
|
||||
) {
|
||||
this.setStateWithData(this.getDataModel(newState))
|
||||
this.setStateWithData(this.getDataModel(newState, oldState.data !== newState.data))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,13 +77,11 @@ export default Base =>
|
||||
oldState.sorted !== newResolvedState.sorted ||
|
||||
oldState.filtered !== newResolvedState.filtered ||
|
||||
oldState.showFilters !== newResolvedState.showFilters ||
|
||||
(!newResolvedState.frozen &&
|
||||
oldState.resolvedData !== newResolvedState.resolvedData)
|
||||
(!newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData)
|
||||
) {
|
||||
// Handle collapseOnsortedChange & collapseOnDataChange
|
||||
if (
|
||||
(oldState.sorted !== newResolvedState.sorted &&
|
||||
this.props.collapseOnSortingChange) ||
|
||||
(oldState.sorted !== newResolvedState.sorted && this.props.collapseOnSortingChange) ||
|
||||
oldState.filtered !== newResolvedState.filtered ||
|
||||
oldState.showFilters !== newResolvedState.showFilters ||
|
||||
(oldState.sortedData &&
|
||||
@@ -108,19 +104,19 @@ export default Base =>
|
||||
if (newResolvedState.sortedData) {
|
||||
newResolvedState.pages = newResolvedState.manual
|
||||
? newResolvedState.pages
|
||||
: Math.ceil(
|
||||
newResolvedState.sortedData.length / newResolvedState.pageSize,
|
||||
)
|
||||
newResolvedState.page = Math.max(
|
||||
: Math.ceil(newResolvedState.sortedData.length / newResolvedState.pageSize)
|
||||
newResolvedState.page = newResolvedState.manual ? newResolvedState.page : Math.max(
|
||||
newResolvedState.page >= newResolvedState.pages
|
||||
? newResolvedState.pages - 1
|
||||
: newResolvedState.page,
|
||||
0,
|
||||
0
|
||||
)
|
||||
}
|
||||
|
||||
return this.setState(newResolvedState, () => {
|
||||
if (cb) { cb() }
|
||||
if (cb) {
|
||||
cb()
|
||||
}
|
||||
if (
|
||||
oldState.page !== newResolvedState.page ||
|
||||
oldState.pageSize !== newResolvedState.pageSize ||
|
||||
|
||||
+68
-85
@@ -13,11 +13,12 @@ export default Base =>
|
||||
return resolvedState
|
||||
}
|
||||
|
||||
getDataModel (newState) {
|
||||
getDataModel (newState, dataChanged) {
|
||||
const {
|
||||
columns,
|
||||
pivotBy = [],
|
||||
data,
|
||||
resolveData,
|
||||
pivotIDKey,
|
||||
pivotValKey,
|
||||
subRowsKey,
|
||||
@@ -40,9 +41,7 @@ export default Base =>
|
||||
let columnsWithExpander = [...columns]
|
||||
|
||||
let expanderColumn = columns.find(
|
||||
col =>
|
||||
col.expander ||
|
||||
(col.columns && col.columns.some(col2 => col2.expander)),
|
||||
col => col.expander || (col.columns && col.columns.some(col2 => col2.expander))
|
||||
)
|
||||
// The actual expander might be in the columns field of a group column
|
||||
if (expanderColumn && !expanderColumn.expander) {
|
||||
@@ -91,7 +90,7 @@ export default Base =>
|
||||
if (dcol.accessor && !dcol.id) {
|
||||
console.warn(dcol)
|
||||
throw new Error(
|
||||
'A column id is required if using a non-string accessor for column above.',
|
||||
'A column id is required if using a non-string accessor for column above.'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -128,11 +127,9 @@ export default Base =>
|
||||
|
||||
visibleColumns = visibleColumns.map(column => {
|
||||
if (column.columns) {
|
||||
const visibleSubColumns = column.columns.filter(d => (
|
||||
pivotBy.indexOf(d.id) > -1
|
||||
? false
|
||||
: _.getFirstDefined(d.show, true)
|
||||
))
|
||||
const visibleSubColumns = column.columns.filter(d =>
|
||||
pivotBy.indexOf(d.id) > -1 ? false : _.getFirstDefined(d.show, true)
|
||||
)
|
||||
return {
|
||||
...column,
|
||||
columns: visibleSubColumns,
|
||||
@@ -141,13 +138,13 @@ export default Base =>
|
||||
return column
|
||||
})
|
||||
|
||||
visibleColumns = visibleColumns.filter(column => (
|
||||
visibleColumns = visibleColumns.filter(column =>
|
||||
column.columns
|
||||
? column.columns.length
|
||||
: pivotBy.indexOf(column.id) > -1
|
||||
? false
|
||||
: _.getFirstDefined(column.show, true)
|
||||
))
|
||||
)
|
||||
|
||||
// Find any custom pivot location
|
||||
const pivotIndex = visibleColumns.findIndex(col => col.pivot)
|
||||
@@ -164,9 +161,8 @@ export default Base =>
|
||||
})
|
||||
|
||||
const PivotParentColumn = pivotColumns.reduce(
|
||||
(prev, current) =>
|
||||
prev && prev === current.parentColumn && current.parentColumn,
|
||||
pivotColumns[0].parentColumn,
|
||||
(prev, current) => prev && prev === current.parentColumn && current.parentColumn,
|
||||
pivotColumns[0].parentColumn
|
||||
)
|
||||
|
||||
let PivotGroupHeader = hasHeaderGroups && PivotParentColumn.Header
|
||||
@@ -237,18 +233,23 @@ export default Base =>
|
||||
row[column.id] = column.accessor(d)
|
||||
})
|
||||
if (row[subRowsKey]) {
|
||||
row[subRowsKey] = row[subRowsKey].map((d, i) =>
|
||||
accessRow(d, i, level + 1),
|
||||
)
|
||||
row[subRowsKey] = row[subRowsKey].map((d, i) => accessRow(d, i, level + 1))
|
||||
}
|
||||
return row
|
||||
}
|
||||
let resolvedData = data.map((d, i) => accessRow(d, i))
|
||||
|
||||
// // If the data hasn't changed, just use the cached data
|
||||
let resolvedData = this.resolvedData
|
||||
// If the data has changed, run the data resolver and cache the result
|
||||
if (!this.resolvedData || dataChanged) {
|
||||
resolvedData = resolveData(data)
|
||||
this.resolvedData = resolvedData
|
||||
}
|
||||
// Use the resolved data
|
||||
resolvedData = resolvedData.map((d, i) => accessRow(d, i))
|
||||
|
||||
// TODO: Make it possible to fabricate nested rows without pivoting
|
||||
const aggregatingColumns = allVisibleColumns.filter(
|
||||
d => !d.expander && d.aggregate,
|
||||
)
|
||||
const aggregatingColumns = allVisibleColumns.filter(d => !d.expander && d.aggregate)
|
||||
|
||||
// If pivoting, recursively group the data
|
||||
const aggregate = rows => {
|
||||
@@ -266,9 +267,7 @@ export default Base =>
|
||||
return rows
|
||||
}
|
||||
// Group the rows together for this level
|
||||
let groupedRows = Object.entries(
|
||||
_.groupBy(rows, keys[i]),
|
||||
).map(([key, value]) => ({
|
||||
let groupedRows = Object.entries(_.groupBy(rows, keys[i])).map(([key, value]) => ({
|
||||
[pivotIDKey]: keys[i],
|
||||
[pivotValKey]: key,
|
||||
[keys[i]]: key,
|
||||
@@ -308,35 +307,39 @@ export default Base =>
|
||||
filtered,
|
||||
defaultFilterMethod,
|
||||
resolvedData,
|
||||
allVisibleColumns,
|
||||
allDecoratedColumns,
|
||||
} = resolvedState
|
||||
|
||||
const sortMethodsByColumnID = {}
|
||||
|
||||
allDecoratedColumns.filter(col => col.sortMethod).forEach(col => {
|
||||
sortMethodsByColumnID[col.id] = col.sortMethod
|
||||
})
|
||||
allDecoratedColumns
|
||||
.filter(col => col.sortMethod)
|
||||
.forEach(col => {
|
||||
sortMethodsByColumnID[col.id] = col.sortMethod
|
||||
})
|
||||
|
||||
// Resolve the data from either manual data or sorted data
|
||||
return {
|
||||
sortedData: manual
|
||||
? resolvedData
|
||||
: this.sortData(
|
||||
this.filterData(
|
||||
resolvedData,
|
||||
filtered,
|
||||
defaultFilterMethod,
|
||||
allVisibleColumns,
|
||||
),
|
||||
this.filterData(resolvedData, filtered, defaultFilterMethod, allDecoratedColumns),
|
||||
sorted,
|
||||
sortMethodsByColumnID,
|
||||
sortMethodsByColumnID
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fireFetchData () {
|
||||
this.props.onFetchData(this.getResolvedState(), this)
|
||||
// determine the current state, preferring certain state values over props
|
||||
const currentState = {
|
||||
...this.getResolvedState(),
|
||||
page: this.getStateOrProp('page'),
|
||||
pageSize: this.getStateOrProp('pageSize'),
|
||||
filtered: this.getStateOrProp('filtered'),
|
||||
}
|
||||
|
||||
this.props.onFetchData(currentState, this)
|
||||
}
|
||||
|
||||
getPropOrState (key) {
|
||||
@@ -365,9 +368,7 @@ export default Base =>
|
||||
if (column.filterAll) {
|
||||
return filterMethod(nextFilter, filteredSoFar, column)
|
||||
}
|
||||
return filteredSoFar.filter(row => (
|
||||
filterMethod(nextFilter, row, column)
|
||||
))
|
||||
return filteredSoFar.filter(row => filterMethod(nextFilter, row, column))
|
||||
}, filteredData)
|
||||
|
||||
// Apply the filter to the subrows if we are pivoting, and then
|
||||
@@ -383,7 +384,7 @@ export default Base =>
|
||||
row[this.props.subRowsKey],
|
||||
filtered,
|
||||
defaultFilterMethod,
|
||||
allVisibleColumns,
|
||||
allVisibleColumns
|
||||
),
|
||||
}
|
||||
})
|
||||
@@ -408,16 +409,12 @@ export default Base =>
|
||||
sorted.map(sort => {
|
||||
// Support custom sorting methods for each column
|
||||
if (sortMethodsByColumnID[sort.id]) {
|
||||
return (a, b) => (
|
||||
sortMethodsByColumnID[sort.id](a[sort.id], b[sort.id], sort.desc)
|
||||
)
|
||||
return (a, b) => sortMethodsByColumnID[sort.id](a[sort.id], b[sort.id], sort.desc)
|
||||
}
|
||||
return (a, b) => (
|
||||
this.props.defaultSortMethod(a[sort.id], b[sort.id], sort.desc)
|
||||
)
|
||||
return (a, b) => this.props.defaultSortMethod(a[sort.id], b[sort.id], sort.desc)
|
||||
}),
|
||||
sorted.map(d => !d.desc),
|
||||
this.props.indexKey,
|
||||
this.props.indexKey
|
||||
)
|
||||
|
||||
sortedData.forEach(row => {
|
||||
@@ -427,7 +424,7 @@ export default Base =>
|
||||
row[this.props.subRowsKey] = this.sortData(
|
||||
row[this.props.subRowsKey],
|
||||
sorted,
|
||||
sortMethodsByColumnID,
|
||||
sortMethodsByColumnID
|
||||
)
|
||||
})
|
||||
|
||||
@@ -435,10 +432,7 @@ export default Base =>
|
||||
}
|
||||
|
||||
getMinRows () {
|
||||
return _.getFirstDefined(
|
||||
this.props.minRows,
|
||||
this.getStateOrProp('pageSize'),
|
||||
)
|
||||
return _.getFirstDefined(this.props.minRows, this.getStateOrProp('pageSize'))
|
||||
}
|
||||
|
||||
// User actions
|
||||
@@ -449,9 +443,7 @@ export default Base =>
|
||||
if (collapseOnPageChange) {
|
||||
newState.expanded = {}
|
||||
}
|
||||
this.setStateWithData(newState, () => (
|
||||
onPageChange && onPageChange(page)
|
||||
))
|
||||
this.setStateWithData(newState, () => onPageChange && onPageChange(page))
|
||||
}
|
||||
|
||||
onPageSizeChange (newPageSize) {
|
||||
@@ -467,9 +459,7 @@ export default Base =>
|
||||
pageSize: newPageSize,
|
||||
page: newPage,
|
||||
},
|
||||
() => (
|
||||
onPageSizeChange && onPageSizeChange(newPageSize, newPage)
|
||||
),
|
||||
() => onPageSizeChange && onPageSizeChange(newPageSize, newPage)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -551,13 +541,13 @@ export default Base =>
|
||||
if (!additive) {
|
||||
newSorted = newSorted.slice(existingIndex, column.length)
|
||||
}
|
||||
// New Sort Column
|
||||
// New Sort Column
|
||||
} else if (additive) {
|
||||
newSorted = newSorted.concat(
|
||||
column.map(d => ({
|
||||
id: d.id,
|
||||
desc: firstSortDirection,
|
||||
})),
|
||||
}))
|
||||
)
|
||||
} else {
|
||||
newSorted = column.map(d => ({
|
||||
@@ -569,15 +559,10 @@ export default Base =>
|
||||
|
||||
this.setStateWithData(
|
||||
{
|
||||
page:
|
||||
(!sorted.length && newSorted.length) || !additive
|
||||
? 0
|
||||
: this.state.page,
|
||||
page: (!sorted.length && newSorted.length) || !additive ? 0 : this.state.page,
|
||||
sorted: newSorted,
|
||||
},
|
||||
() => (
|
||||
onSortedChange && onSortedChange(newSorted, column, additive)
|
||||
),
|
||||
() => onSortedChange && onSortedChange(newSorted, column, additive)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -586,9 +571,7 @@ export default Base =>
|
||||
const { onFilteredChange } = this.props
|
||||
|
||||
// Remove old filter first if it exists
|
||||
const newFiltering = (filtered || []).filter(x => (
|
||||
x.id !== column.id
|
||||
))
|
||||
const newFiltering = (filtered || []).filter(x => x.id !== column.id)
|
||||
|
||||
if (value !== '') {
|
||||
newFiltering.push({
|
||||
@@ -601,16 +584,13 @@ export default Base =>
|
||||
{
|
||||
filtered: newFiltering,
|
||||
},
|
||||
() => (
|
||||
onFilteredChange && onFilteredChange(newFiltering, column, value)
|
||||
),
|
||||
() => onFilteredChange && onFilteredChange(newFiltering, column, value)
|
||||
)
|
||||
}
|
||||
|
||||
resizeColumnStart (event, column, isTouch) {
|
||||
event.stopPropagation()
|
||||
const parentWidth = event.target.parentElement.getBoundingClientRect()
|
||||
.width
|
||||
const parentWidth = event.target.parentElement.getBoundingClientRect().width
|
||||
|
||||
let pageX
|
||||
if (isTouch) {
|
||||
@@ -638,14 +618,21 @@ export default Base =>
|
||||
document.addEventListener('mouseup', this.resizeColumnEnd)
|
||||
document.addEventListener('mouseleave', this.resizeColumnEnd)
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
resizeColumnMoving (event) {
|
||||
event.stopPropagation()
|
||||
const { onResizedChange } = this.props
|
||||
const { resized, currentlyResizing } = this.getResolvedState()
|
||||
const { onResizedChange, column } = this.props
|
||||
const { resized, currentlyResizing, columns } = this.getResolvedState()
|
||||
const currentColumn = columns.find(
|
||||
c => c.accessor === currentlyResizing.id || c.id === currentlyResizing.id
|
||||
)
|
||||
const minResizeWidth =
|
||||
currentColumn && currentColumn.minResizeWidth != null
|
||||
? currentColumn.minResizeWidth
|
||||
: column.minResizeWidth
|
||||
|
||||
// Delete old value
|
||||
const newResized = resized.filter(x => x.id !== currentlyResizing.id)
|
||||
@@ -658,11 +645,9 @@ export default Base =>
|
||||
pageX = event.pageX
|
||||
}
|
||||
|
||||
// Set the min size to 10 to account for margin and border or else the
|
||||
// group headers don't line up correctly
|
||||
const newWidth = Math.max(
|
||||
currentlyResizing.parentWidth + pageX - currentlyResizing.startX,
|
||||
11,
|
||||
minResizeWidth
|
||||
)
|
||||
|
||||
newResized.push({
|
||||
@@ -674,9 +659,7 @@ export default Base =>
|
||||
{
|
||||
resized: newResized,
|
||||
},
|
||||
() => (
|
||||
onResizedChange && onResizedChange(newResized, event)
|
||||
),
|
||||
() => onResizedChange && onResizedChange(newResized, event)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+94
-52
@@ -1,7 +1,5 @@
|
||||
import React, { Component } from 'react'
|
||||
import classnames from 'classnames'
|
||||
//
|
||||
// import _ from './utils'
|
||||
|
||||
const defaultButton = props => (
|
||||
<button type="button" {...props} className="-btn">
|
||||
@@ -10,8 +8,51 @@ const defaultButton = props => (
|
||||
)
|
||||
|
||||
export default class ReactTablePagination extends Component {
|
||||
static defaultProps = {
|
||||
PreviousComponent: defaultButton,
|
||||
NextComponent: defaultButton,
|
||||
renderPageJump: ({
|
||||
onChange, value, onBlur, onKeyPress, inputType, pageJumpText,
|
||||
}) => (
|
||||
<div className="-pageJump">
|
||||
<input
|
||||
aria-label={pageJumpText}
|
||||
type={inputType}
|
||||
onChange={onChange}
|
||||
value={value}
|
||||
onBlur={onBlur}
|
||||
onKeyPress={onKeyPress}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
renderCurrentPage: page => <span className="-currentPage">{page + 1}</span>,
|
||||
renderTotalPagesCount: pages => <span className="-totalPages">{pages || 1}</span>,
|
||||
renderPageSizeOptions: ({
|
||||
pageSize,
|
||||
pageSizeOptions,
|
||||
rowsSelectorText,
|
||||
onPageSizeChange,
|
||||
rowsText,
|
||||
}) => (
|
||||
<span className="select-wrap -pageSizeOptions">
|
||||
<select
|
||||
aria-label={rowsSelectorText}
|
||||
onChange={e => onPageSizeChange(Number(e.target.value))}
|
||||
value={pageSize}
|
||||
>
|
||||
{pageSizeOptions.map((option, i) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<option key={i} value={option}>
|
||||
{`${option} ${rowsText}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</span>
|
||||
),
|
||||
}
|
||||
|
||||
constructor (props) {
|
||||
super()
|
||||
super(props)
|
||||
|
||||
this.getSafePage = this.getSafePage.bind(this)
|
||||
this.changePage = this.changePage.bind(this)
|
||||
@@ -22,12 +63,18 @@ export default class ReactTablePagination extends Component {
|
||||
}
|
||||
}
|
||||
|
||||
componentWillReceiveProps (nextProps) {
|
||||
this.setState({ page: nextProps.page })
|
||||
componentDidUpdate (prevProps, prevState) {
|
||||
if (prevProps.page !== this.props.page && prevState.page !== this.state.page) {
|
||||
// this is probably safe because we only update when old/new state.page are different
|
||||
// eslint-disable-next-line react/no-did-update-set-state
|
||||
this.setState({
|
||||
page: this.props.page,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
getSafePage (page) {
|
||||
if (isNaN(page)) {
|
||||
if (Number.isNaN(page)) {
|
||||
page = this.props.page
|
||||
}
|
||||
return Math.min(Math.max(page, 0), this.props.pages - 1)
|
||||
@@ -42,11 +89,35 @@ export default class ReactTablePagination extends Component {
|
||||
}
|
||||
|
||||
applyPage (e) {
|
||||
if (e) { e.preventDefault() }
|
||||
if (e) {
|
||||
e.preventDefault()
|
||||
}
|
||||
const page = this.state.page
|
||||
this.changePage(page === '' ? this.props.page : page)
|
||||
}
|
||||
|
||||
getPageJumpProperties () {
|
||||
return {
|
||||
onKeyPress: e => {
|
||||
if (e.which === 13 || e.keyCode === 13) {
|
||||
this.applyPage()
|
||||
}
|
||||
},
|
||||
onBlur: this.applyPage,
|
||||
value: this.state.page === '' ? '' : this.state.page + 1,
|
||||
onChange: e => {
|
||||
const val = e.target.value
|
||||
const page = val - 1
|
||||
if (val === '') {
|
||||
return this.setState({ page: val })
|
||||
}
|
||||
this.setState({ page: this.getSafePage(page) })
|
||||
},
|
||||
inputType: this.state.page === '' ? 'text' : 'number',
|
||||
pageJumpText: this.props.pageJumpText,
|
||||
}
|
||||
}
|
||||
|
||||
render () {
|
||||
const {
|
||||
// Computed
|
||||
@@ -61,15 +132,16 @@ export default class ReactTablePagination extends Component {
|
||||
canNext,
|
||||
onPageSizeChange,
|
||||
className,
|
||||
PreviousComponent = defaultButton,
|
||||
NextComponent = defaultButton,
|
||||
PreviousComponent,
|
||||
NextComponent,
|
||||
renderPageJump,
|
||||
renderCurrentPage,
|
||||
renderTotalPagesCount,
|
||||
renderPageSizeOptions,
|
||||
} = this.props
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classnames(className, '-pagination')}
|
||||
style={this.props.paginationStyle}
|
||||
>
|
||||
<div className={classnames(className, '-pagination')} style={this.props.style}>
|
||||
<div className="-previous">
|
||||
<PreviousComponent
|
||||
onClick={() => {
|
||||
@@ -84,47 +156,17 @@ export default class ReactTablePagination extends Component {
|
||||
<div className="-center">
|
||||
<span className="-pageInfo">
|
||||
{this.props.pageText}{' '}
|
||||
{showPageJump
|
||||
? <div className="-pageJump">
|
||||
<input
|
||||
type={this.state.page === '' ? 'text' : 'number'}
|
||||
onChange={e => {
|
||||
const val = e.target.value
|
||||
const page = val - 1
|
||||
if (val === '') {
|
||||
return this.setState({ page: val })
|
||||
}
|
||||
this.setState({ page: this.getSafePage(page) })
|
||||
}}
|
||||
value={this.state.page === '' ? '' : this.state.page + 1}
|
||||
onBlur={this.applyPage}
|
||||
onKeyPress={e => {
|
||||
if (e.which === 13 || e.keyCode === 13) {
|
||||
this.applyPage()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
: <span className="-currentPage">
|
||||
{page + 1}
|
||||
</span>}{' '}
|
||||
{this.props.ofText}{' '}
|
||||
<span className="-totalPages">{pages || 1}</span>
|
||||
{showPageJump ? renderPageJump(this.getPageJumpProperties()) : renderCurrentPage(page)}{' '}
|
||||
{this.props.ofText} {renderTotalPagesCount(pages)}
|
||||
</span>
|
||||
{showPageSizeOptions &&
|
||||
<span className="select-wrap -pageSizeOptions">
|
||||
<select
|
||||
onChange={e => onPageSizeChange(Number(e.target.value))}
|
||||
value={pageSize}
|
||||
>
|
||||
{pageSizeOptions.map((option, i) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<option key={i} value={option}>
|
||||
{option} {this.props.rowsText}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</span>}
|
||||
renderPageSizeOptions({
|
||||
pageSize,
|
||||
rowsSelectorText: this.props.rowsSelectorText,
|
||||
pageSizeOptions,
|
||||
onPageSizeChange,
|
||||
rowsText: this.props.rowsText,
|
||||
})}
|
||||
</div>
|
||||
<div className="-next">
|
||||
<NextComponent
|
||||
|
||||
+33
-58
@@ -2,7 +2,7 @@ import PropTypes from 'prop-types'
|
||||
|
||||
export default {
|
||||
// General
|
||||
data: PropTypes.array,
|
||||
data: PropTypes.any,
|
||||
loading: PropTypes.bool,
|
||||
showPagination: PropTypes.bool,
|
||||
showPaginationTop: PropTypes.bool,
|
||||
@@ -82,41 +82,13 @@ export default {
|
||||
columns: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
// Renderers
|
||||
Cell: PropTypes.oneOfType([
|
||||
PropTypes.element,
|
||||
PropTypes.string,
|
||||
PropTypes.func,
|
||||
]),
|
||||
Header: PropTypes.oneOfType([
|
||||
PropTypes.element,
|
||||
PropTypes.string,
|
||||
PropTypes.func,
|
||||
]),
|
||||
Footer: PropTypes.oneOfType([
|
||||
PropTypes.element,
|
||||
PropTypes.string,
|
||||
PropTypes.func,
|
||||
]),
|
||||
Aggregated: PropTypes.oneOfType([
|
||||
PropTypes.element,
|
||||
PropTypes.string,
|
||||
PropTypes.func,
|
||||
]),
|
||||
Pivot: PropTypes.oneOfType([
|
||||
PropTypes.element,
|
||||
PropTypes.string,
|
||||
PropTypes.func,
|
||||
]),
|
||||
PivotValue: PropTypes.oneOfType([
|
||||
PropTypes.element,
|
||||
PropTypes.string,
|
||||
PropTypes.func,
|
||||
]),
|
||||
Expander: PropTypes.oneOfType([
|
||||
PropTypes.element,
|
||||
PropTypes.string,
|
||||
PropTypes.func,
|
||||
]),
|
||||
Cell: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
|
||||
Header: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
|
||||
Footer: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
|
||||
Aggregated: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
|
||||
Pivot: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
|
||||
PivotValue: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
|
||||
Expander: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
|
||||
Filter: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
|
||||
|
||||
// All Columns
|
||||
@@ -125,6 +97,7 @@ export default {
|
||||
filterable: PropTypes.bool, // use table default
|
||||
show: PropTypes.bool,
|
||||
minWidth: PropTypes.number,
|
||||
minResizeWidth: PropTypes.number,
|
||||
|
||||
// Cells only
|
||||
className: PropTypes.string,
|
||||
@@ -142,11 +115,11 @@ export default {
|
||||
// Footers only
|
||||
footerClassName: PropTypes.string,
|
||||
footerStyle: PropTypes.object,
|
||||
getFooterProps: PropTypes.object,
|
||||
getFooterProps: PropTypes.func,
|
||||
filterMethod: PropTypes.func,
|
||||
filterAll: PropTypes.bool,
|
||||
sortMethod: PropTypes.func,
|
||||
}),
|
||||
})
|
||||
),
|
||||
|
||||
// Global Expander Column Defaults
|
||||
@@ -167,28 +140,30 @@ export default {
|
||||
pageText: PropTypes.node,
|
||||
ofText: PropTypes.node,
|
||||
rowsText: PropTypes.node,
|
||||
pageJumpText: PropTypes.node,
|
||||
rowsSelectorText: PropTypes.node,
|
||||
|
||||
// Components
|
||||
TableComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
TheadComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
TbodyComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
TrGroupComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
TrComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
ThComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
TdComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
TfootComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
FilterComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
ExpanderComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
PivotValueComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
AggregatedComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
TableComponent: PropTypes.elementType,
|
||||
TheadComponent: PropTypes.elementType,
|
||||
TbodyComponent: PropTypes.elementType,
|
||||
TrGroupComponent: PropTypes.elementType,
|
||||
TrComponent: PropTypes.elementType,
|
||||
ThComponent: PropTypes.elementType,
|
||||
TdComponent: PropTypes.elementType,
|
||||
TfootComponent: PropTypes.elementType,
|
||||
FilterComponent: PropTypes.elementType,
|
||||
ExpanderComponent: PropTypes.elementType,
|
||||
PivotValueComponent: PropTypes.elementType,
|
||||
AggregatedComponent: PropTypes.elementType,
|
||||
// this is a computed default generated using
|
||||
PivotComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
PivotComponent: PropTypes.elementType,
|
||||
// the ExpanderComponent and PivotValueComponent at run-time in methods.js
|
||||
PaginationComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
PreviousComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
NextComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
LoadingComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
NoDataComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
ResizerComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
PadRowComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
|
||||
PaginationComponent: PropTypes.elementType,
|
||||
PreviousComponent: PropTypes.elementType,
|
||||
NextComponent: PropTypes.elementType,
|
||||
LoadingComponent: PropTypes.elementType,
|
||||
NoDataComponent: PropTypes.elementType,
|
||||
ResizerComponent: PropTypes.elementType,
|
||||
PadRowComponent: PropTypes.elementType,
|
||||
}
|
||||
|
||||
+24
-13
@@ -78,9 +78,7 @@ function orderBy (arr, funcs, dirs, indexKey) {
|
||||
}
|
||||
}
|
||||
// Use the row index for tie breakers
|
||||
return dirs[0]
|
||||
? rowA[indexKey] - rowB[indexKey]
|
||||
: rowB[indexKey] - rowA[indexKey]
|
||||
return dirs[0] ? rowA[indexKey] - rowB[indexKey] : rowB[indexKey] - rowA[indexKey]
|
||||
})
|
||||
}
|
||||
|
||||
@@ -103,7 +101,7 @@ function clone (a) {
|
||||
return value.toString()
|
||||
}
|
||||
return value
|
||||
}),
|
||||
})
|
||||
)
|
||||
} catch (e) {
|
||||
return a
|
||||
@@ -119,9 +117,7 @@ function getFirstDefined (...args) {
|
||||
}
|
||||
|
||||
function sum (arr) {
|
||||
return arr.reduce((a, b) => (
|
||||
a + b
|
||||
), 0)
|
||||
return arr.reduce((a, b) => a + b, 0)
|
||||
}
|
||||
|
||||
function makeTemplateComponent (compClass, displayName) {
|
||||
@@ -207,10 +203,25 @@ function isSortingDesc (d) {
|
||||
return !!(d.sort === 'desc' || d.desc === true || d.asc === false)
|
||||
}
|
||||
|
||||
function normalizeComponent (Comp, params = {}, fallback = Comp) {
|
||||
return typeof Comp === 'function'
|
||||
? Object.getPrototypeOf(Comp).isReactComponent
|
||||
? <Comp {...params} />
|
||||
: Comp(params)
|
||||
: fallback
|
||||
function normalizeComponent (Comp, props, fallback = Comp) {
|
||||
return isReactComponent(Comp) ? <Comp {...props} /> : typeof Comp === 'function' ? Comp(props) : fallback
|
||||
}
|
||||
|
||||
function isClassComponent (component) {
|
||||
return (
|
||||
typeof component === 'function' &&
|
||||
!!Object.getPrototypeOf(component).isReactComponent
|
||||
)
|
||||
}
|
||||
|
||||
function isFunctionComponent (component) {
|
||||
return (
|
||||
typeof component === 'function' &&
|
||||
String(component).includes('.createElement')
|
||||
)
|
||||
}
|
||||
|
||||
function isReactComponent (component) {
|
||||
return isClassComponent(component) || isFunctionComponent(component)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
const webpack = require('webpack')
|
||||
module.exports = {
|
||||
entry: './lib/index.js',
|
||||
output: {
|
||||
filename: './react-table.js',
|
||||
libraryTarget: 'umd',
|
||||
library: 'ReactTable'
|
||||
},
|
||||
externals: {
|
||||
react: {
|
||||
root: 'React',
|
||||
commonjs2: 'react',
|
||||
commonjs: 'react',
|
||||
amd: 'react'
|
||||
}
|
||||
},
|
||||
plugins: [
|
||||
new webpack.optimize.UglifyJsPlugin()
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
* https://github.com/tannerlinsley/react-table
|
||||
Reference in New Issue
Block a user