Adding sample to demonstrate sp-pnp-js with SPFx GA (#136)

This commit is contained in:
Patrick Rodgers 2017-03-01 02:35:09 -05:00 committed by Vesa Juvonen
parent 3bef74838a
commit 0e7aabce15
29 changed files with 809 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

32
samples/knockout-sp-pnp-js/.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,14 @@
# Folders
.vscode
coverage
node_modules
sharepoint
src
temp
# Files
*.csproj
.git*
.yo-rc.json
gulpfile.js
tsconfig.json

View File

@ -0,0 +1,8 @@
{
"@microsoft/generator-sharepoint": {
"libraryName": "spfx-sp-pnp-js-example",
"framework": "knockout",
"version": "1.0.0",
"libraryId": "ef1fde11-2cb3-42fc-97f6-5f5c8a7ac63d"
}
}

View File

@ -0,0 +1,45 @@
# Sample showing the use of sp-pnp-js with Knockoutjs
## Summary
This webpart demonstrates how to integrate the sp-pnp-js library into the SharePoint Framework as well as including mock data and simple list I/O.
![Sample of the search web part](./assets/screenshot.png)
## Used SharePoint Framework Version
![drop](https://img.shields.io/badge/drop-GA-green.svg)
## Applies to
* [SharePoint Framework](http://dev.office.com/sharepoint/docs/spfx/sharepoint-framework-overview)
* [Office 365](http://dev.office.com/sharepoint)
## Solution
Solution|Author(s)
--------|---------
spfx-sp-pnp-js-example|Patrick Rodgers ([@mediocrebowler](https://twitter.com/mediocrebowler))
## Version history
Version|Date|Comments
-------|----|--------
0.0.1|February 28, 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.**
---
## Minimal Path to Awesome
- Clone this repo
- In the command line run:
- `npm install`
- `gulp serve`
- Open the *workbench* on your Office 365 Developer tenant
- Test out the web part
## Features
Demonstrates integration of sp-pnp-js with the SharePoint Framework GA release. Also shows the use of mock data in the local workbench.

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

View File

@ -0,0 +1,15 @@
{
"entries": [
{
"entry": "./lib/webparts/spPnPjsExample/SpPnPjsExampleWebPart.js",
"manifest": "./src/webparts/spPnPjsExample/SpPnPjsExampleWebPart.manifest.json",
"outputPath": "./dist/sp-pn-pjs-example.bundle.js"
}
],
"externals": {
"sp-pnp-js": "https://cdnjs.cloudflare.com/ajax/libs/sp-pnp-js/2.0.1/pnp.min.js"
},
"localizedResources": {
"spPnPjsExampleStrings": "webparts/spPnPjsExample/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": "spfx-sp-pnp-js-example",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,10 @@
{
"solution": {
"name": "spfx-sp-pnp-js-example-client-side-solution",
"id": "ef1fde11-2cb3-42fc-97f6-5f5c8a7ac63d",
"version": "1.0.0.0"
},
"paths": {
"zippedPackage": "solution/spfx-sp-pnp-js-example.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,30 @@
{
"name": "spfx-sp-pnp-js-example",
"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/knockout": "3.4.39",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"knockout": "3.4.0",
"sp-pnp-js": "^2.0.1"
},
"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,3 @@
export interface ISpPnPjsExampleWebPartProps {
description: string;
}

View File

@ -0,0 +1,85 @@
import * as ko from 'knockout';
import styles from './SpPnPjsExample.module.scss';
import { ISpPnPjsExampleWebPartProps } from './ISpPnPjsExampleWebPartProps';
import pnp, { List, ListEnsureResult, ItemAddResult } from "sp-pnp-js";
import { ISpPnPjsExampleBindingContext, OrderListItem } from './SpPnPjsExampleViewModel';
export default class MockSpPnPjsExampleViewModel {
public description: KnockoutObservable<string> = ko.observable('');
public newItemTitle: KnockoutObservable<string> = ko.observable('');
public newItemNumber: KnockoutObservable<string> = ko.observable('');
public items: KnockoutObservableArray<OrderListItem> = ko.observableArray([]);
public labelClass: string = styles.label;
public helloWorldClass: string = styles.helloWorld;
public containerClass: string = styles.container;
public rowClass: string = `ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}`;
public buttonClass: string = `ms-Button ${styles.button}`;
constructor(bindings: ISpPnPjsExampleBindingContext) {
this.description(bindings.description);
// When web part description is updated, change this view model's description.
bindings.shouter.subscribe((value: string) => {
this.description(value);
}, this, 'description');
// call the load the items
this.getItems().then(items => {
this.items(items);
});
}
/**
* Gets the items from the list
*/
private getItems(): Promise<OrderListItem[]> {
return Promise.resolve([{
Id: 1,
Title: "Mock Item 1",
OrderNumber: "12345"
},
{
Id: 2,
Title: "Mock Item 2",
OrderNumber: "12345"
},
{
Id: 3,
Title: "Mock Item 3",
OrderNumber: "12345"
}]);
}
/**
* Adds an item to the list
*/
public addItem(): void {
if (this.newItemTitle() !== "" && this.newItemNumber() !== "") {
// add the new item to the display
this.items.push({
Id: this.items.length,
OrderNumber: this.newItemNumber(),
Title: this.newItemTitle(),
});
// clear the form
this.newItemTitle("");
this.newItemNumber("");
}
}
/**
* Deletes an item from the list
*/
public deleteItem(data): void {
if (confirm("Are you sure you want to delete this item?")) {
this.items.remove(data);
}
}
}

View File

@ -0,0 +1,52 @@
.helloWorld {
.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: 3px;
}
.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;
}
}
}

View File

@ -0,0 +1,55 @@
<div data-bind="attr: {class:helloWorldClass}">
<div data-bind="attr: {class:containerClass}">
<div data-bind="attr: {class:rowClass}">
<div class="ms-Grid-col ms-u-sm12">
<span class="ms-font-xl ms-fontColor-white ms-fontWeight-semibold" data-bind="text: description"></span>
</div>
</div>
<div data-bind="attr: {class:rowClass}">
<div class="ms-Grid-col ms-u-sm6">
<span class="ms-font-l ms-fontColor-white ms-fontWeight-semibold">Title</span>
</div>
<div class="ms-Grid-col ms-u-sm6">
<span class="ms-font-l ms-fontColor-white ms-fontWeight-semibold">Order Number</span>
</div>
</div>
<!-- ko foreach: items -->
<div data-bind="attr: {class:$parent.rowClass}">
<div class="ms-Grid-col ms-u-sm6">
<span class="ms-font-l ms-fontColor-white" data-bind="text: Title"></span>
</div>
<div class="ms-Grid-col ms-u-sm5">
<span class="ms-font-l ms-fontColor-white" data-bind="text: OrderNumber"></span>
</div>
<div class="ms-Grid-col ms-u-sm1">
<i class="ms-Icon ms-Icon--Delete" aria-hidden="true" data-bind="click: $parent.deleteItem.bind($parent, $data)"></i>
</div>
</div>
<!-- /ko -->
<div data-bind="attr: {class:rowClass}">
<div class="ms-Grid-col ms-u-sm12">
<span class="ms-font-l ms-fontColor-white ms-fontWeight-semibold">Add New</span>
</div>
</div>
<div data-bind="attr: {class:rowClass}">
<form data-bind="submit: addItem">
<div class="ms-Grid-col ms-u-sm5">
<input class="ms-TextField-field" placeholder="Title" data-bind='value: newItemTitle, valueUpdate: "afterkeydown"' />
</div>
<div class="ms-Grid-col ms-u-sm5">
<input class="ms-TextField-field" placeholder="Order Number" data-bind='value: newItemNumber, valueUpdate: "afterkeydown"'
/>
</div>
<div class="ms-Grid-col ms-u-sm2">
<button class="ms-Button--default ms-Button" type="submit" data-bind="enable: newItemTitle().length > 0 && newItemNumber().length > 0"><span class="ms-Button-label">Add</span></button>
</div>
</form>
</div>
</div>
</div>

View File

@ -0,0 +1,163 @@
import * as ko from 'knockout';
import styles from './SpPnPjsExample.module.scss';
import { ISpPnPjsExampleWebPartProps } from './ISpPnPjsExampleWebPartProps';
import pnp, { List, ListEnsureResult, ItemAddResult } from "sp-pnp-js";
export interface ISpPnPjsExampleBindingContext extends ISpPnPjsExampleWebPartProps {
shouter: KnockoutSubscribable<{}>;
}
/**
* Interface which defines the fields in our list items
*/
export interface OrderListItem {
Id: number;
Title: string;
OrderNumber: string;
}
export default class SpPnPjsExampleViewModel {
public description: KnockoutObservable<string> = ko.observable('');
public newItemTitle: KnockoutObservable<string> = ko.observable('');
public newItemNumber: KnockoutObservable<string> = ko.observable('');
public items: KnockoutObservableArray<OrderListItem> = ko.observableArray([]);
public labelClass: string = styles.label;
public helloWorldClass: string = styles.helloWorld;
public containerClass: string = styles.container;
public rowClass: string = `ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}`;
public buttonClass: string = `ms-Button ${styles.button}`;
constructor(bindings: ISpPnPjsExampleBindingContext) {
this.description(bindings.description);
// When web part description is updated, change this view model's description.
bindings.shouter.subscribe((value: string) => {
this.description(value);
}, this, 'description');
// call the load the items
this.getItems().then(items => {
this.items(items);
});
}
/**
* Gets the items from the list
*/
private getItems(): Promise<OrderListItem[]> {
return this.ensureList().then(list => {
// here we are using the getAs operator so that our returned value will be typed
return list.items.select("Id", "Title", "OrderNumber").getAs<OrderListItem[]>();
});
}
/**
* Adds an item to the list
*/
public addItem(): void {
if (this.newItemTitle() !== "" && this.newItemNumber() !== "") {
this.ensureList().then(list => {
// add the new item to the SharePoint list
list.items.add({
Title: this.newItemTitle(),
OrderNumber: this.newItemNumber(),
}).then((iar: ItemAddResult) => {
// add the new item to the display
this.items.push({
Id: iar.data.Id,
OrderNumber: iar.data.OrderNumber,
Title: iar.data.Title,
});
// clear the form
this.newItemTitle("");
this.newItemNumber("");
});
});
}
}
/**
* Deletes an item from the list
*/
public deleteItem(data): void {
if (confirm("Are you sure you want to delete this item?")) {
this.ensureList().then(list => {
list.items.getById(data.Id).delete().then(_ => {
this.items.remove(data);
});
}).catch((e: Error) => {
alert(`There was an error deleting the item ${e.message}`);
});
}
}
/**
* Ensures the list exists and if it creates it adds some default example data
*/
private ensureList(): Promise<List> {
return new Promise<List>((resolve, reject) => {
// use lists.ensure to always have the list available
pnp.sp.web.lists.ensure("SPPnPJSExampleList").then((ler: ListEnsureResult) => {
if (ler.created) {
// we created the list on this call so let's add a column
ler.list.fields.addText("OrderNumber").then(_ => {
// and we will also add a few items so we can see some example data
// here we use batching
// create a batch
let batch = pnp.sp.web.createBatch();
ler.list.getListItemEntityTypeFullName().then(typeName => {
ler.list.items.inBatch(batch).add({
Title: "Title 1",
OrderNumber: "4826492"
}, typeName);
ler.list.items.inBatch(batch).add({
Title: "Title 2",
OrderNumber: "828475"
}, typeName);
ler.list.items.inBatch(batch).add({
Title: "Title 3",
OrderNumber: "75638923"
}, typeName);
// excute the batched operations
batch.execute().then(_ => {
// all of the items have been added within the batch
resolve(ler.list);
}).catch(e => reject(e));
}).catch(e => reject(e));
}).catch(e => reject(e));
} else {
resolve(ler.list);
}
}).catch(e => reject(e));
});
}
}

View File

@ -0,0 +1,20 @@
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"id": "a7a99322-3bec-4eab-b092-5fd889338a61",
"alias": "SpPnPjsExampleWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"manifestVersion": 2,
"preconfiguredEntries": [{
"groupId": "a7a99322-3bec-4eab-b092-5fd889338a61",
"group": { "default": "Under Development" },
"title": { "default": "SPPnPJSExample" },
"description": { "default": "Example of using sp-pnp-js within SPFx" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "SPPnPJSExample"
}
}]
}

View File

@ -0,0 +1,128 @@
import * as ko from 'knockout';
import {
Environment,
EnvironmentType,
Version
} from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import pnp, { Logger, LogLevel, ConsoleListener } from "sp-pnp-js";
import * as strings from 'spPnPjsExampleStrings';
import SpPnPjsExampleViewModel, { ISpPnPjsExampleBindingContext } from './SpPnPjsExampleViewModel';
import MockSpPnPjsExampleViewModel from './MockSpPnPjsExampleViewModel';
import { ISpPnPjsExampleWebPartProps } from './ISpPnPjsExampleWebPartProps';
let _instance: number = 0;
export default class SpPnPjsExampleWebPart extends BaseClientSideWebPart<ISpPnPjsExampleWebPartProps> {
private _id: number;
private _componentElement: HTMLElement;
private _koDescription: KnockoutObservable<string> = ko.observable('');
/**
* Shouter is used to communicate between web part and view model.
*/
private _shouter: KnockoutSubscribable<{}> = new ko.subscribable();
/**
* Initialize the web part.
*/
protected onInit(): Promise<void> {
this._id = _instance++;
const tagName: string = `ComponentElement-${this._id}`;
this._componentElement = this._createComponentElement(tagName);
this._registerComponent(tagName);
// When web part description is changed, notify view model to update.
this._koDescription.subscribe((newValue: string) => {
this._shouter.notifySubscribers(newValue, 'description');
});
const bindings: ISpPnPjsExampleBindingContext = {
description: this.properties.description,
shouter: this._shouter
};
ko.applyBindings(bindings, this._componentElement);
return super.onInit().then(_ => {
pnp.setup({
spfxContext: this.context
});
// optional, we are setting up the sp-pnp-js logging for debugging
Logger.activeLogLevel = LogLevel.Info;
Logger.subscribe(new ConsoleListener());
});
}
public render(): void {
if (!this.renderedOnce) {
this.domElement.appendChild(this._componentElement);
}
this._koDescription(this.properties.description);
}
private _createComponentElement(tagName: string): HTMLElement {
const componentElement: HTMLElement = document.createElement('div');
componentElement.setAttribute('data-bind', `component: { name: "${tagName}", params: $data }`);
return componentElement;
}
private _registerComponent(tagName: string): void {
if (Environment.type === EnvironmentType.Local) {
console.log("here I am.")
ko.components.register(
tagName,
{
viewModel: MockSpPnPjsExampleViewModel,
template: require('./SpPnPjsExample.template.html'),
synchronous: false
}
);
} else {
ko.components.register(
tagName,
{
viewModel: SpPnPjsExampleViewModel,
template: require('./SpPnPjsExample.template.html'),
synchronous: false
}
);
}
}
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,7 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field"
}
});

View File

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

View File

@ -0,0 +1,9 @@
/// <reference types="mocha" />
import { assert } from 'chai';
describe('SpPnPjsExampleWebPart', () => {
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" />