Merge pull request #1655 from rabwill/sample-react-targetaudience

This commit is contained in:
Hugo Bernier 2020-12-16 23:10:50 -05:00 committed by GitHub
commit 7271ef95f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 18119 additions and 0 deletions

View File

@ -0,0 +1,73 @@
# Target audience generic component
## Summary
Sample web part which uses a Generic React Component which enables it to have Target Audience functionality like what was available in classic web parts.
Targets SharePoint Groups only within the site.
![audience.gif](./assets/audience.gif)
## Compatibility
![SPFx 1.11](https://img.shields.io/badge/spfx-1.11.0-green.svg)
![Node.js LTS 10.x](https://img.shields.io/badge/Node.js-LTS%2010.x-green.svg)
![SharePoint Online](https://img.shields.io/badge/SharePoint-Online-red.svg)
![Teams N/A](https://img.shields.io/badge/Teams-N%2FA-lightgrey.svg)
![Workbench Local | Hosted](https://img.shields.io/badge/Workbench-Local%20%7C%20Hosted-yellow.svg)
## Applies to
* [SharePoint Framework](https://docs.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Office 365 developer tenant](https://docs.microsoft.com/sharepoint/dev/spfx/set-up-your-developer-tenant)
## Solution
Solution|Author(s)
--------|---------
target-audience-generic-component | Rabia Williams([@williamsrabia](https://twitter.com/williamsrabia) , [rabiawilliams.com](https://rabiawilliams.com))
## Version history
Version|Date|Comments
-------|----|--------
1.0|Jan 28, 2020|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`
* Define one or more groups to use as an audience
* Add the web part to a page
* In the web part's properties, select the audience you wish to see the web part
## Features
This Web Part illustrates the following concepts on top of the SharePoint Framework:
* Adding audience targeting to web parts using a generic React component
When the web part is configured, the sample content will only appear to users who belong to the targeted audience.
You can use the `TargetAudience` control (located under `src/common/TargetAudience.tsx`) by inserting one or more in your web parts, specifying the `pageContext` and `groupIds` props, and adding the content you wish to show/hide as children elements of the `TargetAudience` control, as follows:
```tsx
<TargetAudience pageContext={this.props.pageContext} groupIds={this.props.groupIds}>
<div>
Your sample content goes here
</div>
</TargetAudience>
```
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-target-audience"/>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

View File

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

View File

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

View File

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

View File

@ -0,0 +1,23 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "target-audience-generic-component-client-side-solution",
"id": "7647d9a9-6cf7-4d44-b43b-02e3c3fb4d8f",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"isDomainIsolated": false,
"developer": {
"name": "Contoso",
"privacyUrl": "https://contoso.com/privacy",
"termsOfUseUrl": "https://contoso.com/terms-of-use",
"websiteUrl": "https://contoso.com/my-app",
"mpnId": "000000"
}
},
"paths": {
"zippedPackage": "solution/target-audience-generic-component.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 build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,45 @@
{
"name": "target-audience-generic-component",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.11.0",
"@microsoft/sp-lodash-subset": "1.11.0",
"@microsoft/sp-office-ui-fabric-core": "1.11.0",
"@microsoft/sp-property-pane": "1.11.0",
"@microsoft/sp-webpart-base": "1.11.0",
"@pnp/spfx-controls-react": "^2.2.0",
"@pnp/spfx-property-controls": "^1.16.0",
"jquery": "^3.4.1",
"office-ui-fabric-react": "6.214.0",
"react": "16.8.5",
"react-dom": "16.8.5"
},
"resolutions": {
"@types/react": "16.8.8"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-3.3": "0.3.5",
"@microsoft/sp-build-web": "1.11.0",
"@microsoft/sp-module-interfaces": "1.11.0",
"@microsoft/sp-tslint-rules": "1.11.0",
"@microsoft/sp-webpart-workbench": "1.11.0",
"@types/chai": "3.4.34",
"@types/es6-promise": "0.0.33",
"@types/mocha": "2.2.38",
"@types/react": "16.8.8",
"@types/react-dom": "16.8.3",
"@types/webpack-env": "1.13.1",
"ajv": "~5.2.2",
"gulp": "~3.9.1"
}
}

View File

@ -0,0 +1,47 @@
import * as React from "react";
import { IPropertyFieldGroupOrPerson } from "@pnp/spfx-property-controls/lib/PropertyFieldPeoplePicker";
import spservices from "../service/spservices";
import { PageContext } from "@microsoft/sp-page-context";
export interface ITargetAudienceProps {
pageContext:PageContext;
groupIds: IPropertyFieldGroupOrPerson[];
}
export interface ITargetAudienceState {
canView?: boolean;
}
export default class TargetAudience extends React.Component<ITargetAudienceProps, ITargetAudienceState>{
constructor(props: ITargetAudienceProps) {
super(props);
this.state = {
canView: false
} as ITargetAudienceState;
}
public componentDidMount(): void {
//setting the state whether user has permission to view webpart
this.checkUserCanViewWebpart();
}
public render(): JSX.Element {
return (<div>{this.props.groupIds? (this.state.canView ?
this.props.children : ``):this.props.children}</div>);
}
public checkUserCanViewWebpart(): void {
const self = this;
let proms = [];
const errors = [];
const _sv = new spservices();
self.props.groupIds.map((item) => {
proms.push(_sv.isMember(item.fullName, self.props.pageContext.legacyPageContext[`userId`], self.props.pageContext.site.absoluteUrl));
});
Promise.race(
proms.map(p => {
return p.catch(err => {
errors.push(err);
if (errors.length >= proms.length) throw errors;
return Promise.race(null);
});
})).then(val => {
this.setState({ canView: true }); //atleast one promise resolved
});
}
}

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,30 @@
import * as $ from 'jquery';
export default class spservices{
constructor(){
}
/*check if user is a member of the group, using SP rest
*/
public async isMember(groupName: string, userId: string, webAbsoluteUrl): Promise<any> {
var p = new Promise<any>((resolve, reject) => {
$.ajax({
url: webAbsoluteUrl + "/_api/web/sitegroups/getByName('" + groupName + "')/Users?$filter=Id eq " + userId,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: (data) => {
if (data.d.results[0] != undefined) {
resolve(true);
}
else {
reject(false);
}
},
error: (error) => {
reject(false);
},
});
});
return p;
}
}

View File

@ -0,0 +1,28 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "eb85da40-ed83-4f29-b820-52a74b374483",
"alias": "SampleTargetedComponentWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart"],
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "Sample Targeted Component" },
"description": { "default": "Sample Targeted Component description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "Sample Targeted Component",
"groups" : []
}
}]
}

View File

@ -0,0 +1,92 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { DisplayMode, Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as strings from 'SampleTargetedComponentWebPartStrings';
import SampleTargetedComponent from './components/SampleTargetedComponent';
import { ISampleTargetedComponentProps } from './components/ISampleTargetedComponentProps';
import { PropertyFieldPeoplePicker, IPropertyFieldGroupOrPerson, PrincipalType } from '@pnp/spfx-property-controls/lib/PropertyFieldPeoplePicker';
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
export interface ISampleTargetedComponentWebPartProps {
description: string;
groups: IPropertyFieldGroupOrPerson[];
}
export default class SampleTargetedComponentWebPart extends BaseClientSideWebPart<ISampleTargetedComponentWebPartProps> {
public render(): void {
if (
this.displayMode === DisplayMode.Edit &&
this.properties.groups.length === 0
) {
const placeHolderElement = React.createElement(Placeholder, {
iconName: "Edit",
iconText: "Configure your web part",
description: "Please configure the web part.",
buttonLabel: "Configure",
onConfigure: this._onConfigure,
});
ReactDom.render(placeHolderElement, this.domElement);
} else {
const element: React.ReactElement<ISampleTargetedComponentProps> = React.createElement(
SampleTargetedComponent,
{
pageContext: this.context.pageContext,
groupIds: this.properties.groups,
description: this.properties.description,
}
);
ReactDom.render(element, this.domElement);
}
}
protected _onConfigure = () => {
// Context of the web part
this.context.propertyPane.open();
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(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
}),
PropertyFieldPeoplePicker('groups', {
label: 'Target Audience',
initialData: this.properties.groups,
allowDuplicate: false,
principalType: [PrincipalType.SharePoint],
onPropertyChange: this.onPropertyPaneFieldChanged,
context: this.context,
properties: this.properties,
onGetErrorMessage: null,
deferredValidationTime: 0,
key: 'peopleFieldId'
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,5 @@
import { ITargetAudienceProps } from '../../../common/TargetAudience';
export interface ISampleTargetedComponentProps extends ITargetAudienceProps {
description: string;
}

View File

@ -0,0 +1,74 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.sampleTargetedComponent {
.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,37 @@
import * as React from "react";
import styles from "./SampleTargetedComponent.module.scss";
import { ISampleTargetedComponentProps } from "./ISampleTargetedComponentProps";
import TargetAudience, {
ITargetAudienceState
} from "../../../common/TargetAudience";
export interface ISampleTargetedComponentState extends ITargetAudienceState {
description?: string;
}
export default class SampleTargetedComponent extends React.Component<ISampleTargetedComponentProps,ISampleTargetedComponentState> {
constructor(props: ISampleTargetedComponentProps) {
super(props);
this.state = {
description: this.props.description
};
}
public render(): JSX.Element {
return (
<TargetAudience pageContext={this.props.pageContext} groupIds={this.props.groupIds}>
<div className={styles.sampleTargetedComponent}>
<div className={styles.container}>
<div className={styles.row}>
<div className={styles.column}>
<span className={styles.title}>Sample webpart</span>
<p className={styles.subTitle}>{this.state.description}</p>
<a href="https://aka.ms/spfx" className={styles.button}>
<span className={styles.label}>Learn more</span>
</a>
</div>
</div>
</div>
</div>
</TargetAudience>
);
}
}

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

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