Merge pull request #1723 from chandaniprajapati/react-datatable

This commit is contained in:
Hugo Bernier 2021-02-22 23:13:04 -05:00 committed by GitHub
commit 37dc6cd041
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 19561 additions and 0 deletions

View File

@ -0,0 +1,25 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# change these settings to your own preference
indent_style = space
indent_size = 2
# we recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package,bower}.json]
indent_style = space
indent_size = 2

32
samples/react-datatable/.gitignore vendored Normal file
View File

@ -0,0 +1,32 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
solution
temp
*.sppkg
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,12 @@
{
"@microsoft/generator-sharepoint": {
"isCreatingSolution": true,
"environment": "spo",
"version": "1.11.0",
"libraryName": "react-datatable",
"libraryId": "35299377-f8c8-4721-bd53-05602fc0c4ee",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,60 @@
# SharePoint Framework DataTable web part sample
## Summary
This web part provides easy way to render SharePoint custom list in datatable view with all the necessary features.
## Features
- Searching (Configurable)
- Sorting (Configurable)
- Download as a CSV and PDF,
- Pagination,
- Column Ordering,
- Dynamic colors for odd and even rows.
![Preview](assets/preview.png?raw=true "Preview")
## Compatibility
![SPFx 1.11](https://img.shields.io/badge/SPFx-1.11.0-green.svg)
![Node.js LTS 10.x](https://img.shields.io/badge/Node.js-LTS%2010.x-green.svg)
![SharePoint Online](https://img.shields.io/badge/SharePoint-Online-yellow.svg)
![Teams N/A: Untested with Microsoft Teams](https://img.shields.io/badge/Teams-N%2FA-lightgrey.svg "Untested with Microsoft Teams")
![Workbench Hosted: Does not work with local workbench](https://img.shields.io/badge/Workbench-Hosted-yellow.svg "Does not work with local workbench")
## Applies to
* [SharePoint Framework](https://docs.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Office 365 tenant](https://docs.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment)
## Solution
Solution|Author(s)
--------|---------
react-datatable | Chandani Prajapati ([@Chandani_SPD](https://twitter.com/Chandani_SPD))
## Version history
Version|Date|Comments
-------|----|--------
1.0|February 29, 2021|Initial release
## Disclaimer
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
---
## Minimal Path to Awesome
### Local testing
* Clone the repository
* `cd` to web part's project folder
* In the command line run:
* `npm install`
* `gulp serve`
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-datatable" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

View File

@ -0,0 +1,20 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"react-datatable-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/reactDatatable/ReactDatatableWebPart.js",
"manifest": "./src/webparts/reactDatatable/ReactDatatableWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"ReactDatatableWebPartStrings": "lib/webparts/reactDatatable/loc/{locale}.js",
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/lib/loc/{locale}.js",
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/copy-assets.schema.json",
"deployCdnPath": "temp/deploy"
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "react-datatable",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,20 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-datatable-client-side-solution",
"id": "35299377-f8c8-4721-bd53-05602fc0c4ee",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": ""
}
},
"paths": {
"zippedPackage": "solution/react-datatable.sppkg"
}
}

View File

@ -0,0 +1,10 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://localhost:5432/workbench",
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

7
samples/react-datatable/gulpfile.js vendored Normal file
View File

@ -0,0 +1,7 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
build.initialize(require('gulp'));

18379
samples/react-datatable/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,49 @@
{
"name": "react-datatable",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@material-ui/core": "^4.11.3",
"@material-ui/data-grid": "^4.0.0-alpha.19",
"@material-ui/icons": "^4.11.2",
"@material-ui/lab": "^4.0.0-alpha.57",
"@microsoft/sp-core-library": "1.11.0",
"@microsoft/sp-lodash-subset": "1.11.0",
"@microsoft/sp-office-ui-fabric-core": "1.11.0",
"@microsoft/sp-property-pane": "1.11.0",
"@microsoft/sp-webpart-base": "1.11.0",
"@pnp/sp": "^2.1.1",
"@pnp/spfx-controls-react": "^2.4.0",
"@pnp/spfx-property-controls": "^2.3.0",
"export-to-csv": "^0.2.1",
"jspdf": "^2.3.0",
"jspdf-autotable": "^3.5.13",
"office-ui-fabric-react": "6.214.0",
"react": "16.8.5",
"react-dom": "16.8.5"
},
"devDependencies": {
"@types/react": "16.8.8",
"@types/react-dom": "16.8.3",
"@microsoft/sp-build-web": "1.11.0",
"@microsoft/sp-tslint-rules": "1.11.0",
"@microsoft/sp-module-interfaces": "1.11.0",
"@microsoft/sp-webpart-workbench": "1.11.0",
"@microsoft/rush-stack-compiler-3.3": "0.3.5",
"gulp": "~3.9.1",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~5.2.2",
"@types/webpack-env": "1.13.1",
"@types/es6-promise": "0.0.33"
}
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,44 @@
import * as React from 'react';
import * as strings from 'ReactDatatableWebPartStrings';
import { ExportToCsv } from 'export-to-csv';
import { Button } from '@material-ui/core';
import GetAppSharpIcon from '@material-ui/icons/GetAppSharp';
interface IExportToCSV {
columnHeader: Array<string>;
listItems: any[];
listName: string;
description: string;
}
export function ExportListItemsToCSV(props: IExportToCSV) {
let { columnHeader, listItems, listName, description } = props;
function generateCSV() {
let colHeader = columnHeader;
const options = {
filename: listName,
fieldSeparator: ',',
quoteStrings: '"',
decimalSeparator: '.',
showLabels: true,
showTitle: true,
title: '',
useTextFile: false,
useBom: true,
useKeysAsHeaders: true,
headers: colHeader
};
const csvExporter = new ExportToCsv(options);
csvExporter.generateCsv(listItems);
}
return (
<Button variant="contained"
onClick={() => generateCSV()}
startIcon={<GetAppSharpIcon />}>
{strings.DownloadAsCSVLabel}
</Button>
);
}

View File

@ -0,0 +1,29 @@
import * as React from 'react';
import * as strings from 'ReactDatatableWebPartStrings';
import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import { Button } from '@material-ui/core';
import GetAppSharpIcon from '@material-ui/icons/GetAppSharp';
interface IExportToPDF {
htmlElementForPDF: string;
listName: string;
}
export function ExportListItemsToPDF(props: IExportToPDF) {
let { htmlElementForPDF, listName } = props;
function genearatePDF() {
const doc = new jsPDF();
autoTable(doc, { html: htmlElementForPDF, theme: 'grid' });
doc.save(`${listName}.pdf`);
}
return (
<Button variant="contained"
onClick={() => genearatePDF()}
startIcon={<GetAppSharpIcon />}>
{strings.DownloadAsPDFLabel}
</Button>
);
}

View File

@ -0,0 +1,44 @@
import TablePagination from '@material-ui/core/TablePagination';
import * as React from 'react';
interface IPagination {
colSpan: number;
totalItems: number;
onPaginationUpdate: (pageNo: number, pageSize: number) => void;
}
export function Pagination(props: IPagination) {
let { colSpan, totalItems, onPaginationUpdate } = props;
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(5);
React.useEffect(() => {
onPaginationUpdate(page, rowsPerPage);
}, [page, rowsPerPage]);
const handlePageChange = (event, newPage: number) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
return (
<TablePagination
rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]}
colSpan={colSpan}
count={totalItems}
rowsPerPage={rowsPerPage}
page={page}
SelectProps={{
inputProps: { 'aria-label': 'rows per page' },
native: true,
}}
onChangePage={handlePageChange}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
);
}

View File

@ -0,0 +1,53 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { sp } from '@pnp/sp/presets/all';
export class SPService {
constructor(private context: WebPartContext) {
sp.setup({
spfxContext: this.context
});
}
public async getListItems(selectedList: string, selectedFields: any[]) {
try {
let selectQuery: any[] = ['Id'];
let expandQuery: any[] = [];
for (var i = 0; i < selectedFields.length; i++) {
switch (selectedFields[i].fieldType) {
case 'SP.FieldUser':
case 'SP.FieldLookup':
selectQuery.push(`${selectedFields[i].key}/Title`);
expandQuery.push(selectedFields[i].key);
break;
case 'SP.Field':
selectQuery.push('Attachments,AttachmentFiles');
expandQuery.push('AttachmentFiles');
break;
default:
selectQuery.push(selectedFields[i].key);
break;
}
}
let listItems: any[] = await sp.web.lists.getById(selectedList).items
.select(selectQuery.join())
.expand(expandQuery.join()).get();
return listItems;
} catch (err) {
Promise.reject(err);
}
}
public async getFields(selectedList: string): Promise<any> {
try {
const allFields: any[] = await sp.web.lists
.getById(selectedList)
.fields
.filter("Hidden eq false and ReadOnlyField eq false and Title ne 'Content Type' and Title ne 'Attachments'")
.get();
return allFields;
}
catch (err) {
Promise.reject(err);
}
}
}

View File

@ -0,0 +1,39 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "9d6e26c1-e57c-4005-ad6a-5b066f1acd65",
"alias": "ReactDatatableWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": [
"SharePointWebPart"
],
"preconfiguredEntries": [
{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": {
"default": "Other"
},
"title": {
"default": "react-datatable"
},
"description": {
"default": "Shows the sharepoint list items in data table format with some advanced features."
},
"officeFabricIconFontName": "Table",
"properties": {
"title": "Webpart Title (eg. DataTable)",
"enableSorting": true,
"enableSearching": true,
"enableDownloadAsCsv": true,
"enableDownloadAsPdf": true,
"enablePagination": true
}
}
]
}

View File

@ -0,0 +1,245 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
IPropertyPaneDropdownOption,
PropertyPaneToggle,
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as strings from 'ReactDatatableWebPartStrings';
import ReactDatatable from './components/ReactDatatable';
import { IReactDatatableProps } from './components/IReactDatatableProps';
import { sp } from '@pnp/sp';
import { SPService } from '../../shared/service/SPService';
import { PropertyFieldColorPicker, PropertyFieldColorPickerStyle } from '@pnp/spfx-property-controls/lib/PropertyFieldColorPicker';
import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldListPicker';
import { PropertyFieldMultiSelect } from '@pnp/spfx-property-controls/lib/PropertyFieldMultiSelect';
import { PropertyFieldOrder } from '@pnp/spfx-property-controls/lib/PropertyFieldOrder';
export interface IReactDatatableWebPartProps {
title: string;
list: string;
fields: any;
fieldDetails: any;
searchBy: any[];
sortBy: any[];
oddRowColor: string;
evenRowColor: string;
enableSorting: boolean;
enableSearching: boolean;
enablePagination: boolean;
enableDownloadAsCsv: boolean;
enableDownloadAsPdf: boolean;
fieldOrder: Array<any>;
}
export default class ReactDatatableWebPart extends BaseClientSideWebPart<IReactDatatableWebPartProps> {
private _services: SPService = null;
private _selectedFields: Array<IPropertyPaneDropdownOption>;
public onInit(): Promise<void> {
return super.onInit().then(_ => {
sp.setup({
spfxContext: this.context
});
this._services = new SPService(this.context);
});
}
private mapFieldsToObjects = () => {
let { fields = [], fieldDetails = [] } = this.properties;
return fields.map(f => fieldDetails.find(fDetails => fDetails.key === f));
}
public async getSelectedListFields() {
if (this.properties.list) {
let allFields = await this._services.getFields(this.properties.list);
this.properties.fieldDetails = allFields.map(field => ({ key: field.InternalName, text: field.Title, fieldType: field['odata.type'] }));
this.context.propertyPane.refresh();
}
}
public render(): void {
this.getSelectedListFields();
const element: React.ReactElement<IReactDatatableProps> = React.createElement(
ReactDatatable,
{
context: this.context,
title: this.properties.title,
list: this.properties.list,
fieldDetails: this.properties.fieldDetails,
fields: this.mapFieldsToObjects(),
enableSorting: this.properties.enableSorting,
enableSearching: this.properties.enableSearching,
enablePagination: this.properties.enablePagination,
searchBy: this.properties.searchBy,
sortBy: this.properties.sortBy,
enableDownloadAsCsv: this.properties.enableDownloadAsCsv,
enableDownloadAsPdf: this.properties.enableDownloadAsPdf,
displayMode: this.displayMode,
oddRowColor: this.properties.oddRowColor,
evenRowColor: this.properties.evenRowColor,
fieldOrder: this.properties.fieldOrder,
onChangeProperty: this.onChangeProperty
}
);
ReactDom.render(element, this.domElement);
}
public onChangeProperty = (changeType: string, oldValue: any, newValue: any[]): void => {
switch (changeType) {
case "list":
this.getSelectedListFields();
this.properties.fields = [];
break;
case "fieldOrder":
this.properties.fields = newValue.map(n => n.key);
break;
default:
break;
}
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
let isSearch = !this.properties.enableSearching;
let isSort = !this.properties.enableSorting;
this._selectedFields = this.mapFieldsToObjects();
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
displayGroupsAsAccordion: true,
groups: [
{
groupName: strings.ListConfigurationGroupName,
isCollapsed: false,
groupFields: [
PropertyPaneTextField('title', {
label: strings.DataTableTitleFieldLabel
}),
PropertyFieldListPicker('list', {
label: strings.ListPickerLabel,
selectedList: this.properties.list,
includeHidden: false,
orderBy: PropertyFieldListPickerOrderBy.Title,
disabled: false,
baseTemplate: 100,
onPropertyChange: this.onChangeProperty.bind(this),
properties: this.properties,
context: this.context,
onGetErrorMessage: null,
key: 'listPickerFieldId',
}),
PropertyFieldMultiSelect('fields', {
key: 'fields',
label: strings.MultiSelectFieldLabel,
options: this.properties.fieldDetails,
selectedKeys: this.properties.fields
}),
]
},
{
groupName: strings.SearchAndSortGroupName,
isCollapsed: false,
groupFields: [
PropertyPaneToggle('enableSorting', {
label: strings.SortingToggleLabel,
checked: true
}),
PropertyFieldMultiSelect('sortBy', {
key: 'sortBy',
label: strings.SortByLabel,
disabled: isSort,
options: this._selectedFields,
selectedKeys: this.properties.sortBy
}),
PropertyPaneToggle('enableSearching', {
label: strings.SearchingToggleLabel,
checked: false
}),
PropertyFieldMultiSelect('searchBy', {
key: 'searchBy',
label: strings.SearchByLabel,
disabled: isSearch,
options: this._selectedFields,
selectedKeys: this.properties.searchBy
}),
]
},
]
},
{
displayGroupsAsAccordion: true,
groups: [
{
groupName: strings.AdvancedFeaturesGroupName,
isCollapsed: false,
groupFields: [
PropertyPaneToggle('enableDownloadAsCsv', {
label: strings.CSVToggleLabel,
checked: false
}),
PropertyPaneToggle('enableDownloadAsPdf', {
label: strings.PDFToggleLabel,
checked: false
}),
PropertyPaneToggle('enablePagination', {
label: strings.PaginationLabel,
checked: false
}),
PropertyFieldOrder("fieldOrder", {
key: "fieldOrder",
label: strings.OrderListItemsLabel,
items: this._selectedFields,
textProperty: "text",
properties: this.properties,
onPropertyChange: this.onChangeProperty
}),
PropertyFieldColorPicker('evenRowColor', {
label: strings.EvenRowColorLabel,
selectedColor: this.properties.evenRowColor,
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
disabled: false,
isHidden: false,
alphaSliderHidden: false,
style: PropertyFieldColorPickerStyle.Full,
iconName: 'Precipitation',
key: 'colorFieldId'
}),
PropertyFieldColorPicker('oddRowColor', {
label: strings.OddRowColorLabel,
selectedColor: this.properties.oddRowColor,
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
disabled: false,
isHidden: false,
alphaSliderHidden: false,
style: PropertyFieldColorPickerStyle.Full,
iconName: 'Precipitation',
key: 'colorFieldId'
}),
]
},
]
}
]
};
}
}

