Merge branch 'dev'

This commit is contained in:
VesaJuvonen 2018-11-09 17:06:21 +02:00
commit f1359c18cc
286 changed files with 87255 additions and 9793 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-RelayService/.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,8 @@
{
"@microsoft/generator-sharepoint": {
"version": "1.4.1",
"libraryName": "react-relay-service",
"libraryId": "3d8b2b8b-cc29-4cf9-b3f1-62edd5ca9b52",
"environment": "spo"
}
}

View File

@ -0,0 +1,26 @@
## react-relay-service
This is where you include your WebPart documentation.
### Building the code
```bash
git clone the repo
npm i
npm i -g gulp
gulp
```
This package produces the following:
* lib/* - intermediate-stage commonjs build artifacts
* dist/* - the bundled script, along with other resources
* deploy/* - all resources which should be uploaded to a CDN.
### Build options
gulp clean - TODO
gulp test - TODO
gulp serve - TODO
gulp bundle - TODO
gulp package-solution - TODO

View File

@ -0,0 +1,18 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"hello-azure-relay-service-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/helloAzureRelayService/HelloAzureRelayServiceWebPart.js",
"manifest": "./src/webparts/helloAzureRelayService/HelloAzureRelayServiceWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"HelloAzureRelayServiceWebPartStrings": "lib/webparts/helloAzureRelayService/loc/{locale}.js"
}
}

View File

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

View File

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

View File

@ -0,0 +1,13 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-relay-service-client-side-solution",
"id": "3d8b2b8b-cc29-4cf9-b3f1-62edd5ca9b52",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true
},
"paths": {
"zippedPackage": "solution/react-relay-service.sppkg"
}
}

View File

@ -0,0 +1,10 @@
{
"$schema": "https://dev.office.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

@ -1,5 +1,5 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/tslint.schema.json",
"$schema": "https://dev.office.com/json-schemas/core-build/tslint.schema.json",
// Display errors as warnings
"displayAsWarning": true,
// The TSLint task may have been configured with several custom lint rules

View File

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

View File

@ -0,0 +1,7 @@
'use strict';
const gulp = require('gulp');
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(gulp);

View File

@ -0,0 +1,33 @@
{
"name": "react-relay-service",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"react": "15.6.2",
"react-dom": "15.6.2",
"@types/react": "15.6.6",
"@types/react-dom": "15.5.6",
"@microsoft/sp-core-library": "~1.4.1",
"@microsoft/sp-webpart-base": "~1.4.1",
"@microsoft/sp-lodash-subset": "~1.4.1",
"@microsoft/sp-office-ui-fabric-core": "~1.4.1",
"@types/webpack-env": ">=1.12.1 <1.14.0"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.4.1",
"@microsoft/sp-module-interfaces": "~1.4.1",
"@microsoft/sp-webpart-workbench": "~1.4.1",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/mocha": ">=2.2.33 <2.6.0",
"ajv": "~5.2.2"
}
}

View File

@ -0,0 +1,26 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "6ddbb470-dced-4bcb-ad30-2956dd91dce9",
"alias": "HelloAzureRelayServiceWebPart",
"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,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "HelloAzureRelayService" },
"description": { "default": "HelloAzureRelayService description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "HelloAzureRelayService"
}
}]
}

View File

@ -0,0 +1,78 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import * as strings from 'HelloAzureRelayServiceWebPartStrings';
import HelloAzureRelayService from './components/HelloAzureRelayService';
import { IHelloAzureRelayServiceProps } from './components/IHelloAzureRelayServiceProps';
import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http';
export interface IHelloAzureRelayServiceWebPartProps {
description: string;
}
export default class HelloAzureRelayServiceWebPart extends BaseClientSideWebPart<IHelloAzureRelayServiceWebPartProps> {
private results: Array<any>;
public onInit(): Promise<any> {
debugger;
const requestHeaders: Headers = new Headers();
requestHeaders.append('Content-type', 'application/json');
requestHeaders.append('Cache-Control', 'no-cache');
const httpClientOptions: IHttpClientOptions = {
headers: requestHeaders
};
const url = "https://relayserviceproxy20180831034031.azurewebsites.net/api/Document?webID=917E82F1-FDF8-4298-AE73-1DD60E244C67";
return this.context.httpClient.get(url, HttpClient.configurations.v1, httpClientOptions).then((response) => {
response.json().then((r => {
debugger;
this.results = r;
}))
}).catch((err) => {
console.log(err);
})
}
public render(): void {
const element: React.ReactElement<IHelloAzureRelayServiceProps> = React.createElement(
HelloAzureRelayService,
{
description: this.properties.description,
documents: this.results
}
);
ReactDom.render(element, this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,74 @@
@import '~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss';
.helloAzureRelayService {
.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 {
@include ms-Grid-row;
@include ms-fontColor-white;
background-color: $ms-color-themeDark;
padding: 20px;
}
.column {
@include ms-Grid-col;
@include ms-lg10;
@include ms-xl8;
@include ms-xlPush2;
@include ms-lgPush1;
}
.title {
@include ms-font-xl;
@include ms-fontColor-white;
}
.subTitle {
@include ms-font-l;
@include ms-fontColor-white;
}
.description {
@include ms-font-l;
@include ms-fontColor-white;
}
.button {
// Our button
text-decoration: none;
height: 32px;
// Primary Button
min-width: 80px;
background-color: $ms-color-themePrimary;
border-color: $ms-color-themePrimary;
color: $ms-color-white;
// 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: $ms-font-size-m;
font-weight: $ms-font-weight-regular;
border-width: 0;
text-align: center;
cursor: pointer;
display: inline-block;
padding: 0 16px;
.label {
font-weight: $ms-font-weight-semibold;
font-size: $ms-font-size-m;
height: 32px;
line-height: 32px;
margin: 0 4px;
vertical-align: top;
display: inline-block;
}
}
}

View File

@ -0,0 +1,32 @@
import * as React from 'react';
import styles from './HelloAzureRelayService.module.scss';
import { IHelloAzureRelayServiceProps } from './IHelloAzureRelayServiceProps';
import { escape } from '@microsoft/sp-lodash-subset';
export default class HelloAzureRelayService extends React.Component<IHelloAzureRelayServiceProps, {}> {
public render(): React.ReactElement<IHelloAzureRelayServiceProps> {
return (
<div className={styles.helloAzureRelayService}>
<div className={styles.container}>
<div className={styles.row}>
<div className={styles.column}>
<span className={styles.title}>Welcome to SharePoint!</span>
<p className={styles.subTitle}>Customize SharePoint experiences using Web Parts.</p>
<p className={styles.description}>{escape(this.props.description)}</p>
<a href="https://aka.ms/spfx" className={styles.button}>
<ul>
{this.props.documents.map((d, i) => {
debugger;
return <li>{d.Title}</li>;
})}
</ul>
</a>
</div>
</div>
</div>
</div>
);
}
}

View File

@ -0,0 +1,4 @@
export interface IHelloAzureRelayServiceProps {
description: string;
documents:Array<any>;
}

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 IHelloAzureRelayServiceWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'HelloAzureRelayServiceWebPartStrings' {
const strings: IHelloAzureRelayServiceWebPartStrings;
export = strings;
}

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
}
}

View File

@ -15,12 +15,12 @@
"text": "dddd, DD MMMM YYYY [at] hh:mm:ss A"
},
{
"key": "MM/d/YYYY HH:mm:ss",
"text": "MM/d/YYYYY HH:mm:ss"
"key": "MM/DD/YYYY HH:mm:ss",
"text": "MM/DD/YYYYY HH:mm:ss"
},
{
"key": "d/M/YYYY HH:mm:ss",
"text": "d/M/YYYYY HH:mm:ss"
"key": "D/M/YYYY HH:mm:ss",
"text": "D/M/YYYYY HH:mm:ss"
}, {
"key": "dddd, MMMM Do, YYYY, h:mm:ss",
"text": "dddd, MMMM Do, YYYY, h:mm:ss"

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,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,11 @@
{
"@microsoft/generator-sharepoint": {
"version": "1.6.0",
"libraryName": "sp-fx-code-splitting",
"libraryId": "e71d24c8-d252-4a08-a8b4-6616ac46775e",
"environment": "spo",
"packageManager": "npm",
"isCreatingSolution": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,43 @@
# Code Splitting in SharePoint Framework
## Summary
Load React components and third party packages on demand in SPFx
![Dynamic Loading of React components](./assets/cs3.gif)
## Used SharePoint Framework Version
![SPFx v1.6.0](https://img.shields.io/badge/SPFx-1.6-green.svg)
## Applies to
* [SharePoint Framework](https:/dev.office.com/sharepoint)
* [Office 365 tenant](https://dev.office.com/sharepoint/docs/spfx/set-up-your-development-environment)
## Solution
Solution|Author(s)
--------|---------
react-components-dynamicloading | Vardhaman Deshpande ([@vrdmn](https://twitter.com/vrdmn) , [vrdmn.com](http://vrdmn.com))
## Version history
Version|Date|Comments
-------|----|--------
1.0|October 09, 2018|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
- Clone this repository
- in the command line run:
- `npm install`
- `gulp serve`
## Features
More details included in this blog post: https://www.vrdmn.com/2018/10/code-splitting-in-sharepoint-framework.html
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-components-dynamicloading" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 478 KiB

View File

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"loader-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/loader/LoaderWebPart.js",
"manifest": "./src/webparts/loader/LoaderWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"LoaderWebPartStrings": "lib/webparts/loader/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": "sp-fx-code-splitting",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,13 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "sp-fx-code-splitting-client-side-solution",
"id": "e71d24c8-d252-4a08-a8b4-6616ac46775e",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true
},
"paths": {
"zippedPackage": "solution/sp-fx-code-splitting.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 -->"
}

View File

@ -0,0 +1,7 @@
'use strict';
const gulp = require('gulp');
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(gulp);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,37 @@
{
"name": "sp-fx-code-splitting",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test",
"prod": "gulp clean && gulp build --ship && gulp bundle -ship && gulp package-solution --ship"
},
"dependencies": {
"@microsoft/sp-core-library": "1.6.0",
"@microsoft/sp-lodash-subset": "1.6.0",
"@microsoft/sp-webpart-base": "1.6.0",
"@types/es6-promise": "0.0.33",
"@types/react": "15.6.6",
"@types/react-dom": "15.5.6",
"@types/webpack-env": "1.13.1",
"moment": "^2.22.2",
"office-ui-fabric-react": "^5.125.0",
"react": "15.6.2",
"react-dom": "15.6.2"
},
"devDependencies": {
"@microsoft/sp-build-web": "1.6.0",
"@microsoft/sp-module-interfaces": "1.6.0",
"@microsoft/sp-webpart-workbench": "1.6.0",
"tslint-microsoft-contrib": "~5.0.0",
"gulp": "~3.9.1",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~5.2.2"
}
}

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,26 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "71039ada-32dc-4509-944c-91d3f1b3ae33",
"alias": "LoaderWebPart",
"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,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "Code Splitting Demo - Loader" },
"description": { "default": "Loader description" },
"officeFabricIconFontName": "Code",
"properties": {
"description": "Loader"
}
}]
}

View File

@ -0,0 +1,31 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart
} from '@microsoft/sp-webpart-base';
import Loader from './components/Loader';
import { ILoaderProps } from './components/ILoaderProps';
export interface ILoaderWebPartProps {
}
export default class LoaderWebPart extends BaseClientSideWebPart<ILoaderWebPartProps> {
public render(): void {
const element: React.ReactElement<ILoaderProps > = React.createElement(
Loader
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
}

View File

@ -0,0 +1,337 @@
import * as React from 'react';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
import {
DetailsList,
DetailsListLayoutMode,
Selection,
SelectionMode,
IColumn
} from 'office-ui-fabric-react/lib/DetailsList';
import { MarqueeSelection } from 'office-ui-fabric-react/lib/MarqueeSelection';
let _items: IDocument[] = [];
const fileIcons: { name: string }[] = [
{ name: 'accdb' },
{ name: 'csv' },
{ name: 'docx' },
{ name: 'dotx' },
{ name: 'mpp' },
{ name: 'mpt' },
{ name: 'odp' },
{ name: 'ods' },
{ name: 'odt' },
{ name: 'one' },
{ name: 'onepkg' },
{ name: 'onetoc' },
{ name: 'potx' },
{ name: 'ppsx' },
{ name: 'pptx' },
{ name: 'pub' },
{ name: 'vsdx' },
{ name: 'vssx' },
{ name: 'vstx' },
{ name: 'xls' },
{ name: 'xlsx' },
{ name: 'xltx' },
{ name: 'xsn' }
];
export interface IDetailsListDocumentsExampleState {
columns: IColumn[];
items: IDocument[];
selectionDetails: string;
isModalSelection: boolean;
isCompactMode: boolean;
}
export interface IDocument {
[key: string]: any;
name: string;
value: string;
iconName: string;
modifiedBy: string;
dateModified: string;
dateModifiedValue: number;
fileSize: string;
fileSizeRaw: number;
}
export class DetailsListDocumentsComponent extends React.Component<any, IDetailsListDocumentsExampleState> {
private _selection: Selection;
constructor(props: any) {
super(props);
// Populate with items for demos.
if (_items.length === 0) {
for (let i = 0; i < 500; i++) {
const randomDate = this._randomDate(new Date(2012, 0, 1), new Date());
const randomFileSize = this._randomFileSize();
const randomFileType = this._randomFileIcon();
let fileName: string = Math.random().toString(36).substring(7);
let userName: string = "Joe Contoso";
fileName = fileName.charAt(0).toUpperCase() + fileName.slice(1).concat(`.${randomFileType.docType}`);
userName = userName
.split(' ')
.map((name: string) => name.charAt(0).toUpperCase() + name.slice(1))
.join(' ');
_items.push({
name: fileName,
value: fileName,
iconName: randomFileType.url,
modifiedBy: userName,
dateModified: randomDate.dateFormatted,
dateModifiedValue: randomDate.value,
fileSize: randomFileSize.value,
fileSizeRaw: randomFileSize.rawSize
});
}
_items = this._sortItems(_items, 'name');
}
const _columns: IColumn[] = [
{
key: 'column1',
name: 'File Type',
headerClassName: 'DetailsListExample-header--FileIcon',
className: 'DetailsListExample-cell--FileIcon',
iconClassName: 'DetailsListExample-Header-FileTypeIcon',
ariaLabel: 'Column operations for File type',
iconName: 'Page',
isIconOnly: true,
fieldName: 'name',
minWidth: 16,
maxWidth: 16,
onColumnClick: this._onColumnClick,
onRender: (item: IDocument) => {
return <img src={item.iconName} className={'DetailsListExample-documentIconImage'} />;
}
},
{
key: 'column2',
name: 'Name',
fieldName: 'name',
minWidth: 210,
maxWidth: 350,
isRowHeader: true,
isResizable: true,
isSorted: true,
isSortedDescending: false,
sortAscendingAriaLabel: 'Sorted A to Z',
sortDescendingAriaLabel: 'Sorted Z to A',
onColumnClick: this._onColumnClick,
data: 'string',
isPadded: true
},
{
key: 'column3',
name: 'Date Modified',
fieldName: 'dateModifiedValue',
minWidth: 70,
maxWidth: 90,
isResizable: true,
onColumnClick: this._onColumnClick,
data: 'number',
onRender: (item: IDocument) => {
return <span>{item.dateModified}</span>;
},
isPadded: true
},
{
key: 'column4',
name: 'Modified By',
fieldName: 'modifiedBy',
minWidth: 70,
maxWidth: 90,
isResizable: true,
isCollapsable: true,
data: 'string',
onColumnClick: this._onColumnClick,
onRender: (item: IDocument) => {
return <span>{item.modifiedBy}</span>;
},
isPadded: true
},
{
key: 'column5',
name: 'File Size',
fieldName: 'fileSizeRaw',
minWidth: 70,
maxWidth: 90,
isResizable: true,
isCollapsable: true,
data: 'number',
onColumnClick: this._onColumnClick,
onRender: (item: IDocument) => {
return <span>{item.fileSize}</span>;
}
}
];
this._selection = new Selection({
onSelectionChanged: () => {
this.setState({
selectionDetails: this._getSelectionDetails(),
isModalSelection: this._selection.isModal()
});
}
});
this.state = {
items: _items,
columns: _columns,
selectionDetails: this._getSelectionDetails(),
isModalSelection: this._selection.isModal(),
isCompactMode: false
};
}
public render() {
const { columns, isCompactMode, items, selectionDetails } = this.state;
return (
<div>
<Toggle
label="Enable Compact Mode"
checked={isCompactMode}
onChanged={this._onChangeCompactMode}
onText="Compact"
offText="Normal"
/>
<Toggle
label="Enable Modal Selection"
checked={this.state.isModalSelection}
onChanged={this._onChangeModalSelection}
onText="Modal"
offText="Normal"
/>
<div>{selectionDetails}</div>
<TextField label="Filter by name:" onChanged={this._onChangeText} />
<MarqueeSelection selection={this._selection}>
<DetailsList
items={items}
compact={isCompactMode}
columns={columns}
selectionMode={this.state.isModalSelection ? SelectionMode.multiple : SelectionMode.none}
setKey="set"
layoutMode={DetailsListLayoutMode.justified}
isHeaderVisible={true}
selection={this._selection}
selectionPreservedOnEmptyClick={true}
onItemInvoked={this._onItemInvoked}
enterModalSelectionOnTouch={true}
/>
</MarqueeSelection>
</div>
);
}
public componentDidUpdate(previousProps: any, previousState: IDetailsListDocumentsExampleState) {
if (previousState.isModalSelection !== this.state.isModalSelection) {
this._selection.setModal(this.state.isModalSelection);
}
}
private _onChangeCompactMode = (checked: boolean): void => {
this.setState({ isCompactMode: checked });
}
private _onChangeModalSelection = (checked: boolean): void => {
this.setState({ isModalSelection: checked });
}
private _onChangeText = (text?: string): void => {
this.setState({ items: text ? _items.filter(i => i.name.toLowerCase().indexOf(text) > -1) : _items });
}
private _onItemInvoked(item: any): void {
alert(`Item invoked: ${item.name}`);
}
private _randomDate(start: Date, end: Date): { value: number; dateFormatted: string } {
const date: Date = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
const dateData = {
value: date.valueOf(),
dateFormatted: date.toLocaleDateString()
};
return dateData;
}
private _randomFileIcon(): { docType: string; url: string } {
const docType: string = fileIcons[Math.floor(Math.random() * fileIcons.length) + 0].name;
return {
docType,
url: `https://static2.sharepointonline.com/files/fabric/assets/brand-icons/document/svg/${docType}_16x1.svg`
};
}
private _randomFileSize(): { value: string; rawSize: number } {
const fileSize: number = Math.floor(Math.random() * 100) + 30;
return {
value: `${fileSize} KB`,
rawSize: fileSize
};
}
private _getSelectionDetails(): string {
const selectionCount = this._selection.getSelectedCount();
switch (selectionCount) {
case 0:
return 'No items selected';
case 1:
return '1 item selected: ' + (this._selection.getSelection()[0] as any).name;
default:
return `${selectionCount} items selected`;
}
}
private _onColumnClick = (ev: React.MouseEvent<HTMLElement>, column: IColumn): void => {
const { columns, items } = this.state;
let newItems: IDocument[] = items.slice();
const newColumns: IColumn[] = columns.slice();
const currColumn: IColumn = newColumns.filter((currCol: IColumn, idx: number) => {
return column.key === currCol.key;
})[0];
newColumns.forEach((newCol: IColumn) => {
if (newCol === currColumn) {
currColumn.isSortedDescending = !currColumn.isSortedDescending;
currColumn.isSorted = true;
} else {
newCol.isSorted = false;
newCol.isSortedDescending = true;
}
});
newItems = this._sortItems(newItems, currColumn.fieldName || '', currColumn.isSortedDescending);
this.setState({
columns: newColumns,
items: newItems
});
}
private _sortItems = (items: IDocument[], sortBy: string, descending = false): IDocument[] => {
if (descending) {
return items.sort((a: IDocument, b: IDocument) => {
if (a[sortBy] < b[sortBy]) {
return 1;
}
if (a[sortBy] > b[sortBy]) {
return -1;
}
return 0;
});
} else {
return items.sort((a: IDocument, b: IDocument) => {
if (a[sortBy] < b[sortBy]) {
return -1;
}
if (a[sortBy] > b[sortBy]) {
return 1;
}
return 0;
});
}
}
}

View File

@ -0,0 +1,2 @@
export interface ILoaderProps {
}

View File

@ -0,0 +1,74 @@
@import '~office-ui-fabric-react/dist/sass/_References.scss';
.loader {
.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 {
@include ms-Grid-row;
@include ms-fontColor-white;
background-color: $ms-color-themeDark;
padding: 20px;
}
.column {
@include ms-Grid-col;
@include ms-lg10;
@include ms-xl8;
@include ms-xlPush2;
@include ms-lgPush1;
}
.title {
@include ms-font-xl;
@include ms-fontColor-white;
}
.subTitle {
@include ms-font-l;
@include ms-fontColor-white;
}
.description {
@include ms-font-l;
@include ms-fontColor-white;
}
.button {
// Our button
text-decoration: none;
height: 32px;
// Primary Button
min-width: 80px;
background-color: $ms-color-themePrimary;
border-color: $ms-color-themePrimary;
color: $ms-color-white;
// 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: $ms-font-size-m;
font-weight: $ms-font-weight-regular;
border-width: 0;
text-align: center;
cursor: pointer;
display: inline-block;
padding: 0 16px;
.label {
font-weight: $ms-font-weight-semibold;
font-size: $ms-font-size-m;
height: 32px;
line-height: 32px;
margin: 0 4px;
vertical-align: top;
display: inline-block;
}
}
}

View File

@ -0,0 +1,62 @@
import * as React from 'react';
import styles from './Loader.module.scss';
import { ILoaderProps } from './ILoaderProps';
import * as ReactDom from 'react-dom';
export interface ILoaderState {
currentTime: string;
}
export default class Loader extends React.Component<ILoaderProps, ILoaderState> {
constructor(props: ILoaderProps) {
super(props);
this.state = {
currentTime: ''
};
}
public render(): React.ReactElement<ILoaderProps> {
return (
<div className={styles.loader}>
<button onClick={this._loadDocumentsClicked.bind(this)}>
Load Documents
</button>
<button onClick={this._loadMomentClicked.bind(this)}>
Load moment js
</button>
<div className="momentContainer">
{this.state.currentTime}
</div>
<div className="detailsContainer">
</div>
</div>
);
}
private async _loadDocumentsClicked() {
const component = await import(
/* webpackChunkName: 'documentdetails-component' */
'./DetailsListComponent' //Custom component from the solution
);
const element: React.ReactElement<any> = React.createElement(
component.DetailsListDocumentsComponent
);
const currentElement = ReactDom.findDOMNode(this);
const detailsContainerElement = currentElement.getElementsByClassName("detailsContainer")[0];
ReactDom.render(element, detailsContainerElement);
}
private async _loadMomentClicked() {
const moment = await import(
/* webpackChunkName: 'moment-js' */
'moment'
);
this.setState({
currentTime: moment().calendar()
});
}
}

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 ILoaderWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'LoaderWebPartStrings' {
const strings: ILoaderWebPartStrings;
export = strings;
}

