React Modern Charts (#154)

* Initial Commit

* Cleaned up unused files
This commit is contained in:
Jeremy Coleman 2017-03-13 03:35:20 -07:00 committed by Vesa Juvonen
parent 087c35671b
commit 794c8fd32f
32 changed files with 1190 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

View File

@ -0,0 +1 @@
* text=auto

View File

@ -0,0 +1,14 @@
# Folders
.vscode
coverage
node_modules
sharepoint
src
temp
# Files
*.csproj
.git*
.yo-rc.json
gulpfile.js
tsconfig.json

View File

@ -0,0 +1,3 @@
{
"vsicons.presets.angular": false
}

View File

@ -0,0 +1,8 @@
{
"@microsoft/generator-sharepoint": {
"libraryName": "modern-charts",
"framework": "react",
"version": "1.0.0",
"libraryId": "f8a78a9a-a93e-4843-89e5-7b871d9b9fa2"
}
}

View File

@ -0,0 +1,80 @@
# Modern Charts
## Summary
This webpart uses the Chart.js library to visualize SharePoint list data.
Built in Chart Types:
-Bar
-Horizontal Bar
-Doughnut
-Line
-Pie
-Polar
-Radar
Each chart is uniquely themed with the built-in color theme generator (color-scheme), continue generating a theme until you find one to your liking.
New charts are populated with Sample data, select a site (or define a custom path with the Other option), a list data source, label column, data column and which column indicates a unique value in your list. See the demo below for an example.
Current Data Functions:
-Average
-Count
-Sum
## Media
![](https://raw.githubusercontent.com/jcoleman-pcprofessional/Modern-Charts/master/assets/modern-chart2.png)
![](https://raw.githubusercontent.com/jcoleman-pcprofessional/Modern-Charts/master/assets/modern-charts.png)
![](https://raw.githubusercontent.com/jcoleman-pcprofessional/Modern-Charts/master/assets/Modern-Charts.gif)
### Working with
Built with SharePoint Framework GA, Office Graph, React and Chart.JS
## Used SharePoint Framework Version
![drop](https://img.shields.io/badge/version-GA-green.svg)
## Applies to
* [SharePoint Framework Developer Preview](http://dev.office.com/sharepoint/docs/spfx/sharepoint-framework-overview)
* [Office 365 developer tenant](http://dev.office.com/sharepoint/docs/spfx/set-up-your-developer-tenant)
## Solution
Solution|Author(s)
--------|---------
react-modern-charts|Jeremy Coleman (MCP, PC Professional, Inc.)
## Version history
Version|Date|Comments
-------|----|--------
1.0.0.0|February 11, 2017|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.**
---
## Prerequisites
- SharePoint Online tenant with Office Graph content enabled
## Minimal Path to Awesome
- clone this repo
- `$ npm i`
- `$ gulp serve`
- if deploying to Office 365, upadte the CDN path in write-manifests.json
## Features
Sample Web Parts in this solution illustrate the following concepts on top of the SharePoint Framework:
- using React for building SharePoint Framework Client-Side Web Parts
- using Office UI Fabric React components for building user experience consistent with SharePoint and Office
- communicating with SharePoint using its REST API
- passing Web Part properties to React components
- building dynamic web part properties
![](https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-modern-charts)

Binary file not shown.

After

Width:  |  Height:  |  Size: 718 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

View File

@ -0,0 +1,13 @@
{
"entries": [
{
"entry": "./lib/webparts/modernCharts/ModernChartsWebPart.js",
"manifest": "./src/webparts/modernCharts/ModernChartsWebPart.manifest.json",
"outputPath": "./dist/modern-charts.bundle.js"
}
],
"externals": {},
"localizedResources": {
"modernChartsStrings": "webparts/modernCharts/loc/{locale}.js"
}
}

View File

@ -0,0 +1,3 @@
{
"deployCdnPath": "temp/deploy"
}

View File

@ -0,0 +1,6 @@
{
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "modern-charts",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,10 @@
{
"solution": {
"name": "modern-charts-client-side-solution",
"id": "f8a78a9a-a93e-4843-89e5-7b871d9b9fa2",
"version": "1.0.0.0"
},
"paths": {
"zippedPackage": "solution/modern-charts.sppkg"
}
}

View File

@ -0,0 +1,9 @@
{
"port": 4321,
"initialPage": "https://localhost:5432/workbench",
"https": true,
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
}

View File

@ -0,0 +1,46 @@
{
// Display errors as warnings
"displayAsWarning": true,
// The TSLint task may have been configured with several custom lint rules
// before this config file is read (for example lint rules from the tslint-microsoft-contrib
// project). If true, this flag will deactivate any of these rules.
"removeExistingRules": true,
// When true, the TSLint task is configured with some default TSLint "rules.":
"useDefaultConfigAsBase": false,
// Since removeExistingRules=true and useDefaultConfigAsBase=false, there will be no lint rules
// which are active, other than the list of rules below.
"lintConfig": {
// Opt-in to Lint rules which help to eliminate bugs in JavaScript
"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-case": true,
"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-unused-imports": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"valid-typeof": true,
"variable-name": false,
"whitespace": false,
"prefer-const": true
}
}
}

View File

@ -0,0 +1,3 @@
{
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,6 @@
'use strict';
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
build.initialize(gulp);

View File

@ -0,0 +1,38 @@
{
"name": "modern-charts",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"@microsoft/sp-client-base": "~1.0.0",
"@microsoft/sp-core-library": "~1.0.0",
"@microsoft/sp-webpart-base": "~1.0.0",
"@types/chart.js": "0.0.14",
"@types/react": "0.14.46",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-test-utils": "0.14.15",
"@types/react-addons-update": "0.14.14",
"@types/react-dom": "0.14.18",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"chart.js": "^2.5.0",
"color-scheme": "0.0.5",
"react": "15.4.2",
"react-chartjs-2": "^2.0.5",
"react-dom": "15.4.2"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.0.0",
"@microsoft/sp-module-interfaces": "~1.0.0",
"@microsoft/sp-webpart-workbench": "~1.0.0",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/mocha": ">=2.2.33 <2.6.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
}
}

View File

@ -0,0 +1,89 @@
export interface Theme {
name: string;
bgColors: Array<string>;
hoverColors: Array<string>;
}
import * as cs from 'color-scheme/lib/color-scheme';
import { MChart } from './IModernChartsWebPartProps';
export default class ChartOptions {
public static _sampleData: Array<number> = [100, 50, 275, 100];
public static _sampleCols: Array<string> = ['UPS','FedEx','USPS','OnTrac'];
public static Options(): Object{
return {
legend: {
display: true,
layout: {
padding: 5
},
position: 'bottom',
labels: {
fontColor: 'rgba(100, 100, 100, 1.0)'
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
};
};
public static Data(chart: MChart) {
return {
labels: chart.labels,
datasets: [{
data: chart.data,
backgroundColor: chart.config.bgColors,
hoverBackgroundColor: chart.config.hoverColors
}]
};
}
public static RandomColors(): Object {
var colors = {bgColors: [], hoverColors: []};
var colorTheme = new cs;
var colorHue = Math.floor(Math.random() * 360);
var colorPalette = colorTheme.from_hue(colorHue).scheme('analogic').variation('default');
colors.bgColors = this.shuffleArray(colorPalette.add_complement(true).colors());
colors.hoverColors = this.shuffleArray((colorPalette.add_complement(true).colors()).splice(6,6));
colors.bgColors.forEach((hex,i)=> { colors.bgColors[i] = '#' + hex; });
colors.hoverColors.forEach((hex,i)=> { colors.hoverColors[i] = '#' + hex; });
return colors;
}
public static SampleData() {
var theme = this.RandomColors();
return {
labels: [
'Red',
'Green',
'Yellow',
'??'
],
datasets: [{
data: [100, 50, 275, 100],
backgroundColor: theme['bgColors'],
hoverBackgroundColor: theme['hoverColors']
}]
};
}
public static shuffleArray(array){
var currentIndex = array.length, temporaryValue, randomIndex ;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
}

View File

@ -0,0 +1,53 @@
export interface ChartConfiguration {
title: string;
description: string;
other: boolean;
dataUrlDisabled: boolean;
colsDisabled: boolean;
listsDisabled: boolean;
type: string;
url: string;
dataurl: string;
list: string;
col1: string;
col2: string;
act: string;
unique: string;
size: number;
options: Object;
columns: Array<any>;
lists: Array<any>;
theme: string;
bgColors: Array<string>;
hoverColors: Array<string>;
}
export interface IModernChartsWebPartProps {
description: string;
numCharts: number;
chartConfig: Array<ChartConfiguration>;
state: boolean;
firstLoad: boolean;
siteOptions: Array<any>;
listOptions: Array<any>;
url: string;
other: boolean;
maxResults: number;
}
export interface IModernChartsProps {
description: string;
title: string;
state: boolean;
config: Object;
context: any;
data: Object;
charts: Array<MChart>;
}
export interface MChart {
data: Array<number>;
labels: Array<string>;
config: ChartConfiguration;
key: number;
}

View File

@ -0,0 +1,24 @@
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"id": "50dbeca0-48ed-4459-800f-b75b13159b21",
"alias": "ModernChartsWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"manifestVersion": 2,
"preconfiguredEntries": [{
"groupId": "50dbeca0-48ed-4459-800f-b75b13159b21",
"group": { "default": "Modern Web Parts" },
"title": { "default": "ModernCharts" },
"description": { "default": "Modern Charts Sample" },
"officeFabricIconFontName": "Chart",
"properties": {
"description": "ModernCharts",
"numCharts": 1,
"state": false,
"maxResults": 25,
"listOptions": []
}
}]
}

View File

@ -0,0 +1,497 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
IWebPartContext,
PropertyPaneSlider,
PropertyPaneDropdown,
IPropertyPaneDropdownOption,
PropertyPaneButton
} from '@microsoft/sp-webpart-base';
import * as strings from 'modernChartsStrings';
import ModernCharts from './components/ModernCharts';
import { IModernChartsProps } from './IModernChartsWebPartProps';
import { MChart } from './IModernChartsWebPartProps';
import { IModernChartsWebPartProps } from './IModernChartsWebPartProps';
import { ChartConfiguration } from './IModernChartsWebPartProps';
import ChartOptions from './ChartOptions';
import {
SPHttpClient,
SPHttpClientResponse
} from '@microsoft/sp-http';
export interface ISPLists {
value: ISPList[];
}
export interface ISPList {
Title: string;
Id: string;
}
export default class ModernChartsWebPart extends BaseClientSideWebPart<IModernChartsWebPartProps> {
private reactCharts: React.ReactElement<IModernChartsProps>;
// Columns Enable / Disable
private colsDisabled: boolean = true;
private listDisabled: boolean = true;
private urlTextDisabled: boolean = true;
//Property Dropdown Options
private _chartThemeOptions: IPropertyPaneDropdownOption[] = [];
private _siteOptions: IPropertyPaneDropdownOption[] = [];
private _dropdownOptions: IPropertyPaneDropdownOption[] = [];
private _columnOptions: IPropertyPaneDropdownOption[] = [];
private _ListColumnOptions: Array<IPropertyPaneDropdownOption> = [];
private _chartSizeOptions: IPropertyPaneDropdownOption[] = [
{key: 3, text:'Small'},
{key: 6, text:'Medium'},
{key: 9, text: 'Medium-Large'},
{key: 12, text: 'Large'}
];
private _chartTypeOptions: IPropertyPaneDropdownOption[] = [
{key: 'bar', text:'Bar'},
{key: 'horizontalbar', text:'Horizontal Bar'},
{key: 'doughnut', text: 'Doughnut'},
{key: 'line', text: 'Line'},
{key: 'pie', text: 'Pie'},
{key: 'polar', text:'Polar'},
{key: 'radar', text:'Radar'}
];
private _chartColActions: IPropertyPaneDropdownOption[] = [
{key: 'average', text: 'Average'},
{key: 'count', text: 'Count'},
{key: 'sum', text: 'Sum'}
];
public constructor(context: IWebPartContext) {
super();
}
private ChartThemes: ChartOptions;
private defaultOptions: Object = {
legend: {
display: false,
layout: {
padding: 10
},
position: 'bottom',
labels: {
fontColor: 'rgba(100, 100, 100, 1.0)'
}
}
};
public defaultChartConfig(chartDesc: string): ChartConfiguration {
var defConfig = {
title: 'Chart Title',
description: chartDesc,
type: 'doughnut',
list: null,
dataurl: this.context.pageContext.web.absoluteUrl,
url: this.context.pageContext.web.absoluteUrl,
other: true,
dataUrlDisabled: true,
colsDisabled: true,
listsDisabled: false,
col1: '',
col2: '',
act: '',
unique: '',
size: 12,
options: ChartOptions.Options(),
columns: [],
lists: this.properties.listOptions,
theme: "Random",
bgColors: ChartOptions.RandomColors()['bgColors'],
hoverColors: ChartOptions.RandomColors()['bgColors']
};
return defConfig;
}
public render(): void {
//Initialize first demo chart
if (!this.properties.state){
this.properties.state = true;
this.properties.firstLoad = true;
this.properties.numCharts = 1;
this.properties.chartConfig = [];
const firstChartConfig = this.defaultChartConfig;
this.properties.chartConfig.push(this.defaultChartConfig('Demo Chart, Edit Web Part to Customize'));
}
this.getChartData();
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
private getChartData(): void{
const _chartData: Array<MChart> = [];
var _count = 0;
this.properties.chartConfig.forEach((cfg,i) => {
if (cfg.list != null){
this.getData(cfg).then((response) => {
const chart = this.calculateData(response.value, cfg);
const _chart: MChart = {data:chart['data'],labels:chart['labels'],config:cfg,key: i};
_chartData[i] = _chart;
if (++_count == this.properties.chartConfig.length){ this.getCharts(_chartData); }
});
} else {
const _chart: MChart = {data:ChartOptions._sampleData,labels:ChartOptions._sampleCols,config:cfg,key: i};
_chartData[i] = _chart;
if (++_count == this.properties.chartConfig.length){ this.getCharts(_chartData); }
}
});
}
private getCharts(charts: Array<MChart>): void{
const chartArea: React.ReactElement<IModernChartsProps> = React.createElement(ModernCharts,{
description: this.properties.description,
title: this.properties.description,
state: this.properties.state,
config: {},
context: this.context,
data: {},
charts: charts
});
ReactDom.render(chartArea,this.domElement);
}
private calculateData(data: Array<Object>,config:ChartConfiguration): Object {
var values: Array<number> = [];
var labels: Object = this.getUnique(data, config);
var dataVal: Array<Array<any>> = this.getValues(data,labels['unique'],config);
switch(config.act) {
case 'sum':
dataVal.forEach((vals,i) => {
values[i] = 0;
vals.forEach((val) => {
values[i]+=parseFloat(val);
});
});
break;
case 'average':
dataVal.forEach((vals,i) => {
values[i] = 0;
vals.forEach((val) => {
values[i]+=parseFloat(val);
});
if (values[i] != 0) {
values[i] = values[i] / vals.length;
}
});
break;
case 'count':
dataVal.forEach((vals) => {
values.push(vals.length);
});
break;
default:
values = [100,250,90,300];
break;
}
return { data:values, labels:labels['labels'] };
}
private getUnique(data: Array<Object>,config:ChartConfiguration): Object {
const chLabels: Object = { unique:[], labels:[] };
data.forEach((item) => {
if (chLabels['unique'].indexOf(item[config.unique]) == -1 && item[config.unique] != null && item[config.unique] != ""){
chLabels['unique'].push(item[config.unique]);
chLabels['labels'].push(item[config.col1]);
}
});
return chLabels;
}
private getValues(data: Array<Object>,unique: Array<string>, config: ChartConfiguration): Array<Array<any>>{
const values: Object = {};
const vals: Array<Array<any>> = [[]];
unique.forEach((col,i) => {
values[col] = [];
vals[i] = [];
data.forEach((item, _i) => {
if (item[config.unique] == col){
vals[i].push(item[config.col2]);
}
});
});
return vals;
}
protected onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any): void {
var pPath = propertyPath;
var pPathInd = propertyPath[12];
if (pPath === 'numCharts' && oldValue != newValue) {
if (this.properties.chartConfig.length < newValue){
while (this.properties.chartConfig.length < newValue) {
this.properties.chartConfig.push(this.defaultChartConfig('Chart Description'));
}
} else if (this.properties.chartConfig.length > newValue) {
while (newValue < this.properties.chartConfig.length) {
this.properties.chartConfig.pop();
}
}
}
if (propertyPath.indexOf('[') != -1) {
pPath = propertyPath.substring(16).replace('\"]','');
}
if (pPath === 'url' && newValue == 'other' && (oldValue != newValue)){
this.urlTextDisabled = false;
this.properties.chartConfig[pPathInd].dataUrlDisabled = false;
this.properties.chartConfig[pPathInd].dataurl = oldValue;
}
if (pPath === 'url' && newValue != 'other' && (oldValue != newValue)){
this.properties.chartConfig[pPathInd].dataurl = newValue;
this.properties.chartConfig[pPathInd].dataUrlDisabled = true;
}
if ( (pPath === 'url' && (newValue != oldValue)) || (pPath === 'dataurl' && (newValue != oldValue)) ){
this._updateListTitles(newValue,this.properties.chartConfig[pPathInd]);
this.properties.chartConfig[pPathInd]['other'] = true;
this.properties.state = true;
}
if (pPath === 'list' && (newValue != oldValue)){
var siteUrl = this.properties.chartConfig[pPathInd]['dataurl'];
this._updateListColumns(siteUrl,newValue,this.properties.chartConfig[pPathInd]);
this.properties.chartConfig[pPathInd].colsDisabled = false;
}
if (pPath === 'theme' && (newValue != oldValue)){
const newTheme = ChartOptions.RandomColors();
this.properties.chartConfig[pPathInd].bgColors = newTheme['bgColors'];
this.properties.chartConfig[pPathInd].hoverColors = newTheme['hoverColors'];
}
this.context.propertyPane.refresh();
this.render();
}
protected onPropertyPaneConfigurationStart(): void {
if (this.properties.firstLoad || this.properties.chartConfig[0].columns.length <= 0 || this.properties.chartConfig[0].list.length <= 0){
this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'First Time Configuration');
this.properties.firstLoad = false;
this._getSiteRootWeb()
.then((response0) => {
this._getSites(response0['Url'])
.then((response) => {
var sites: IPropertyPaneDropdownOption[] = [];
sites.push({key:this.context.pageContext.web.absoluteUrl, text:'This Site'});
sites.push({key:'other', text:'Other Site (Specify Url)'});
for (var _key in response.value) {
if (this.context.pageContext.web.absoluteUrl != response.value[_key]['Url']){
sites.push({key: response.value[_key]['Url'], text: response.value[_key]['Title']});
}
}
this._siteOptions = sites;
this.properties.siteOptions = sites;
this._getListTitles(this.properties.chartConfig[0].dataurl)
.then((response2) => {
this.properties.listOptions = response2.value.map((list: ISPList) => {
return {
key: list.Title,
text: list.Title
};
});
this.properties.chartConfig[0].lists = this.properties.listOptions;
this._getListColumns(this.properties.chartConfig[0].list,this.properties.chartConfig[0].url)
.then((response3) => {
var col: IPropertyPaneDropdownOption[] = [];
for (var __key in response3.value) {
col.push({key: response3.value[__key]['InternalName'], text: response3.value[__key]['Title']});
}
this._columnOptions = col;
this.colsDisabled = false;
this.listDisabled = false;
this.context.propertyPane.refresh();
this.context.statusRenderer.clearLoadingIndicator(this.domElement);
this.render();
});
});
});
});
}
};
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
let columnPropertyOptions: any;
columnPropertyOptions = [
{
groupName: 'General Options',
groupFields: [
PropertyPaneTextField('description', {
label: 'Web Part Title'
}),
PropertyPaneSlider('numCharts', {
label: 'Number of Charts',
min: 1,
max: 10
}),
PropertyPaneSlider('maxResults', {
label: 'Max # of list items',
min: 1,
max: 1000
})
]
}
];
for (var _i = 0; _i < this.properties.numCharts; _i++) {
columnPropertyOptions.push(
{
groupName: "Chart " + (_i + 1) + " Configuration",
groupFields:[
PropertyPaneTextField('chartConfig[' + _i + ']["title"]', {
label: "Chart Title"
}),
PropertyPaneTextField('chartConfig[' + _i + ']["description"]', {
label: "Description "
}),
PropertyPaneDropdown('chartConfig[' + _i + ']["type"]', {
label: 'Chart Type',
options: this._chartTypeOptions
}),
PropertyPaneDropdown('chartConfig[' + _i + ']["size"]', {
label: 'Chart Size',
options: this._chartSizeOptions
}),
PropertyPaneButton('chartConfig[' + _i + ']["theme"]', {
buttonType: 0,
text: 'Generate Theme',
icon: 'Color',
onClick: ((val) => {
return new Date().valueOf();
})
}),
PropertyPaneDropdown('chartConfig[' + _i + ']["url"]', {
label: 'Chart Data Source',
options: this.properties.siteOptions
}),
PropertyPaneTextField('chartConfig[' + _i + ']["dataurl"]', {
label: 'Chart Site Url (i.e. https://contoso.sharepoint.com/path)',
disabled: this.properties.chartConfig[_i].dataUrlDisabled
}),
PropertyPaneDropdown('chartConfig[' + _i + ']["list"]', {
label: 'List Data Source',
options: this.properties.chartConfig[_i].lists,
disabled: this.properties.chartConfig[_i].listsDisabled
}),
PropertyPaneDropdown('chartConfig[' + _i + ']["col1"]', {
label: 'Label Column',
options: this.properties.chartConfig[_i].columns,
disabled: this.properties.chartConfig[_i].colsDisabled
}),
PropertyPaneDropdown('chartConfig[' + _i + ']["col2"]', {
label: 'Data Column',
options: this.properties.chartConfig[_i].columns,
disabled: this.properties.chartConfig[_i].colsDisabled
}),
PropertyPaneDropdown('chartConfig[' + _i + ']["unique"]', {
label: 'Unique Identifier',
options: this.properties.chartConfig[_i].columns,
disabled: this.properties.chartConfig[_i].colsDisabled
}),
PropertyPaneDropdown('chartConfig[' + _i + ']["act"]', {
label: 'Operation',
options: this._chartColActions,
disabled: this.properties.chartConfig[_i].colsDisabled
})
]
});
}
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: columnPropertyOptions
}
]
};
}
protected onPropertyPaneConfigurationComplete(){
this.render();
}
private _getSiteRootWeb(): Promise<string[]> {
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/Site/RootWeb?$select=Title,Url`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
});
}
private _getSites(rootWebUrl: string): Promise<ISPLists> {
return this.context.spHttpClient.get(rootWebUrl + `/_api/web/webs?$select=Title,Url`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
});
}
private _getListTitles(site: string): Promise<ISPLists> {
return this.context.spHttpClient.get(site + `/_api/web/lists?$filter=Hidden eq false and BaseType eq 0`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
});
}
private _getListColumns(listName: string,listsite: string): Promise<any> {
return this.context.spHttpClient.get(listsite + `/_api/web/lists/GetByTitle('${listName}')/Fields?$filter=Hidden eq false and ReadOnlyField eq false and TypeAsString ne 'User' and TypeAsString ne 'Lookup'`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
});
}
public getData(chartConfig: Object){
return this.context.spHttpClient.get(chartConfig['dataurl'] + `/_api/web/lists/GetByTitle(\'${chartConfig['list']}\')/items?$orderby=Id desc&$limit=10&$top=${this.properties.maxResults}`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
});
}
private _updateListTitles(siteUrl: string,_chartConfig: ChartConfiguration): void {
this._getListTitles(siteUrl).then((response) => {
var respLists: IPropertyPaneDropdownOption[] = [];
for (var _key in response.value) {
respLists.push({key: response.value[_key]['Title'], text: response.value[_key]['Title']});
}
this._dropdownOptions = respLists;
_chartConfig.lists = respLists;
this.context.propertyPane.refresh();
}).catch((err) => {
this.context.statusRenderer.clearLoadingIndicator(this.domElement);
this.context.statusRenderer.renderError(this.domElement,"There was an error loading your list, please verify the selected list has Calendar Events or choose a new list.");
});
}
private _updateListColumns(siteUrl: string, listName: string, _chartConfig: ChartConfiguration): void {
this._getListColumns(listName,siteUrl).then((response) => {
var respLists: IPropertyPaneDropdownOption[] = [];
console.log(response.value);
for (var _key in response.value) {
respLists.push({key: response.value[_key]['InternalName'], text: response.value[_key]['Title']});
}
this._columnOptions = respLists;
_chartConfig.columns = respLists;
this.context.propertyPane.refresh();
}).catch((err) => {
this.context.statusRenderer.clearLoadingIndicator(this.domElement);
this.context.statusRenderer.renderError(this.domElement,"There was an error loading your list, please verify the selected list has Calendar Events or choose a new list.");
});
}
}

View File

@ -0,0 +1,15 @@
export interface IModernChartsProps {
description: string;
title: string;
state: boolean;
config: Object;
context: any;
data: Object;
charts: Array<MChart>;
}
export interface MChart {
size: number;
data: Object;
config: Object;
key: number;
}

View File

@ -0,0 +1,117 @@
.charts {
.container {
max-width: 700px;
margin: 0px auto;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.row {
padding: 20px;
}
.listItem {
max-width: 715px;
margin: 5px auto 5px auto;
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.button {
// Our button
text-decoration: none;
height: 32px;
// Primary Button
min-width: 80px;
background-color: #0078d7;
border-color: #0078d7;
color: #ffffff;
// Basic Button
outline: transparent;
position: relative;
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 14px;
font-weight: 400;
border-width: 0;
text-align: center;
cursor: pointer;
display: inline-block;
padding: 0 16px;
.label {
font-weight: 600;
font-size: 14px;
height: 32px;
line-height: 32px;
margin: 0 4px;
vertical-align: top;
display: inline-block;
}
}
}
.chartjs {
height: 100%;
.chartCard{
border-bottom: 2px solid #a6a6a6;
position: relative;
background-color: #f8f8f8;
border-bottom-color: rgb(206, 75, 31);
overflow: hidden;
}
canvas {
display:block;
}
.docContainer {
max-width: none;
min-width: initial;
padding-left: 0px;
padding-right: 0px;
display:inherit;
}
.legend{
display:initial;
}
@media (min-width: 640px){
.docContainer6 {
max-width: 48%;
margin-left: 1%;
margin-right: 1%;
margin-top:5px;
margin-bottom:5px;
}
}
}
#modernChart {
.chartCard{
border-bottom: 2px solid #a6a6a6;
position: relative;
background-color: #f8f8f8;
border-bottom-color: rgb(206, 75, 31);
overflow: hidden;
}
canvas {
display:block;
}
.docContainer {
max-width: none;
min-width: initial;
padding-left: 0px;
padding-right: 0px;
display:inherit;
}
.legend{
display:initial;
}
@media (min-width: 640px){
.docContainer6 {
max-width: 48%;
margin-left: 1%;
margin-right: 1%;
margin-top:5px;
margin-bottom:5px;
}
}
}

View File

@ -0,0 +1,77 @@
import * as React from 'react';
import styles from './ModernCharts.module.scss';
import { IModernChartsProps } from '../IModernChartsWebPartProps';
import { MChart } from '../IModernChartsWebPartProps';
import 'chart.js';
import { Doughnut } from 'react-chartjs-2';
import { Line } from 'react-chartjs-2';
import { Pie } from 'react-chartjs-2';
import { Bar } from 'react-chartjs-2';
import { HorizontalBar } from 'react-chartjs-2';
import { Radar } from 'react-chartjs-2';
import { Polar } from 'react-chartjs-2';
import ChartOptions from '../ChartOptions';
import {
DocumentCard,
DocumentCardTitle,
DocumentCardLocation,
DocumentCardPreview,
IDocumentCardPreviewProps
} from 'office-ui-fabric-react/lib/DocumentCard';
export default class ModernCharts extends React.Component<IModernChartsProps, void> {
public render(): JSX.Element {
const charts: JSX.Element[] = this.props.charts.map((chart: MChart, i: number) => {
return (
<DocumentCard onClickHref='#' className={styles.docContainer + ' ms-Grid-col ms-u-sm12 ms-u-md12 ms-u-lg' + chart.config.size} key={chart.key}>
<div className={styles.chartCard}>
{this.chart(ChartOptions.Data(chart),ChartOptions.Options(),chart.config.type)}
</div>
<DocumentCardLocation location={chart.config.description}/>
<DocumentCardTitle title={chart.config.title}/>
</DocumentCard>
);
});
return (
<div className={styles.chartjs + ' ms-Grid'}>
<div className={'ms-Grid-row'}>
{charts}
</div>
<div style={{clear: 'both'}}/>
</div>
);
}
public chart(data: Object, options: Object, type: string) {
var tChart: any;
switch (type) {
case 'doughnut':
tChart = <Doughnut data={data} options={options} />;
return tChart;
case 'line':
tChart = <Line data={data} options={options} />;
return tChart;
case 'pie':
tChart = <Pie data={data} options={options} />;
return tChart;
case 'bar':
tChart = <Bar data={data} options={options} />;
return tChart;
case 'horizontalbar':
tChart = <HorizontalBar data={data} options={options} />;
return tChart;
case 'radar':
tChart = <Radar data={data} options={options} />;
return tChart;
case 'polar':
tChart = <Polar data={data} options={options} />;
return tChart;
default:
tChart = <Line data={data} options={options} />;
return tChart;
}
}
}

View File

@ -0,0 +1,3 @@
export interface ChartJSProps {
title: string;
}

View File

@ -0,0 +1,7 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field"
}
});

View File

@ -0,0 +1,10 @@
declare interface IModernChartsStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'modernChartsStrings' {
const strings: IModernChartsStrings;
export = strings;
}

View File

@ -0,0 +1,9 @@
/// <reference types="mocha" />
import { assert } from 'chai';
describe('ModernChartsWebPart', () => {
it('should do something', () => {
assert.ok(true);
});
});

View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"types": [
"es6-promise",
"es6-collections",
"webpack-env"
]
}
}

View File

@ -0,0 +1,8 @@
// Type definitions for Microsoft ODSP projects
// Project: ODSP
/* Global definition for UNIT_TEST builds
Code that is wrapped inside an if(UNIT_TEST) {...}
block will not be included in the final bundle when the
--ship flag is specified */
declare const UNIT_TEST: boolean;

View File

@ -0,0 +1 @@
/// <reference path="@ms/odsp.d.ts" />