View File

@ -0,0 +1,23 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { DisplayMode } from '@microsoft/sp-core-library';
import { IPropertyPaneDropdownOption } from "@microsoft/sp-property-pane";
export interface IReactDatatableProps {
context: WebPartContext;
displayMode: DisplayMode;
title: string;
list: string;
oddRowColor: string;
evenRowColor: string;
fields: Array<IPropertyPaneDropdownOption & { fieldType: string }>;
fieldDetails: any[];
onChangeProperty: any;
enableSorting: boolean;
enableSearching: boolean;
enablePagination: boolean;
enableDownloadAsCsv: boolean;
enableDownloadAsPdf: boolean;
searchBy: string[];
sortBy: string[];
fieldOrder: Array<any>;
}

View File

@ -0,0 +1,12 @@
import { ColDef } from "@material-ui/data-grid";
export interface IReactDatatableState {
listItems: any[];
columns: ColDef[];
page: number;
rowsPerPage: number;
searchText: string;
contentType: string;
sortingFields: string;
sortDirection: 'asc'|'desc';
}

View File

@ -0,0 +1,10 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.reactDatatable {
.dataTableUtilities{
margin-bottom: 10px;
.downloadButtons > *{
margin-right: 10px;
}
}
}

View File

@ -0,0 +1,306 @@
import * as React from 'react';
import styles from './ReactDatatable.module.scss';
import { IReactDatatableProps } from './IReactDatatableProps';
import { IReactDatatableState } from './IReactDatatableState';
import * as strings from 'ReactDatatableWebPartStrings';
import { SPService } from '../../../shared/service/SPService';
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
import { DisplayMode } from '@microsoft/sp-core-library';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import { Alert, AlertTitle } from '@material-ui/lab';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableFooter from '@material-ui/core/TableFooter';
import TableRow from '@material-ui/core/TableRow';
import { Grid, InputAdornment, Link, TextField } from '@material-ui/core';
import SearchIcon from '@material-ui/icons/Search';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import { withStyles, Theme, createStyles, makeStyles } from '@material-ui/core/styles';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import { ExportListItemsToCSV } from '../../../shared/common/ExportListItemsToCSV/ExportListItemsToCSV';
import { ExportListItemsToPDF } from '../../../shared/common/ExportListItemsToPDF/ExportListItemsToPDF';
import { Pagination } from '../../../shared/common/Pagination/Pagination';
const StyledTableCell = withStyles((theme: Theme) =>
createStyles({
head: {
backgroundColor: theme.palette.grey[200],
},
body: {
fontSize: 14,
},
}),
)(TableCell);
export default class ReactDatatable extends React.Component<IReactDatatableProps, IReactDatatableState> {
private _services: SPService = null;
constructor(props: IReactDatatableProps) {
super(props);
this.state = {
listItems: [],
columns: [],
page: 0,
rowsPerPage: 5,
searchText: '',
sortingFields: '',
sortDirection: 'asc',
contentType: ''
};
this._services = new SPService(this.props.context);
this._onConfigure = this._onConfigure.bind(this);
this.getSelectedListItems = this.getSelectedListItems.bind(this);
}
public componentDidMount() {
this.getSelectedListItems();
}
public componentDidUpdate(prevProps: IReactDatatableProps) {
if (prevProps.list !== this.props.list) {
this.props.onChangeProperty("list");
}
else if (this.props.fields != prevProps.fields) {
this.getSelectedListItems();
}
}
public async getSelectedListItems() {
let fields = this.props.fields || [];
if (fields.length) {
let listItems = await this._services.getListItems(this.props.list, fields);
/** Format list items for data grid */
listItems = listItems && listItems.map(item => ({
id: item.Id, ...fields.reduce((ob, f) => {
ob[f.key] = item[f.key] ? this.formatColumnValue(item[f.key], f.fieldType) : '-';
return ob;
}, {})
}));
let dataGridColumns = [...fields].map(f => ({ field: f.key as string, headerName: f.text }));
this.setState({ listItems: listItems, columns: dataGridColumns });
}
}
private _onConfigure() {
this.props.context.propertyPane.open();
}
public formatColumnValue(value: any, type: string) {
if (!value) {
return value;
}
switch (type) {
case 'SP.FieldDateTime':
value = value;
break;
case 'SP.FieldMultiChoice':
value = (value instanceof Array) ? value.join() : value;
break;
case 'SP.Taxonomy.TaxonomyField':
value = value['Label'];
break;
case 'SP.FieldLookup':
value = value['Title'];
break;
case 'SP.FieldUser':
value = value['Title'];
break;
case 'SP.FieldMultiLineText':
value = <div dangerouslySetInnerHTML={{ __html: value }}></div>;
break;
case 'SP.FieldText':
value = value;
break;
case 'SP.FieldComputed':
value = value;
break;
case 'SP.FieldUrl':
value = <Link href={value['Url']} target="_blank">{value['Description']}</Link>;
break;
case 'SP.FieldLocation':
value = JSON.parse(value).DisplayName;
break;
default:
break;
}
return value;
}
private handlePaginationChange(pageNo: number, pageSize: number) {
this.setState({ page: pageNo, rowsPerPage: pageSize });
}
public handleSearch(event: React.ChangeEvent<HTMLInputElement>) {
this.setState({ searchText: event.target.value });
}
public filterListItems() {
let { searchBy, enableSorting } = this.props;
let { sortingFields, listItems, searchText } = this.state;
if (searchText) {
if (searchBy) {
listItems = listItems.filter(l => searchBy.some(field => {
return (l[field] && l[field].toLowerCase().includes(searchText.toLowerCase()));
}));
}
}
if (enableSorting && sortingFields) {
listItems = this.sortListItems(listItems);
}
return listItems;
}
private sortListItems(listItems: any[]) {
const { sortingFields, sortDirection } = this.state;
const isAsc = sortDirection === 'asc' ? 1 : -1;
let sortFieldDetails = this.props.fields.filter(f => f.key === sortingFields)[0];
let sortFn: (a, b) => number;
switch (sortFieldDetails.fieldType) {
case 'SP.FieldDateTime':
sortFn = (a, b) => ((new Date(a[sortingFields]).getTime() > new Date(b[sortingFields]).getTime()) ? 1 : -1) * isAsc;
break;
default:
sortFn = (a, b) => ((a[sortingFields] > b[sortingFields]) ? 1 : -1) * isAsc;
break;
}
listItems.sort(sortFn);
return listItems;
}
private paginateFn = (filterItem: any[]) => {
let { rowsPerPage, page } = this.state;
return (rowsPerPage > 0
? filterItem.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
: filterItem
);
}
private handleSorting = (property: string) => (event: React.MouseEvent<unknown>) => {
let { sortingFields, sortDirection } = this.state;
const isAsc = sortingFields === property && sortDirection === 'asc';
this.setState({ sortDirection: (isAsc ? 'desc' : 'asc'), sortingFields: property });
}
public render(): React.ReactElement<IReactDatatableProps> {
let filteredItems = this.filterListItems();
let { list, fields, enableDownloadAsCsv, enableDownloadAsPdf, enablePagination, displayMode, enableSearching, title, evenRowColor, oddRowColor, sortBy } = this.props;
let { sortingFields, sortDirection, columns, listItems } = this.state;
filteredItems = enablePagination ? this.paginateFn(filteredItems) : filteredItems;
return (
<div className={styles.reactDatatable}>
{
this.props.list == "" || this.props.list == undefined ?
<Placeholder
iconName='Edit'
iconText='Configure your web part'
description={strings.ConfigureWebpartDescription}
buttonLabel={strings.ConfigureWebpartButtonLabel}
hideButton={displayMode === DisplayMode.Read}
onConfigure={this._onConfigure} /> : <>
<WebPartTitle
title={title}
displayMode={DisplayMode.Read}
updateProperty={() => { }}>
</WebPartTitle>
{ list && fields && fields.length ?
<div>
<Grid container className={styles.dataTableUtilities}>
<Grid item xs={6} className={styles.downloadButtons}>
{
enableDownloadAsCsv
? <ExportListItemsToCSV
columnHeader={columns.map(c => c.headerName)}
listName={list}
description={title}
listItems={listItems}
/> : <></>
}
{
enableDownloadAsPdf
? <ExportListItemsToPDF
listName={list}
htmlElementForPDF='#dataTable'
/>
: <></>
}
</Grid>
<Grid container justify='flex-end' xs={6}>
{
enableSearching ?
<TextField
onChange={this.handleSearch.bind(this)}
size="small"
label="Search"
variant="outlined"
InputProps={{
endAdornment: (
<InputAdornment position="end">
<SearchIcon />
</InputAdornment>
),
}}
/>
: <></>
}
</Grid>
</Grid>
<div id="generateTable">
<TableContainer component={Paper} >
<Table aria-label="customized table" id="dataTable" >
<TableHead>
<TableRow>
{columns.map((c) => (
<StyledTableCell key={c.headerName}>
{
(sortBy && sortBy.indexOf(c.field) !== -1)
? <TableSortLabel
active={sortingFields === c.field}
direction={sortingFields === c.field ? sortDirection : 'asc'}
onClick={this.handleSorting(c.field)}
>
{c.headerName}
</TableSortLabel>
: c.headerName
}
</StyledTableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{filteredItems.map((row, index) => (
<TableRow
style={{ backgroundColor: ((index + 1) % 2 === 0) ? evenRowColor : oddRowColor }} >
{columns.map((c) => (
<StyledTableCell >{row[c.field]}</StyledTableCell >
))}
</TableRow>
))}
</TableBody>
{enablePagination ?
<React.Fragment>
<TableFooter>
<TableRow>
<Pagination
colSpan={columns.length}
onPaginationUpdate={this.handlePaginationChange.bind(this)}
totalItems={listItems.length} />
</TableRow>
</TableFooter>
</React.Fragment> : <></>
}
</Table>
</TableContainer>
</div>
</div> : <Alert severity="info">
{strings.ListFieldValidation}</Alert>
}</>
}
</div >
);
}
}

View File

@ -0,0 +1,27 @@
define([], function () {
return {
"PropertyPaneDescription": "This webpart provides easy way to render sharepoint custom list in datatable view with all the necessary features.",
"BasicGroupName": "Group Name",
"DataTableTitleFieldLabel": "Webpart title",
"ConfigureWebpartButtonLabel": "Configure",
"ConfigureWebpartDescription": "Please configure the web part.",
"ListFieldValidation": "Please select the list fields.",
"ListPickerLabel": "Select a list",
"MultiSelectFieldLabel": "Multi select field",
"SortingToggleLabel": "Enable Sort",
"SortByLabel": "Default Sort By",
"SearchingToggleLabel": "Enable Search",
"SearchByLabel": "Default Search By",
"PaginationLabel": "Enable Pagination",
"DownloadAsCSVLabel": "CSV",
"CSVToggleLabel": "Enable CSV",
"PDFToggleLabel": "Enable PDF",
"DownloadAsPDFLabel": "PDF",
"EvenRowColorLabel": "Set Even Row Color",
"OddRowColorLabel": "Set Odd Row Color",
"OrderListItemsLabel": "Ordered List Items",
"ListConfigurationGroupName": "List Configuration",
"SearchAndSortGroupName": "Search and sort",
"AdvancedFeaturesGroupName": "Advanced Features"
}
});

View File

@ -0,0 +1,30 @@
declare interface IReactDatatableWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DataTableTitleFieldLabel: string;
ConfigureWebpartButtonLabel: string;
ConfigureWebpartDescription: string;
ListFieldValidation: string;
ListPickerLabel: string;
MultiSelectFieldLabel: string;
SortingToggleLabel: string;
SortByLabel: string;
SearchingToggleLabel: string;
SearchByLabel: string;
PaginationLabel: string;
DownloadAsCSVLabel: string;
DownloadAsPDFLabel: string;
CSVToggleLabel: string;
PDFToggleLabel: string;
EvenRowColorLabel: string;
OddRowColorLabel: string;
OrderListItemsLabel: string;
ListConfigurationGroupName: string;
SearchAndSortGroupName: string;
AdvancedFeaturesGroupName: string;
}
declare module 'ReactDatatableWebPartStrings' {
const strings: IReactDatatableWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 B

View File

@ -0,0 +1,39 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.3/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
],
"exclude": [
"node_modules",
"lib"
]
}

View File

@ -0,0 +1,30 @@
{
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}