View File

@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"lib"
]
}

View File

@ -0,0 +1,32 @@
{
"rulesDirectory": [
"tslint-microsoft-contrib"
],
"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
}
}

View File

@ -0,0 +1 @@
.npmrc

View File

@ -0,0 +1,11 @@
{
"@microsoft/generator-sharepoint": {
"isCreatingSolution": true,
"environment": "spo",
"version": "1.7.0",
"libraryName": "react-events-dynamicdata",
"libraryId": "dcd4558f-8ea7-4f77-b494-c2b8a4d51b1d",
"packageManager": "npm",
"componentType": "webpart"
}
}

View File

@ -5,7 +5,7 @@ Sample web parts illustrating using the SharePoint Framework Dynamic data capabi
![Web parts placed on a modern SharePoint page showing information about events](./assets/dynamic-data-webparts.png)
## Used SharePoint Framework Version
![drop](https://img.shields.io/badge/drop-1.5.0--plusbeta-blue.svg)
![drop](https://img.shields.io/badge/drop-1.7.0-green.svg)
## Applies to
@ -22,6 +22,7 @@ react-events-dynamicdata|Waldek Mastykarz (MVP, Rencore, @waldekm)
Version|Date|Comments
-------|----|--------
1.1|November 9, 2018|Updated sample to SPFx v1.7.0
1.0|June 5, 2018|Initial release
## Disclaimer
@ -43,12 +44,14 @@ Version|Date|Comments
* edit a page
* add the three web parts named: _Events_, _Event details_ and _Map_
* configure the _Event details_ web part:
* as _Data source_, choose the _Events_ option
* as _Data property_, choose the _Event_ option
* as _Connect to source_, choose the _Events_ option
* as _Event's properties_, choose the _Event_ option
* configure the _Map_ web part:
* get a Bing maps API key (follow the link in the web part)
* as _Data source_, choose the _Events_ option
* as _Data property_, choose the _Location_ option
* as _Connect to source_, choose the _Events_ option
* as _Event's properties_, choose the _Location_ option
* as _Address_, choose the _address_ option
* as _City_, choose the _city_ option
## Features
@ -59,7 +62,6 @@ Web parts in this solution illustrate the following concepts on top of the Share
* making web part a dynamic data source
* exposing multiple data properties from a single data source
* subscribing to dynamic data source notifications from a web part
* persisting dynamic data subscription information in web part properties
* deploying list instances from a SharePoint Framework solution package
* using [PnPjs](https://github.com/pnp/pnpjs) to retrieve data from a SharePoint list
* using [SharePoint Framework React Controls](https://github.com/SharePoint/sp-dev-fx-controls-react) in web parts

File diff suppressed because it is too large Load Diff

View File

@ -11,27 +11,27 @@
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.5.0-plusbeta",
"@microsoft/sp-lodash-subset": "1.5.0-plusbeta",
"@microsoft/sp-office-ui-fabric-core": "1.5.0-plusbeta",
"@microsoft/sp-webpart-base": "1.5.0-plusbeta",
"@microsoft/sp-core-library": "1.7.0",
"@microsoft/sp-lodash-subset": "1.7.0",
"@microsoft/sp-office-ui-fabric-core": "1.7.0",
"@microsoft/sp-webpart-base": "1.7.0",
"@pnp/common": "^1.1.0",
"@pnp/logging": "^1.1.0",
"@pnp/odata": "^1.1.0",
"@pnp/sp": "^1.1.0",
"@pnp/spfx-controls-react": "^1.4.0",
"@types/es6-promise": "0.0.33",
"@types/react": "15.6.6",
"@types/react-dom": "15.5.6",
"@types/react": "16.4.2",
"@types/react-dom": "16.0.5",
"@types/webpack-env": "1.13.1",
"react": "15.6.2",
"react-dom": "15.6.2"
"react": "16.3.2",
"react-dom": "16.3.2"
},
"devDependencies": {
"@microsoft/generator-sharepoint": "1.5.0",
"@microsoft/sp-build-web": "1.5.0-plusbeta",
"@microsoft/sp-module-interfaces": "1.5.0-plusbeta",
"@microsoft/sp-webpart-workbench": "1.5.0-plusbeta",
"@microsoft/sp-build-web": "1.7.0",
"@microsoft/sp-module-interfaces": "1.7.0",
"@microsoft/sp-webpart-workbench": "1.7.0",
"@microsoft/sp-tslint-rules": "1.7.0",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~5.2.2",

View File

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

View File

@ -20,6 +20,7 @@
"description": { "default": "Shows details of the selected event" },
"officeFabricIconFontName": "CustomList",
"properties": {
"event": {},
"title": "Event details"
}
}]

View File

@ -4,28 +4,24 @@ import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
IPropertyPaneDropdownOption,
PropertyPaneDropdown
IWebPartPropertiesMetadata,
PropertyPaneDynamicFieldSet,
PropertyPaneDynamicField
} from '@microsoft/sp-webpart-base';
import * as strings from 'EventDetailsWebPartStrings';
import { EventDetails, IEventDetailsProps } from './components';
import { IDynamicDataSource } from '@microsoft/sp-dynamic-data';
import { IEvent } from '../../data';
import { DynamicProperty } from '@microsoft/sp-component-base';
/**
* Represents properties of the Event details web part
*/
export interface IEventDetailsWebPartProps {
/**
* The ID of the dynamic data to which the web part is subscribed
* Event to show the details for
*/
propertyId: string;
/**
* The dynamic data source ID to which the web part is subscribed
*/
sourceId: string;
event: DynamicProperty<IEvent>;
/**
* Web part title
*/
@ -37,20 +33,6 @@ export interface IEventDetailsWebPartProps {
* from the connected dynamic data source.
*/
export default class EventDetailsWebPart extends BaseClientSideWebPart<IEventDetailsWebPartProps> {
/**
* The previous ID of the dynamic data source to which the web part is
* subscribed. Used to unsubscribe from previously registered dynamic data
* source notifications after changing web part configuration in the property
* pane.
*/
private _lastSourceId: string = undefined;
/**
* The previous ID of the dynamic data to which the web part is subscribed.
* Used to unsubscribe from previously registered dynamic data source
* notifications after changing web part configuration in the property pane.
*/
private _lastPropertyId: string = undefined;
/**
* Event handler for clicking the Configure button on the Placeholder
*/
@ -58,48 +40,14 @@ export default class EventDetailsWebPart extends BaseClientSideWebPart<IEventDet
this.context.propertyPane.open();
}
protected onInit(): Promise<void> {
// bind render method to the current instance so that it can be correctly
// invoked when dynamic data change notification is triggered
this.render = this.render.bind(this);
return Promise.resolve();
}
public render(): void {
let event: IEvent = undefined;
const needsConfiguration: boolean = !this.properties.sourceId || !this.properties.propertyId;
// subscribe to dynamic data changes notifications
// do this only once the first time the web part is rendered and only,
// if the dynamic data source ID and property ID are provided
if (this.renderedOnce === false && !needsConfiguration) {
try {
this.context.dynamicDataProvider.registerPropertyChanged(this.properties.sourceId, this.properties.propertyId, this.render);
// store current values for the dynamic data source ID and property ID
// so that the web part can unsubscribe from notifications when the
// web part configuration changes
this._lastSourceId = this.properties.sourceId;
this._lastPropertyId = this.properties.propertyId;
}
catch (e) {
this.context.statusRenderer.renderError(this.domElement, `An error has occurred while connecting to the data source. Details: ${e}`);
return;
}
}
// retrieve the current value of dynamic data only if the dynamic data
// source ID and property ID have been provided
if (!needsConfiguration) {
const source: IDynamicDataSource = this.context.dynamicDataProvider.tryGetSource(this.properties.sourceId);
event = source ? source.getPropertyValue(this.properties.propertyId) : undefined;
}
const needsConfiguration: boolean = !this.properties.event.tryGetSource();
const element: React.ReactElement<IEventDetailsProps> = React.createElement(
EventDetails,
{
needsConfiguration: needsConfiguration,
event: event,
event: this.properties.event,
onConfigure: this._onConfigure,
displayMode: this.displayMode,
title: this.properties.title,
@ -116,47 +64,28 @@ export default class EventDetailsWebPart extends BaseClientSideWebPart<IEventDet
return Version.parse('1.0');
}
protected get propertiesMetadata(): IWebPartPropertiesMetadata {
return {
'event': {
dynamicPropertyType: 'object'
}
};
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
// get all available dynamic data sources on the page
const sourceOptions: IPropertyPaneDropdownOption[] =
this.context.dynamicDataProvider.getAvailableSources().map(source => {
return {
key: source.id,
text: source.metadata.title
};
});
const selectedSource: string = this.properties.sourceId;
let propertyOptions: IPropertyPaneDropdownOption[] = [];
if (selectedSource) {
const source: IDynamicDataSource = this.context.dynamicDataProvider.tryGetSource(selectedSource);
if (source) {
// get the list of all properties exposed by the currently selected
// data source
propertyOptions = source.getPropertyDefinitions().map(prop => {
return {
key: prop.id,
text: prop.title
};
});
}
}
return {
pages: [
{
groups: [
{
groupFields: [
PropertyPaneDropdown('sourceId', {
label: strings.SourceIdFieldLabel,
options: sourceOptions,
selectedKey: this.properties.sourceId
}),
PropertyPaneDropdown('propertyId', {
label: strings.PropertyIdFieldLabel,
options: propertyOptions,
selectedKey: this.properties.propertyId
PropertyPaneDynamicFieldSet({
label: 'Select event source',
fields: [
PropertyPaneDynamicField('event', {
label: 'Event source'
})
]
})
]
}
@ -165,27 +94,4 @@ export default class EventDetailsWebPart extends BaseClientSideWebPart<IEventDet
]
};
}
protected onPropertyPaneFieldChanged(propertyPath: string): void {
if (propertyPath === 'sourceId') {
// reset the selected property ID after selecting a different dynamic
// data source
this.properties.propertyId =
this.context.dynamicDataProvider.tryGetSource(this.properties.sourceId).getPropertyDefinitions()[0].id;
}
if (this._lastSourceId && this._lastPropertyId) {
// unsubscribe from the previously registered dynamic data changes
// notifications
this.context.dynamicDataProvider.unregisterPropertyChanged(this._lastSourceId, this._lastPropertyId, this.render);
}
// subscribe to the newly configured dynamic data changes notifications
this.context.dynamicDataProvider.registerPropertyChanged(this.properties.sourceId, this.properties.propertyId, this.render);
// store current values for the dynamic data source ID and property ID
// so that the web part can unsubscribe from notifications when the
// web part configuration changes
this._lastSourceId = this.properties.sourceId;
this._lastPropertyId = this.properties.propertyId;
}
}

View File

@ -4,12 +4,13 @@ import { IEventDetailsProps } from './IEventDetailsProps';
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
import { Label } from 'office-ui-fabric-react/lib/Label';
import { Icon } from 'office-ui-fabric-react/lib/Icon';
import { IEvent } from '../../../data';
import { WebPartTitle } from '@pnp/spfx-controls-react/lib/WebPartTitle';
import { IEvent } from '../../../data';
export class EventDetails extends React.Component<IEventDetailsProps, {}> {
public render(): React.ReactElement<IEventDetailsProps> {
const { needsConfiguration, event, onConfigure, displayMode, title, updateProperty } = this.props;
const eventData: IEvent | undefined = event.tryGetValue();
return (
<div className={styles.eventDetails}>
@ -24,8 +25,8 @@ export class EventDetails extends React.Component<IEventDetailsProps, {}> {
buttonLabel='Configure'
onConfigure={onConfigure} />}
{!needsConfiguration &&
event &&
(!event.name || !event.address) &&
eventData &&
(!eventData.name || !eventData.address) &&
<Placeholder
iconName='Edit'
iconText='Configure your web part'
@ -33,19 +34,19 @@ export class EventDetails extends React.Component<IEventDetailsProps, {}> {
buttonLabel='Configure'
onConfigure={onConfigure} />}
{!needsConfiguration &&
!event &&
!eventData &&
<Placeholder
iconName='CustomList'
iconText='Event details'
description='Select an event' />}
{!needsConfiguration &&
event &&
eventData &&
<ul>
<li><Label>Event name</Label> {event.name}</li>
<li><Label>City</Label> {event.city}</li>
<li><Label>Address</Label> {event.address}</li>
<li><Label>Organizer</Label> <Icon iconName='Mail' /> <a href={`mailto:${event.organizerEmail}`}>{event.organizerName}</a></li>
<li><Label>Date</Label> {new Date(event.date).toLocaleDateString()}</li>
<li><Label>Event name</Label> {eventData.name}</li>
<li><Label>City</Label> {eventData.city}</li>
<li><Label>Address</Label> {eventData.address}</li>
<li><Label>Organizer</Label> <Icon iconName='Mail' /> <a href={`mailto:${eventData.organizerEmail}`}>{eventData.organizerName}</a></li>
<li><Label>Date</Label> {new Date(eventData.date).toLocaleDateString()}</li>
</ul>}
</div>
);

View File

@ -1,4 +1,5 @@
import { DisplayMode } from "@microsoft/sp-core-library";
import { DynamicProperty } from "@microsoft/sp-component-base";
import { IEvent } from "../../../data";
/**
@ -12,7 +13,7 @@ export interface IEventDetailsProps {
/**
* The currently selected event
*/
event: IEvent;
event: DynamicProperty<IEvent>;
/**
* Determines if the web part has been connected to a dynamic data source or
* not

View File

@ -20,6 +20,7 @@
"description": { "default": "Shows upcoming events" },
"officeFabricIconFontName": "Calendar",
"properties": {
"event": "",
"title": "Upcoming events"
}
}]

View File

@ -3,8 +3,7 @@ import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
IPropertyPaneConfiguration
} from '@microsoft/sp-webpart-base';
import * as strings from 'EventsWebPartStrings';
@ -12,7 +11,7 @@ import { Events } from './components';
import { IEventsProps } from './components/IEventsProps';
import { sp } from '@pnp/sp';
import { IDynamicDataController, IDynamicDataPropertyDefinition } from '@microsoft/sp-dynamic-data';
import { IDynamicDataPropertyDefinition, IDynamicDataCallables } from '@microsoft/sp-dynamic-data';
import { IEvent, ILocation } from '../../data';
/**
@ -28,7 +27,7 @@ export interface IEventsWebPartProps {
/**
* Events web part. Shows list of events retrieved from a SharePoint list
*/
export default class EventsWebPart extends BaseClientSideWebPart<IEventsWebPartProps> implements IDynamicDataController {
export default class EventsWebPart extends BaseClientSideWebPart<IEventsWebPartProps> implements IDynamicDataCallables {
/**
* Currently selected event
*/

View File

@ -1,18 +1,18 @@
import * as React from 'react';
import styles from './Events.module.scss';
import { IEventsProps, IEventsState } from '.';
import { IEvent, IEventItem } from "../../../data";
import { IEventItem } from "../../../data";
import { sp } from "@pnp/sp";
import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";
import { ListView, SelectionMode } from "@pnp/spfx-controls-react/lib/ListView";
/**
* Events component
*/
export class Events extends React.Component<IEventsProps, IEventsState> {
constructor() {
super();
constructor(props: IEventsProps) {
super(props);
// set default state
this.state = {
@ -38,31 +38,60 @@ export class Events extends React.Component<IEventsProps, IEventsState> {
loading: true
});
this.setState({
loading: false,
events: [{
name: 'Tampa Home Show',
city: 'Tampa, FL',
address: '333 S Franklin St',
organizerName: 'Grady Archie',
organizerEmail: 'GradyA@contoso.OnMicrosoft.com',
date: '2018-05-29T00:00:00Z'
},
{
name: 'Custom Electronic Design and Installation Association (CEDIA)',
city: 'San Diego, CA',
address: '111 W Harbor Dr',
organizerName: 'Megan Bowen',
organizerEmail: 'MeganB@contoso.OnMicrosoft.com',
date: '2018-06-15T00:00:00Z'
},
{
name: 'Design Automation Conference (DAC)',
city: 'San Francisco, CA',
address: '747 Howard St Fl 5',
organizerName: 'Irvin Sayers',
organizerEmail: 'IrvinSB@contoso.OnMicrosoft.com',
date: '2018-07-05T00:00:00Z'
}],
error: undefined
});
// load information about events from the SharePoint list
sp.web
.getList(`${this.props.siteUrl}/Lists/CompanyEvents`)
.items.getAll()
.then((items: IEventItem[]): void => {
this.setState({
loading: false,
events: items.map(i => {
return {
date: i.PnPEventDate,
name: i.Title,
city: i.PnPCity,
address: i.PnPAddress,
organizerName: i.PnPOrganizerName,
organizerEmail: i.PnPOrganizerEmail
};
})
});
}, (error: any): void => {
// communicate error
this.setState({
loading: false,
error: error
});
});
// sp.web
// .getList(`${this.props.siteUrl}/Lists/CompanyEvents`)
// .items.getAll()
// .then((items: IEventItem[]): void => {
// this.setState({
// loading: false,
// events: items.map(i => {
// return {
// date: i.PnPEventDate,
// name: i.Title,
// city: i.PnPCity,
// address: i.PnPAddress,
// organizerName: i.PnPOrganizerName,
// organizerEmail: i.PnPOrganizerEmail
// };
// })
// });
// }, (error: any): void => {
// // communicate error
// this.setState({
// loading: false,
// error: error
// });
// });
}
public render(): React.ReactElement<IEventsProps> {

View File

@ -1,6 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "44181a37-27e5-4802-8f0b-4f8766792ede",
"id": "44181a37-27e5-4802-8f0b-4f8766792eda",
"alias": "MapWebPart",
"componentType": "WebPart",
@ -22,6 +22,7 @@
"properties": {
"address": "",
"bingMapsApiKey": "",
"city": "",
"title": ""
}
}]

View File

@ -5,16 +5,17 @@ import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneDropdown,
IPropertyPaneDropdownOption,
PropertyPaneLabel,
PropertyPaneLink
PropertyPaneLink,
IPropertyPaneConditionalGroup,
PropertyPaneDynamicFieldSet,
PropertyPaneDynamicField,
IWebPartPropertiesMetadata,
DynamicDataSharedDepth
} from '@microsoft/sp-webpart-base';
import * as strings from 'MapWebPartStrings';
import { Map, IMapProps } from './components';
import { IDynamicDataSource } from '@microsoft/sp-dynamic-data';
import { ILocation } from '../../data';
import { DynamicProperty } from '@microsoft/sp-component-base';
/**
* Map web part properties
@ -23,19 +24,15 @@ export interface IMapWebPartProps {
/**
* The address to display on the map
*/
address: string;
address: DynamicProperty<string>;
/**
* Bing maps API key to use with the Bing maps API
*/
bingMapsApiKey: string;
/**
* The ID of the dynamic data to which the web part is subscribed
* The city where the address is located
*/
propertyId: string;
/**
* The dynamic data source ID to which the web part is subscribed
*/
sourceId: string;
city: DynamicProperty<string>;
/**
* Web part title
*/
@ -48,20 +45,6 @@ export interface IMapWebPartProps {
* source connection.
*/
export default class MapWebPart extends BaseClientSideWebPart<IMapWebPartProps> {
/**
* The previous ID of the dynamic data source to which the web part is
* subscribed. Used to unsubscribe from previously registered dynamic data
* source notifications after changing web part configuration in the property
* pane.
*/
private _lastSourceId: string;
/**
* The previous ID of the dynamic data to which the web part is subscribed.
* Used to unsubscribe from previously registered dynamic data source
* notifications after changing web part configuration in the property pane.
*/
private _lastPropertyId: string;
/**
* Event handler for clicking the Configure button on the Placeholder
*/
@ -69,50 +52,14 @@ export default class MapWebPart extends BaseClientSideWebPart<IMapWebPartProps>
this.context.propertyPane.open();
}
protected onInit(): Promise<void> {
// bind render method to the current instance so that it can be correctly
// invoked when dynamic data change notification is triggered
this.render = this.render.bind(this);
return Promise.resolve();
}
public render(): void {
// subscribe to dynamic data changes notifications
// do this only once the first time the web part is rendered and only,
// if the dynamic data source ID and property ID are provided
if (this.renderedOnce === false) {
if (this.properties.sourceId && this.properties.propertyId) {
try {
this.context.dynamicDataProvider.registerPropertyChanged(this.properties.sourceId, this.properties.propertyId, this.render);
this._lastSourceId = this.properties.sourceId;
this._lastPropertyId = this.properties.propertyId;
}
catch (e) {
this.context.statusRenderer.renderError(this.domElement, `${strings.ErrorText}${e}`);
return;
}
}
}
const dynamicAddress: boolean = !!this.properties.sourceId;
const needsConfiguration: boolean = !this.properties.bingMapsApiKey ||
(!dynamicAddress && !this.properties.address) ||
(dynamicAddress && !this.properties.propertyId);
let address: string = dynamicAddress ? undefined : this.properties.address;
// if the web part is set to retrieve its address from a dynamic data source
// and the dynamic data source has been configured, try to retrieve the
// currently selected location
if (!needsConfiguration && dynamicAddress) {
const source: IDynamicDataSource = this.context.dynamicDataProvider.tryGetSource(this.properties.sourceId);
const location: ILocation = source ? source.getPropertyValue(this.properties.propertyId) : undefined;
if (location) {
address = `${location.address} ${location.city}`;
}
}
// Get the location to show on the map. The location will be retrieved
// either from the event selected in the connected data source or from the
// address entered in web part properties
const address: string | undefined = this.properties.address.tryGetValue();
const city: string | undefined = this.properties.city.tryGetValue();
const needsConfiguration: boolean = !this.properties.bingMapsApiKey || (!address && !this.properties.address.tryGetSource()) ||
(!city && !this.properties.city.tryGetSource());
const element: React.ReactElement<IMapProps> = React.createElement(
Map,
@ -120,8 +67,8 @@ export default class MapWebPart extends BaseClientSideWebPart<IMapWebPartProps>
needsConfiguration: needsConfiguration,
httpClient: this.context.httpClient,
bingMapsApiKey: this.properties.bingMapsApiKey,
dynamicAddress: dynamicAddress,
address: address,
dynamicAddress: !!this.properties.address.tryGetSource(),
address: `${address} ${city}`,
onConfigure: this._onConfigure,
width: this.domElement.clientWidth,
height: this.domElement.clientHeight,
@ -140,39 +87,21 @@ export default class MapWebPart extends BaseClientSideWebPart<IMapWebPartProps>
return Version.parse('1.0');
}
protected get propertiesMetadata(): IWebPartPropertiesMetadata {
return {
// Denote the address web part property as a dynamic property of type
// object to allow the address information to be serialized by
// the SharePoint Framework.
'address': {
dynamicPropertyType: 'string'
},
'city': {
dynamicPropertyType: 'string'
}
} as any as IWebPartPropertiesMetadata;
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
// get all available dynamic data sources on the page
const sourceOptions: IPropertyPaneDropdownOption[] =
this.context.dynamicDataProvider.getAvailableSources().map(source => {
return {
key: source.id,
text: source.metadata.title
};
});
// add an extra option on top to indicate, that the web part should get
// its address information from the web part configuration rather than from
// a dynamic data source
sourceOptions.unshift({
key: '',
text: 'Web part configuration'
});
const selectedSource: string = this.properties.sourceId;
let propertyOptions: IPropertyPaneDropdownOption[] = [];
if (selectedSource) {
const source: IDynamicDataSource = this.context.dynamicDataProvider.tryGetSource(selectedSource);
if (source) {
// get the list of all properties exposed by the currently selected
// data source
propertyOptions = source.getPropertyDefinitions().map(prop => {
return {
key: prop.id,
text: prop.title
};
});
}
}
return {
pages: [
{
@ -190,62 +119,55 @@ export default class MapWebPart extends BaseClientSideWebPart<IMapWebPartProps>
})
]
},
// Web part properties group for specifying the information about
// the address to show on the map.
{
// Primary group is used to provide the address to show on the map
// in a text field in the web part properties
primaryGroup: {
groupName: strings.DataGroupName,
groupFields: [
PropertyPaneTextField('address', {
label: strings.AddressFieldLabel
}),
PropertyPaneTextField('city', {
label: strings.CityFieldLabel
})
]
},
{
groupName: strings.ConnectionGroupName,
// Secondary group is used to retrieve the address from the
// connected dynamic data source
secondaryGroup: {
groupName: strings.DataGroupName,
groupFields: [
PropertyPaneDropdown('sourceId', {
label: strings.SourceIdFieldLabel,
options: sourceOptions,
selectedKey: this.properties.sourceId
PropertyPaneDynamicFieldSet({
label: 'Address',
fields: [
PropertyPaneDynamicField('address', {
label: strings.AddressFieldLabel
}),
PropertyPaneDropdown('propertyId', {
label: strings.PropertyIdFieldLabel,
options: propertyOptions,
selectedKey: this.properties.propertyId
PropertyPaneDynamicField('city', {
label: strings.CityFieldLabel
})
],
sharedConfiguration: {
// because address and city come from the same data source
// the connection can share the selected dynamic property
depth: DynamicDataSharedDepth.Property
}
})
]
}
},
// Show the secondary group only if the web part has been
// connected to a dynamic data source
showSecondaryGroup: !!this.properties.address.tryGetSource()
} as IPropertyPaneConditionalGroup
]
}
]
};
}
protected onPropertyPaneFieldChanged(propertyPath: string): void {
if (!this.properties.sourceId) {
return;
}
if (propertyPath === 'sourceId') {
// reset the selected property ID after selecting a different dynamic
// data source
this.properties.propertyId =
this.context.dynamicDataProvider.tryGetSource(this.properties.sourceId).getPropertyDefinitions()[0].id;
}
if (this._lastSourceId && this._lastPropertyId) {
// unsubscribe from the previously registered dynamic data changes
// notifications
this.context.dynamicDataProvider.unregisterPropertyChanged(this._lastSourceId, this._lastPropertyId, this.render);
}
// subscribe to the newly configured dynamic data changes notifications
this.context.dynamicDataProvider.registerPropertyChanged(this.properties.sourceId, this.properties.propertyId, this.render);
// store current values for the dynamic data source ID and property ID
// so that the web part can unsubscribe from notifications when the
// web part configuration changes
this._lastSourceId = this.properties.sourceId;
this._lastPropertyId = this.properties.propertyId;
}
protected get disableReactivePropertyChanges(): boolean {
// set property changes mode to reactive, so that the Bing Maps API is not
// called on each keystroke when typing in the address to show on the map

View File

@ -1,5 +1,7 @@
import { HttpClient } from "@microsoft/sp-http";
import { DisplayMode } from "@microsoft/sp-core-library";
import { DynamicProperty } from "@microsoft/sp-component-base";
import { ILocation } from "../../../data";
/**
* Map component properties
@ -8,7 +10,7 @@ export interface IMapProps {
/**
* The address to show on the map
*/
address: string;
address: ILocation | string | undefined;
/**
* The Bing maps API key to use when communicating with the Bing maps API
*/

View File

@ -10,8 +10,8 @@ import { WebPartTitle } from '@pnp/spfx-controls-react/lib/WebPartTitle';
* Map component. Renders map for the specified location
*/
export class Map extends React.Component<IMapProps, IMapState> {
constructor() {
super();
constructor(props: IMapProps) {
super(props);
// set default state
this.state = {
@ -30,6 +30,10 @@ export class Map extends React.Component<IMapProps, IMapState> {
return;
}
if (!this.props.address) {
return;
}
// indicate that the component will be loading its data
this.setState({
error: undefined,
@ -68,14 +72,14 @@ export class Map extends React.Component<IMapProps, IMapState> {
});
}
public componentWillMount(): void {
public componentDidMount(): void {
// get coordinates for the current address after the component has been
// instantiated
this._resolveCoordinates();
}
public componentDidUpdate?(prevProps: IMapProps, prevState: IMapState, prevContext: any): void {
if (this.props.address !== prevProps.address) {
public componentDidUpdate?(prevProps: IMapProps, prevState: IMapState, snapshot: any): void {
if (prevProps.address !== this.props.address) {
// get coordinates for the new address
this._resolveCoordinates();
}

View File

@ -3,6 +3,7 @@ define([], function() {
"AddressFieldLabel": "Address",
"BingMapsApiKeyFieldLabel": "Bing Maps API Key",
"BingMapsGroupName": "Bing Maps configuration",
"CityFieldLabel": "City",
"ConnectionGroupName": "Connection",
"DataGroupName": "Data",
"ErrorText": "An error has occurred while connecting to the data source. Details: ",

View File

@ -2,6 +2,7 @@ declare interface IMapWebPartStrings {
AddressFieldLabel: string;
BingMapsApiKeyFieldLabel: string;
BingMapsGroupName: string;
CityFieldLabel: string;
ConnectionGroupName: string;
DataGroupName: string;
ErrorText: string;

View File

@ -9,6 +9,7 @@
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
@ -22,5 +23,12 @@
"dom",
"es2015.collection"
]
}
},
"include": [
"src/**/*.ts"
],
"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
}
}

View File

@ -46,11 +46,11 @@ export default class FileUpload extends React.Component<IFileUploadProps, {}> {
processing: function (file, xhr) {
if(_fileUploadTo=="DocumentLibrary")
myDropzone.options.url = `${_context.pageContext.web.absoluteUrl}/_api/web/Lists/getById('${_listName}')/rootfolder/files/add(overwrite=true,url='${file.name}')`;
myDropzone.options.url = `${_context.pageContext.web.absoluteUrl}/_api/web/Lists/getById('${_parent.props.listName}')/rootfolder/files/add(overwrite=true,url='${file.name}')`;
else
{
if(_itemId)
myDropzone.options.url = `${_context.pageContext.web.absoluteUrl}/_api/web/lists/getById('${_listName}')/items(${_itemId})/AttachmentFiles/add(FileName='${file.name}')`;
myDropzone.options.url = `${_context.pageContext.web.absoluteUrl}/_api/web/lists/getById('${_parent.props.listName}')/items(${_itemId})/AttachmentFiles/add(FileName='${file.name}')`;
else
alert('Item not found or query string value is null!')
}

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-item-History/.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,8 @@
{
"@microsoft/generator-sharepoint": {
"version": "1.4.1",
"libraryName": "react-item-history",
"libraryId": "bc845683-0162-4f0c-b58a-f7f4237a1c46",
"environment": "spo"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

View File

@ -0,0 +1,55 @@
## react-item-history
## Summary
This listview command is used to show the past versions of the selected list item in a grid.
![Item History](./Capture.PNG)
## Used SharePoint Framework Version
![drop](https://img.shields.io/badge/version-GA-green.svg)
## Applies to
* [SharePoint Framework](https:/dev.office.com/sharepoint)
* [Office 365 tenant](https://dev.office.com/sharepoint/docs/spfx/set-up-your-development-environment)
## Prerequisites
> No pre-requisites
## Solution
Solution|Author(s)
--------|---------
react-item-History|Russell Gove
## Version history
Version|Date|Comments
-------|----|--------
1.0|June 15, 2018|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
- Clone this repository
- in the command line run:
- `npm install`
- `gulp serve`
## Features
This listview command is used to show the past versions of the selected list item in a grid.
Add-PnPCustomAction `
-Name 'Item History(GRID)' `
-Title 'Item History(GRID)' `
-Location 'ClientSideExtension.ListViewCommandSet.CommandBar' `
-ClientSideComponentId "f6b9bab2-00a1-4ff1-8bc2-04fea3d64fed" `
-RegistrationType List `
-RegistrationId "101" `
-ClientSideComponentProperties "{}"

View File

@ -0,0 +1,20 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"item-history-command-set": {
"components": [
{
"entrypoint": "./lib/extensions/itemHistory/ItemHistoryCommandSet.js",
"manifest": "./src/extensions/itemHistory/ItemHistoryCommandSet.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"ItemHistoryCommandSetStrings": "lib/extensions/itemHistory/loc/{locale}.js",
}
}

View File

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

View File

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

View File

@ -0,0 +1,13 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-item-history-client-side-solution",
"id": "bc845683-0162-4f0c-b58a-f7f4237a1c46",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true
},
"paths": {
"zippedPackage": "solution/react-item-history.sppkg"
}
}

View File

@ -0,0 +1,29 @@
{
"$schema": "https://dev.office.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"serveConfigurations": {
"default": {
"pageUrl": "https://tronoxglobal.sharepoint.com/sites/GLMasterData/Lists/Account%20Requests/AllItems.aspx",
"customActions": {
"f6b9bab2-00a1-4ff1-8bc2-04fea3d64fed": {
"location": "ClientSideExtension.ListViewCommandSet.CommandBar",
"properties": {
}
}
}
},
"itemHistory": {
"pageUrl": "https://tronoxglobal.sharepoint.com/sites/GLMasterData/Lists/Account%20Requests/AllItems.aspx",
"customActions": {
"f6b9bab2-00a1-4ff1-8bc2-04fea3d64fed": {
"location": "ClientSideExtension.ListViewCommandSet.CommandBar",
"properties": {
}
}
}
}
}
}

View File

@ -0,0 +1,45 @@
{
"$schema": "https://dev.office.com/json-schemas/core-build/tslint.schema.json",
// 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-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
}
}
}

View File

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

View File

@ -0,0 +1,7 @@
'use strict';
const gulp = require('gulp');
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(gulp);

View File

@ -0,0 +1,36 @@
{
"name": "react-item-history",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/decorators": "~1.4.1",
"@microsoft/sp-core-library": "~1.4.1",
"@microsoft/sp-dialog": "~1.4.1",
"@microsoft/sp-listview-extensibility": "~1.4.1",
"@pnp/common": "^1.1.1",
"@pnp/logging": "^1.1.1",
"@pnp/odata": "^1.1.1",
"@pnp/sp": "^1.1.1",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"date-fns": "^1.29.0",
"lodash": "^4.17.10",
"office-ui-fabric-react": "^5.41.2"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.4.1",
"@microsoft/sp-module-interfaces": "~1.4.1",
"@microsoft/sp-webpart-workbench": "~1.4.1",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/mocha": ">=2.2.33 <2.6.0",
"ajv": "~5.2.2"
}
}

View File

@ -0,0 +1,323 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { BaseDialog, IDialogConfiguration } from '@microsoft/sp-dialog';
import { find } from "lodash";
import {
autobind,
PrimaryButton,
Button,
DialogFooter,
DialogContent
} from 'office-ui-fabric-react';
import {
DetailsList, DetailsListLayoutMode, IColumn, SelectionMode, Selection,
ColumnActionsMode
} from "office-ui-fabric-react/lib/DetailsList";
import { parse, format } from "date-fns";
//import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";
import { sp, Fields, Field } from "@pnp/sp";
interface IItemHistoryDialogContentProps {
versions: Array<any>;
columns: Array<string>;
columnDefs: Array<Field>;
close: () => void;
}
class ItemHistoryDialogContent extends React.Component<IItemHistoryDialogContentProps, {}> {
constructor(props) {
super(props);
}
@autobind
public fieldChanged(item?: any, index?: number, column?: IColumn, columnType: string = "Text"): boolean {
if (index < this.props.versions.length - 1) {
switch (columnType) {
case "User":
if (this.props.versions[index][column.fieldName]["LookupId"] !== this.props.versions[index + 1][column.fieldName]["LookupId"]) {
return true;
}
break;
case "LookupMulti":
debugger; // if the length is different true; if the values are diffent fales
if (this.props.versions[index][column.fieldName].length !== this.props.versions[index + 1][column.fieldName].length) {
return true;
}
// length is the same, compare values
for (let i = 0; i < this.props.versions[index][column.fieldName].length; i++) {
if (this.props.versions[index][column.fieldName][i]["LookupId"] !== this.props.versions[index + 1][column.fieldName][i]["LookupId"]) {
return true;
}
}
return false;
default:
if (this.props.versions[index][column.fieldName] !== this.props.versions[index + 1][column.fieldName]) {
return true;
}
break;
}
}
return false;
}
@autobind
public getStyle(item?: any, index?: number, column?: IColumn, columnType: string = "Text"): React.CSSProperties {
if (this.fieldChanged(item, index, column, columnType)) {
return {
backgroundColor: 'yellow',
};
}
return {};
}
@autobind
public onRenderDateTime(item?: any, index?: number, column?: IColumn): any {
return (<div style={this.getStyle(item, index, column)}>
{format(parse(item[column.fieldName]), "DD-MMM-YYYY")}
</div>);
}
@autobind
public onRenderUser(item?: any, index?: number, column?: IColumn): any {
debugger;
return (<div style={this.getStyle(item, index, column, "User")}>
{item[column.fieldName]["LookupValue"]}
</div>);
}
@autobind
public onRenderLookupMulti(item?: any, index?: number, column?: IColumn): any {
debugger;
let display = "";
for (let val of item[column.fieldName]) {
display += val["LookupValue"]+";";
}
return (<div style={this.getStyle(item, index, column, "LookupMulti")}>
{display}
</div>);
}
@autobind
public onRenderChoice(item?: any, index?: number, column?: IColumn): any {
return (<div style={this.getStyle(item, index, column)}>
{item[column.fieldName]}
</div>);
}
@autobind
public onRenderText(item?: any, index?: number, column?: IColumn): any {
debugger;
return (<div style={this.getStyle(item, index, column)}>
{item[column.fieldName]}
</div>);
}
@autobind
public onRenderAttachments(item?: any, index?: number, column?: IColumn): any {
debugger;
let value=item[column.fieldName]?"Yes":"No";
return (<div style={this.getStyle(item, index, column)}>
{value}
</div>);
}
@autobind
public render(): JSX.Element {
debugger;
try {
let testviewFields: Array<IColumn> = this.props.columns.map(cname => {
let columnDef: Field = find(this.props.columnDefs, (colunmDef) => { return colunmDef["InternalName"] === cname; });
switch (columnDef["TypeAsString"]) {
case "Attachments":
return {
name: columnDef["Title"],
isResizable: true,
key: cname,
fieldName: cname,
minWidth: 100,
onRender: this.onRenderAttachments,
};
case "LookupMulti":
return {
name: columnDef["Title"],
isResizable: true,
key: cname,
fieldName: cname,
minWidth: 100,
onRender: this.onRenderLookupMulti,
};
case "DateTime":
return {
name: columnDef["Title"],
isResizable: true,
key: cname,
fieldName: cname,
minWidth: 100,
onRender: this.onRenderDateTime,
};
case "Choice":
return {
name: columnDef["Title"],
isResizable: true,
key: cname,
fieldName: cname,
minWidth: 100,
onRender: this.onRenderChoice
};
case "Lookup":
case "User":
return {
name: columnDef["Title"],
isResizable: true,
key: cname,
fieldName: cname,
minWidth: 100,
onRender: this.onRenderUser
};
case "Text":
case "Note":
return {
name: columnDef["Title"],
isResizable: true,
key: cname,
fieldName: cname,
minWidth: 100,
onRender: this.onRenderText
};
default:
console.log("the colum type " + columnDef["TypeAsString"] + "HAS NOT BEENTESTED, default to text")
return {
name: columnDef["Title"],
isResizable: true,
key: cname,
fieldName: cname,
minWidth: 100,
onRender: this.onRenderText
};
}
});
testviewFields.unshift({
name: "Version",
isResizable: true,
key: "Version",
fieldName: "VersionLabel",
minWidth: 50
}
);
return (<DialogContent
title='Version History(Grid)'
onDismiss={this.props.close}
showCloseButton={true}
>
<DetailsList
items={this.props.versions}
columns={testviewFields}
compact={false}
selectionMode={SelectionMode.none}
key={"ID"}
onShouldVirtualize={() => { return false; }}
layoutMode={DetailsListLayoutMode.justified}
skipViewportMeasures={true}
/>
<DialogFooter>
<Button text='Cancel' title='Cancel' onClick={this.props.close} />
</DialogFooter>
</DialogContent>);
}
catch (e) {
debugger;
}
}
}
export default class ItemHistoryDialog extends BaseDialog {
public itemId: number;
public listId: string;
public viewId: string;
public fieldInterntalNames: Array<string>;
public fieldDefinitions: Array<Field>;
public versionHistory: Array<any>;
public onBeforeOpen(): Promise<void> {
// set up pnp here
// let viewId = this.context.pageContext.legacyPageContext.viewId //get the view id and then used pnp to query view columns/fields as follows,
let batch = sp.createBatch();
// get the fields in the view
sp.web.lists.getById(this.listId).views.getById(this.viewId).fields.inBatch(batch).get().then((results: any) => {
this.fieldInterntalNames = results.Items.map(f => {
switch (f) {
case "LinkTitle":
case "LinkTitleNoMenu":
return "Title";
//break;
default:
return f;
}
});
}).catch((err: any) => {
debugger;
});
// get the field definitions for the list
sp.web.lists.getById(this.listId).fields.inBatch(batch).get().then((results: any) => {
this.fieldDefinitions = results;
}).catch((err: any) => {
debugger;
});
// get the field versionHostory
sp.web.lists.getById(this.listId).items.getById(this.itemId).versions.inBatch(batch).get().then((versions) => {
this.versionHistory = versions;
return;
}).catch((err: any) => {
debugger;
});
return batch.execute().then(e => {
});
}
public render(): void {
ReactDOM.render(<ItemHistoryDialogContent
versions={this.versionHistory}
columns={this.fieldInterntalNames}
columnDefs={this.fieldDefinitions}
close={this.close}
/>, this.domElement);
}
public getConfig(): IDialogConfiguration {
return {
isBlocking: false
};
}
}

View File

@ -0,0 +1,24 @@
{
"$schema": "https://dev.office.com/json-schemas/spfx/command-set-extension-manifest.schema.json",
"id": "f6b9bab2-00a1-4ff1-8bc2-04fea3d64fed",
"alias": "ItemHistoryCommandSet",
"componentType": "Extension",
"extensionType": "ListViewCommandSet",
// 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,
"items": {
"COMMAND_ViewHistory": {
"title": { "default": "Version History (Grid)" },
"type": "command"
}
}
}

View File

@ -0,0 +1,69 @@
import { override } from '@microsoft/decorators';
import { Log } from '@microsoft/sp-core-library';
//import { RowAccessor} from '@microsoft/sp-listview-extensibility';
import {
BaseListViewCommandSet,
Command,
IListViewCommandSetListViewUpdatedParameters,
IListViewCommandSetExecuteEventParameters
} from '@microsoft/sp-listview-extensibility';
import { Dialog } from '@microsoft/sp-dialog';
import { setup as pnpSetup } from "@pnp/common";
import { sp } from "@pnp/sp";
import * as strings from 'ItemHistoryCommandSetStrings';
import ItemHistoryDialog from "./ItemHistory";
import { find } from "lodash";
/**
* If your command set uses the ClientSideComponentProperties JSON input,
* it will be deserialized into the BaseExtension.properties object.
* You can define an interface to describe it.
*/
export interface IItemHistoryCommandSetProperties {
// This is an example; replace with your own properties
}
const LOG_SOURCE: string = 'ItemHistoryCommandSet';
export default class ItemHistoryCommandSet extends BaseListViewCommandSet<IItemHistoryCommandSetProperties> {
public fields: Array<string>;
@override
public onInit(): Promise<void> {
Log.info(LOG_SOURCE, 'Initialized ItemHistoryCommandSet');
pnpSetup({
spfxContext: this.context
});
return Promise.resolve();
}
@override
public onListViewUpdated(event: IListViewCommandSetListViewUpdatedParameters): void {
const compareOneCommand: Command = this.tryGetCommand('COMMAND_1');
if (compareOneCommand) {
// This command should be hidden unless exactly one row is selected.
compareOneCommand.visible = event.selectedRows.length === 1;
}
}
@override
public onExecute(event: IListViewCommandSetExecuteEventParameters): void {
switch (event.itemId) {
case 'COMMAND_ViewHistory':
const dialog: ItemHistoryDialog = new ItemHistoryDialog();
dialog.itemId = event.selectedRows[0].getValueByName("ID");
dialog.listId = this.context.pageContext.list.id.toString();
dialog.viewId = this.context.pageContext.legacyPageContext.viewId;
dialog.show()
.then(() => {
debugger;
})
.catch((e) => {
debugger;
});
break;
default:
throw new Error('Unknown command');
}
}
}

View File

@ -0,0 +1,14 @@
<html>
<body>
<div style='width: 320px; height: 140px;position: relative'>
<img style=' transform:rotate(45deg);transform-origin: bottom; width:30px;margin:auto;left:0;right:0;bottom:0;position:
absolute; ' src='http://tronet.global.tronox.com/_layouts/Tronet/Images/Tronox-logo.png '>
</img>
</div>
<hr>
<img src='http://tronet.global.tronox.com/_layouts/Tronet/Images/Tronox-logo.png '>
</img>
</body>
</html>

View File

@ -0,0 +1 @@
{ '__metadata': { 'type': 'SP.Data.OMSAlertsListItem' }, 'Title': 'Test'}

View File

@ -0,0 +1 @@
[{"Claims":"i:0#.f|membership|russell.gove@tronox.com","DisplayName":"Gove, Russell","Email":"Russell.Gove@tronox.com","Picture":"https://tronoxglobal.sharepoint.com/sites/GLMasterData/_layouts/15/UserPhoto.aspx?Size=L&AccountName=Russell.Gove@tronox.com","Department":"Infrastructure Services","JobTitle":"Sr SharePoint Architect"},{"Claims":"i:0#.f|membership|john.njoroge@tronox.com","DisplayName":"Njoroge, John","Email":"John.Njoroge@tronox.com","Picture":"https://tronoxglobal.sharepoint.com/sites/GLMasterData/_layouts/15/UserPhoto.aspx?Size=L&AccountName=John.Njoroge@tronox.com","Department":"CFO Staff","JobTitle":"Manager Accounting Analysis"}]

View File

@ -0,0 +1,6 @@
define([], function() {
return {
"Command1": "Command 1",
"Command2": "Command 2"
}
});

View File

@ -0,0 +1,9 @@
declare interface IItemHistoryCommandSetStrings {
Command1: string;
Command2: string;
}
declare module 'ItemHistoryCommandSetStrings' {
const strings: IItemHistoryCommandSetStrings;
export = strings;
}

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Some files were not shown because too many files have changed in this diff Show More