Merge pull request #2509 from techienickb/main

Updated react-pages-hierarchy with a Tree View & Added react-group-members sample
This commit is contained in:
Hugo Bernier 2022-04-10 18:27:33 -07:00 committed by GitHub
commit 9e98e89eb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 24363 additions and 15 deletions

33
samples/react-group-members/.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
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,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,16 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"version": "1.14.0",
"libraryName": "react-group-members",
"libraryId": "0b0829f6-4e41-4bf2-9cbe-fd67fca2d34c",
"environment": "spo",
"packageManager": "npm",
"solutionName": "react-group-members",
"solutionShortDescription": "react-group-members description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,55 @@
# react-group-members
## Summary
Uses the MS Graph client to list the members of a group(s) and displays Person Cards, think of it as an automated People Profile native control. Utilizes PnP Property Controls and PnP Placeholder.
## Compatibility
![SPFx 1.14.0](https://img.shields.io/badge/SPFx-1.14.0-green.svg)
![Node.js v14 | v12 | v10](https://img.shields.io/badge/Node.js-v14%20%7C%20v12%20%7C%20v10-green.svg)
![SharePoint Online](https://img.shields.io/badge/SharePoint-Online-yellow.svg)
![Workbench Hosted: Does not work with local workbench](https://img.shields.io/badge/Workbench-Hosted-yellow.svg "Does not work with local workbench")
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/o365devprogram)
## Prerequisites
> Any special pre-requisites?
## Solution
Solution|Author(s)
--------|---------
react-group-members | [Nick Brown](https://github.com/techienickb)
## Version history
Version|Date|Comments
-------|----|--------
1.0|March 30, 2022|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 build`
- `gulp bundle --ship`
- `gulp package-solution --ship`
- Add to AppCatalog and deploy
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit https://aka.ms/spfx-devcontainer for further instructions.

View File

@ -0,0 +1,20 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"group-members-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/groupMembers/GroupMembersWebPart.js",
"manifest": "./src/webparts/groupMembers/GroupMembersWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"GroupMembersWebPartStrings": "lib/webparts/groupMembers/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,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "react-group-members",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,47 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-group-members-client-side-solution",
"id": "0b0829f6-4e41-4bf2-9cbe-fd67fca2d34c",
"title": "Group Members",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "Nick Brown",
"websiteUrl": "https://nbdev.uk",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.14.0"
},
"metadata": {
"shortDescription": {
"default": "List members of a group in people cards"
},
"longDescription": {
"default": "Loads the members of an AAD group and then displays that in a people card"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "List members of a group in the People control view",
"description": "Loads the members of an AAD group and then displays that in a people card. Automated people profiles based on a group",
"id": "a3238ad2-9b27-4970-88a7-cad9bbf08142",
"version": "1.0.0.0"
}
],
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "GroupMember.Read.All"
}
]
},
"paths": {
"zippedPackage": "solution/react-group-members.sppkg"
}
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx"
}

View File

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

16
samples/react-group-members/gulpfile.js vendored Normal file
View File

@ -0,0 +1,16 @@
'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.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));

23474
samples/react-group-members/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
{
"name": "react-group-members",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/microsoft-graph-types": "^2.16.0",
"@microsoft/sp-core-library": "1.14.0",
"@microsoft/sp-lodash-subset": "1.14.0",
"@microsoft/sp-office-ui-fabric-core": "1.14.0",
"@microsoft/sp-property-pane": "1.14.0",
"@microsoft/sp-webpart-base": "1.14.0",
"@pnp/spfx-controls-react": "3.7.2",
"@pnp/spfx-property-controls": "3.6.0",
"office-ui-fabric-react": "^7.184.0",
"react": "16.13.1",
"react-dom": "16.13.1"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-3.9": "^0.4.48",
"@microsoft/sp-build-web": "1.14.0",
"@microsoft/sp-module-interfaces": "1.14.0",
"@microsoft/sp-tslint-rules": "1.14.0",
"@types/react": "16.9.51",
"@types/react-dom": "16.9.8",
"@types/webpack-env": "1.13.1",
"ajv": "~5.2.2",
"gulp": "~4.0.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,23 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "64de6274-1a65-4ef7-a44e-2d8ce48e14ff",
"alias": "GroupMembersWebPart",
"componentType": "WebPart",
"version": "*",
"manifestVersion": 2,
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70",
"group": { "default": "Other" },
"title": { "default": "Group Members" },
"description": { "default": "Group Members description" },
"officeFabricIconFontName": "Group",
"properties": {
"groups": [],
"ignorePeople": []
}
}]
}

View File

@ -0,0 +1,118 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import { IPropertyPaneConfiguration } from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import * as strings from 'GroupMembersWebPartStrings';
import GroupMembers from './components/GroupMembers';
import { IGroupMembersProps } from './components/IGroupMembersProps';
import { IPropertyFieldGroupOrPerson, PrincipalType, PropertyFieldPeoplePicker } from '@pnp/spfx-property-controls';
export interface IGroupMembersWebPartProps {
groups: IPropertyFieldGroupOrPerson[];
ignorePeople: IPropertyFieldGroupOrPerson[];
}
export default class GroupMembersWebPart extends BaseClientSideWebPart<IGroupMembersWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = '';
protected onInit(): Promise<void> {
this._environmentMessage = this._getEnvironmentMessage();
return super.onInit();
}
public render(): void {
const element: React.ReactElement<IGroupMembersProps> = React.createElement(
GroupMembers,
{
groups: this.properties.groups,
ignorePeople: this.properties.ignorePeople,
context: this.context,
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
}
);
ReactDom.render(element, this.domElement);
}
private _getEnvironmentMessage(): string {
if (!!this.context.sdks.microsoftTeams) { // running in Teams
return this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentTeams : strings.AppTeamsTabEnvironment;
}
return this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentSharePoint : strings.AppSharePointEnvironment;
}
protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void {
if (!currentTheme) {
return;
}
this._isDarkTheme = !!currentTheme.isInverted;
const {
semanticColors
} = currentTheme;
this.domElement.style.setProperty('--bodyText', semanticColors.bodyText);
this.domElement.style.setProperty('--link', semanticColors.link);
this.domElement.style.setProperty('--linkHovered', semanticColors.linkHovered);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: ""
},
groups: [
{
groupName: "",
groupFields: [
PropertyFieldPeoplePicker('groups', {
label: "Select a group, please don't select a person",
initialData: this.properties.groups,
allowDuplicate: false,
principalType: [PrincipalType.SharePoint, PrincipalType.Security],
onPropertyChange: this.onPropertyPaneFieldChanged,
context: this.context,
properties: this.properties,
onGetErrorMessage: null,
deferredValidationTime: 0,
key: 'groups'
}),
PropertyFieldPeoplePicker('ignorePeople', {
label: "Select any users you wish to ignore",
initialData: this.properties.ignorePeople,
allowDuplicate: false,
principalType: [PrincipalType.Users],
onPropertyChange: this.onPropertyPaneFieldChanged,
context: this.context,
properties: this.properties,
onGetErrorMessage: null,
deferredValidationTime: 0,
key: 'ignorePeople'
})
]
}
]
}
]
};
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,21 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.groupMembers {
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
display: flex;
flex-wrap: wrap;
gap: 4px;
.personaCard {
width: 250px;
border-radius: 2px;
padding: 4px;
}
.personaCard:hover {
background-color: #f3f3f3;
}
}

View File

@ -0,0 +1,64 @@
import * as React from 'react';
import styles from './GroupMembers.module.scss';
import { IGroupMembersProps } from './IGroupMembersProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { IPropertyFieldGroupOrPerson } from '@pnp/spfx-property-controls';
import { MSGraphClient } from '@microsoft/sp-http';
import * as MicrosoftGraph from "@microsoft/microsoft-graph-types";
import { PersonaSize } from 'office-ui-fabric-react';
import SPFxPeopleCard, { IPeopleCardProps } from './SPFxPeopleCard';
import { Placeholder } from '@pnp/spfx-controls-react';
export default class GroupMembers extends React.Component<IGroupMembersProps, {}> {
public state = { people: [] };
public componentDidMount() {
this.load(this.props.groups, this.props.ignorePeople);
}
public componentWillReceiveProps(nextProps: Readonly<IGroupMembersProps>, nextContext: any): void {
this.load(nextProps.groups, nextProps.ignorePeople);
}
protected load = (groups: IPropertyFieldGroupOrPerson[], ignorePeople: IPropertyFieldGroupOrPerson[]): void => {
this.setState({ people: [] });
this.props.context.msGraphClientFactory.getClient().then((client: MSGraphClient): void => {
groups.forEach(g => {
client.api(`/groups/${g.id.split('|')[2]}/members`).top(999).get((err, res: any) => {
if (res !== null) {
let r: MicrosoftGraph.User[] = res.value;
if (!ignorePeople) ignorePeople = [];
let p: IPeopleCardProps[] = r.filter(u => ignorePeople.filter(i => i.email.toLowerCase() === u.mail.toLowerCase()).length === 0).map(r1 => (
{
primaryText: r1.displayName,
secondaryText: r1.jobTitle,
email: r1.mail ?? r1.userPrincipalName,
serviceScope: this.props.context.serviceScope,
class: styles.personaCard,
size: PersonaSize.size40
} ));
this.setState({ people: this.state.people.concat(p).sort((a, b) => a.primaryText.localeCompare(b.primaryText)) });
}
});
});
});
}
public render(): React.ReactElement<IGroupMembersProps> {
const { people } = this.state;
const { hasTeamsContext } = this.props;
if (people.length === 0) return (
<Placeholder iconName='Edit' iconText='Select the group(s) to use' description='Please configure the group(s) to use' buttonLabel='Configure' onConfigure={() => this.props.context.propertyPane.open()} />
);
return (
<section className={`${styles.groupMembers} ${hasTeamsContext ? styles.teams : ''}`}>
{ people.map(p => (<SPFxPeopleCard {...p} />)) }
</section>
);
}
}

View File

@ -0,0 +1,11 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { IPropertyFieldGroupOrPerson } from "@pnp/spfx-property-controls";
export interface IGroupMembersProps {
groups: IPropertyFieldGroupOrPerson[];
ignorePeople: IPropertyFieldGroupOrPerson[];
context: WebPartContext;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
}

View File

@ -0,0 +1,196 @@
import * as React from "react";
import { SPComponentLoader } from "@microsoft/sp-loader";
import { ServiceScope, Log, Text } from "@microsoft/sp-core-library";
import { Persona, PersonaSize, IPersonaProps, PersonaInitialsColor } from "@microsoft/office-ui-fabric-react-bundle";
export interface IPeopleCardProps {
primaryText: string;
secondaryText?: string;
tertiaryText?: string;
optionalText?: string;
moreDetail?: HTMLElement | string;
email: string;
serviceScope: ServiceScope;
class: string;
size: PersonaSize;
initialsColor?: PersonaInitialsColor;
onCardOpenCallback?: Function;
onCardCloseCallback?: Function;
}
export interface IPeopleCardState {
pictureUrl: string;
personaCard: any;
}
const EXP_SOURCE: string = "SPFxPeopleCardComponent";
const MD5_MODULE_ID: string = "8494e7d7-6b99-47b2-a741-59873e42f16f";
const LIVE_PERSONA_COMPONENT_ID: string = "914330ee-2df2-4f6e-a858-30c23a812408";
const DEFAULT_PERSONA_IMG_HASH: string = "7ad602295f8386b7615b582d87bcc294";
const PROFILE_IMAGE_URL: string = '/_layouts/15/userphoto.aspx?size={0}&accountname={1}';
export default class SPFxPeopleCard extends React.PureComponent<IPeopleCardProps, IPeopleCardState>{
constructor(props: any, context: any) {
super(props, context);
this.state = {
pictureUrl: null,
personaCard: null
};
}
public componentDidMount(): any {
const size = this.getPersonaSize();
const personaImgUrl = Text.format(PROFILE_IMAGE_URL, size, this.props.email);
this.getImageBase64(personaImgUrl).then((url: string) => {
this.getMd5HashForUrl(url).then((newHash)=>{
Log.info(EXP_SOURCE, `${url} h- ${newHash}`);
if (newHash !== DEFAULT_PERSONA_IMG_HASH) {
this.setState({ pictureUrl: "data:image/png;base64," + url });
}
});
});
this.loadSPComponentById(LIVE_PERSONA_COMPONENT_ID).then((sharedLibrary: any) => {
const livePersonaCard: any = sharedLibrary.LivePersonaCard;
this.setState({ personaCard: livePersonaCard });
});
}
private getPersonaSize(){
let size = 'M';
if(this.props.size <= 3){
size = 'S';
}else if(this.props.size <= 6 && this.props.size > 5){
size = 'M';
}
return size;
}
private getMoreDetailElement(){
if(React.isValidElement(this.props.moreDetail)){
return React.createElement('div',
{
className: 'more-persona-details'
}, this.props.moreDetail);
}else{
return React.createElement('div',
{
className: 'more-persona-details',
dangerouslySetInnerHTML: { __html: this.props.moreDetail}
});
}
}
/**
* Display default OfficeUIFabric Persona card if SPFx LivePersonaCard not loaded
*/
private defaultContactCard() {
return React.createElement<IPersonaProps>(Persona, {
primaryText: this.props.primaryText,
secondaryText: this.props.secondaryText,
tertiaryText: this.props.tertiaryText,
optionalText: this.props.optionalText,
imageUrl: this.state.pictureUrl,
initialsColor: this.props.initialsColor ? this.props.initialsColor : "#808080",
className: this.props.class,
size: this.props.size,
imageShouldFadeIn: false,
imageShouldStartVisible: true
}, this.getMoreDetailElement());
}
/**
* Configure SPFx LivePersona card from SPFx component loader
*/
private spfxLiverPersonaCard() {
return React.createElement(this.state.personaCard, {
className: 'people',
clientScenario: "PeopleWebPart",
disableHover: false,
hostAppPersonaInfo: {
PersonaType: "User"
},
serviceScope: this.props.serviceScope,
upn: this.props.email,
onCardOpen: () => {
if(this.props.onCardOpenCallback){
this.props.onCardOpenCallback();
}
},
onCardClose: () => {
if(this.props.onCardCloseCallback){
this.props.onCardCloseCallback();
}
}
}, this.defaultContactCard());
}
/**
* Get MD5Hash for the image url to verify whether user has default image or custom image
* @param url
*/
private getMd5HashForUrl(url: string) {
return new Promise((resolve, reject) => {
this.loadSPComponentById(MD5_MODULE_ID).then((library: any) => {
const md5Hash = library.Md5Hash;
if (md5Hash) {
const convertedHash = md5Hash(url);
resolve(convertedHash);
}
}).catch((error) => {
Log.error(EXP_SOURCE, error, this.props.serviceScope);
resolve(url);
});
});
}
private getImageBase64(pictureUrl: string) {
return new Promise((resolve, reject) => {
let image = new Image();
image.addEventListener("load", () => {
let tempCanvas = document.createElement("canvas");
tempCanvas.width = image.width,
tempCanvas.height = image.height,
tempCanvas.getContext("2d").drawImage(image, 0, 0);
let base64Str;
try {
base64Str = tempCanvas.toDataURL("image/png");
} catch (e) {
return "";
}
base64Str = base64Str.replace(/^data:image\/png;base64,/, "");
resolve(base64Str);
});
image.src = pictureUrl;
});
}
/**
* Load SPFx component by id, SPComponentLoader is used to load the SPFx components
* @param componentId - componentId, guid of the component library
*/
private loadSPComponentById(componentId: string) {
return new Promise((resolve, reject) => {
SPComponentLoader.loadComponentById(componentId).then((component: any) => {
resolve(component);
}).catch((error) => {
Log.error(EXP_SOURCE, error, this.props.serviceScope);
});
});
}
public render(): JSX.Element {
return (
<div className={this.props.class}>
{
this.state.personaCard ? this.spfxLiverPersonaCard() : this.defaultContactCard()
}
</div>
);
}
}

View File

@ -0,0 +1,11 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field",
"AppLocalEnvironmentSharePoint": "The app is running on your local environment as SharePoint web part",
"AppLocalEnvironmentTeams": "The app is running on your local environment as Microsoft Teams app",
"AppSharePointEnvironment": "The app is running on SharePoint page",
"AppTeamsTabEnvironment": "The app is running in Microsoft Teams"
}
});

View File

@ -0,0 +1,14 @@
declare interface IGroupMembersWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
}
declare module 'GroupMembersWebPartStrings' {
const strings: IGroupMembersWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 B

View File

@ -0,0 +1,35 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.9/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": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}

View File

@ -0,0 +1,29 @@
{
"extends": "./node_modules/@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-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}

View File

@ -31,4 +31,7 @@ obj
# Styles Generated Code # Styles Generated Code
*.scss.ts *.scss.ts
release release# .CER Certificates
*.cer
# .PEM Certificates
*.pem

View File

@ -20,7 +20,7 @@ extensions:
This web part allows users to create a faux page hierarchy in their pages library and use it for page-to-page navigation. It will ask you to create a page parent property on first use which is then used by the web part to either show a breadcrumb of the current pages ancestors or buttons for the pages children. This web part allows users to create a faux page hierarchy in their pages library and use it for page-to-page navigation. It will ask you to create a page parent property on first use which is then used by the web part to either show a breadcrumb of the current pages ancestors or buttons for the pages children.
![Page Navigator](./assets/PagesHierarchy.gif) ![Page Navigator](./assets/PagesHierarchy.gif)
![Tree View](./assets/treeview.png)
## Compatibility ## Compatibility
@ -48,6 +48,7 @@ This web part allows users to create a faux page hierarchy in their pages librar
Solution|Author(s) Solution|Author(s)
--------|--------- --------|---------
react-pages-hierarchy|[Bo George](https://github.com/bogeorge) ([@bo_george](https://twitter.com/bo_george)) react-pages-hierarchy|[Bo George](https://github.com/bogeorge) ([@bo_george](https://twitter.com/bo_george))
react-pages-hierarchy|[Nick Brown](https://github.com/techienickb) ([@techienickb](https://twitter.com/techienickb))
## Version history ## Version history
@ -55,6 +56,7 @@ Version|Date|Comments
-------|----|-------- -------|----|--------
1.0|April 30, 2020|Initial release 1.0|April 30, 2020|Initial release
1.2|March 24, 2022|Updated to SPFX v1.14 and PnP packages to v3 1.2|March 24, 2022|Updated to SPFX v1.14 and PnP packages to v3
1.3|March 31, 2322|Added a Tree View
## Minimal path to awesome ## Minimal path to awesome

View File

@ -9,7 +9,7 @@
"This web part allows users to create a faux page hierarchy in their pages library and use it for page-to-page navigation." "This web part allows users to create a faux page hierarchy in their pages library and use it for page-to-page navigation."
], ],
"creationDateTime": "2020-04-30", "creationDateTime": "2020-04-30",
"updateDateTime": "2022-03-24", "updateDateTime": "2022-03-31",
"products": [ "products": [
"SharePoint" "SharePoint"
], ],
@ -63,4 +63,4 @@
} }
] ]
} }
] ]

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@ -4,7 +4,7 @@
"name": "react-pages-hierarchy", "name": "react-pages-hierarchy",
"id": "89758fb6-85e2-4e2b-ac88-4f4e7e5f60cb", "id": "89758fb6-85e2-4e2b-ac88-4f4e7e5f60cb",
"title": "Pages Hierarchy", "title": "Pages Hierarchy",
"version": "1.0.2.0", "version": "1.0.3.0",
"includeClientSideAssets": true, "includeClientSideAssets": true,
"isDomainIsolated": false, "isDomainIsolated": false,
"developer": { "developer": {
@ -39,6 +39,12 @@
"description": "Displays a list of child pages", "description": "Displays a list of child pages",
"id": "ce42762f-a823-4f12-80b2-b708cdebfaa5", "id": "ce42762f-a823-4f12-80b2-b708cdebfaa5",
"version": "1.0.2.0" "version": "1.0.2.0"
},
{
"title": "Tree",
"description": "Displays a list of pages in a tree",
"id": "ce42762f-a823-4f12-80b2-b708cdebfaa6",
"version": "1.0.3.0"
} }
] ]
}, },

View File

@ -5,6 +5,7 @@ import { Action } from "./action";
import { GetRequest } from './getRequest'; import { GetRequest } from './getRequest';
import { IPage } from '@src/models/IPage'; import { IPage } from '@src/models/IPage';
import { WebPartContext } from '@microsoft/sp-webpart-base'; import { WebPartContext } from '@microsoft/sp-webpart-base';
import { INavLink } from 'office-ui-fabric-react';
// state that we track // state that we track
interface PagesState { interface PagesState {
@ -12,6 +13,7 @@ interface PagesState {
userCanManagePages: boolean; userCanManagePages: boolean;
ancestorPages: IPage[]; ancestorPages: IPage[];
childrenPages: IPage[]; childrenPages: IPage[];
tree: INavLink | null;
getRequest: GetRequest; getRequest: GetRequest;
} }
@ -27,7 +29,8 @@ interface PageApi {
interface PageTreePayloadAction extends Action { interface PageTreePayloadAction extends Action {
payload: { payload: {
childgrenPages: IPage[], childgrenPages: IPage[],
ancestorPages: IPage[] ancestorPages: IPage[],
tree: INavLink
}; };
} }
interface ParentPageColumnExistAction extends Action { interface ParentPageColumnExistAction extends Action {
@ -56,6 +59,7 @@ function pagesReducer(state: PagesState, action: Action): PagesState {
...state, ...state,
childrenPages: arrayAction.payload.childgrenPages, childrenPages: arrayAction.payload.childgrenPages,
ancestorPages: arrayAction.payload.ancestorPages, ancestorPages: arrayAction.payload.ancestorPages,
tree: arrayAction.payload.tree,
getRequest: { isLoading: false, hasError: false, errorMessage: "" } getRequest: { isLoading: false, hasError: false, errorMessage: "" }
}; };
case ActionTypes.GET_PAGES_ERRORED: case ActionTypes.GET_PAGES_ERRORED:
@ -84,13 +88,14 @@ function pagesReducer(state: PagesState, action: Action): PagesState {
} }
} }
export function usePageApi(currentPageId: number, pageEditFinished: boolean, context: WebPartContext): PageApi { export function usePageApi(currentPageId: number, pageEditFinished: boolean, context: WebPartContext, treeTop: number, treeExpandTo: number): PageApi {
const [pagesState, pagesDispatch] = useReducer(pagesReducer, { const [pagesState, pagesDispatch] = useReducer(pagesReducer, {
parentPageColumnExists: true, parentPageColumnExists: true,
userCanManagePages: false, userCanManagePages: false,
ancestorPages: [] = [], ancestorPages: [] = [],
childrenPages: [] = [], childrenPages: [] = [],
getRequest: { isLoading: false, hasError: false, errorMessage: "" }, getRequest: { isLoading: false, hasError: false, errorMessage: "" },
tree: null
}); });
const sp = spfi().using(SPFx(context)); const sp = spfi().using(SPFx(context));
@ -143,11 +148,12 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
const ancestorPages: IPage[] = buildPageAncestors(pages, currentPageId).reverse(); const ancestorPages: IPage[] = buildPageAncestors(pages, currentPageId).reverse();
const childrenPages: IPage[] = buildPageChildren(pages, currentPageId); const childrenPages: IPage[] = buildPageChildren(pages, currentPageId);
const treeLink: INavLink = buildHierarchy(pages);
// dispatch the GET_ALL action // dispatch the GET_ALL action
pagesDispatch({ pagesDispatch({
type: ActionTypes.GET_PAGES, type: ActionTypes.GET_PAGES,
payload: { childgrenPages: childrenPages, ancestorPages: ancestorPages }, payload: { childgrenPages: childrenPages, ancestorPages: ancestorPages, tree: treeLink },
} as PageTreePayloadAction); } as PageTreePayloadAction);
} }
@ -247,6 +253,18 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
return childPages; return childPages;
} }
function buildHierarchy(allPages: IPage[]): INavLink {
function recurse(id: number, l: number): INavLink {
var item: IPage = allPages.filter(i => i.id === id)[0];
var links: INavLink[] = [];
links = links.concat(allPages.filter(i => i.parentPageId === id).map(it => recurse(it.id, (l+1))));
return { name: item.title, url: item.url, key: item.id.toString(), links: links, isExpanded: treeExpandTo >= l };
}
return recurse(treeTop, 1);
}
const addParentPageField = () => { const addParentPageField = () => {
addParentPageFieldToSitePages(); addParentPageFieldToSitePages();
}; };
@ -262,6 +280,7 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
hasError: pagesState.getRequest.hasError, hasError: pagesState.getRequest.hasError,
errorMessage: pagesState.getRequest.errorMessage errorMessage: pagesState.getRequest.errorMessage
}, },
tree: pagesState.tree
}, },
addParentPageField addParentPageField
}; };

View File

@ -1,7 +1,8 @@
export enum PagesToDisplay { export enum PagesToDisplay {
None = 'none', None = 'none',
Ancestors = 'ancestors', Ancestors = 'ancestors',
Children = 'children' Children = 'children',
Tree = 'tree'
} }
export enum RenderDirection { export enum RenderDirection {

View File

@ -4,4 +4,6 @@ export default interface IPageHierarchyWebPartProps {
title: string; title: string;
debugPageId?: number; debugPageId?: number;
pagesToDisplay: PagesToDisplay; pagesToDisplay: PagesToDisplay;
treeFrom: number;
treeExpandTo: number
} }

View File

@ -24,7 +24,9 @@
}, },
"officeFabricIconFontName": "CompassNW", "officeFabricIconFontName": "CompassNW",
"properties": { "properties": {
"pagesToDisplay": "none" "pagesToDisplay": "none",
"treeFrom": 1,
"treeExpandTo": 10
} }
} }
] ]

View File

@ -54,7 +54,9 @@ export default class PageHierarchyWebPart extends BaseWebPart<IPageHierarchyWebP
updateTitle: (t) => { this.properties.title = t; this.render(); }, updateTitle: (t) => { this.properties.title = t; this.render(); },
onConfigure: () => { this.onConfigure(); }, onConfigure: () => { this.onConfigure(); },
pageEditFinished: this.pageEditFinished, pageEditFinished: this.pageEditFinished,
context: this.context context: this.context,
treeFrom: this.properties.treeFrom,
treeExpandTo: this.properties.treeExpandTo
} }
); );
ReactDom.render(element, this.domElement, () => { ReactDom.render(element, this.domElement, () => {
@ -146,8 +148,30 @@ export default class PageHierarchyWebPart extends BaseWebPart<IPageHierarchyWebP
text: strings.PropertyPane_PagesToDisplay_OptionText_Children, text: strings.PropertyPane_PagesToDisplay_OptionText_Children,
checked: this.properties.pagesToDisplay === PagesToDisplay.Children, checked: this.properties.pagesToDisplay === PagesToDisplay.Children,
iconProps: { officeFabricIconFontName: 'DistributeDown' } iconProps: { officeFabricIconFontName: 'DistributeDown' }
},
{
key: PagesToDisplay.Tree,
text: strings.PropertyPane_PagesToDisplay_OptionText_Tree,
checked: this.properties.pagesToDisplay === PagesToDisplay.Tree,
iconProps: { officeFabricIconFontName: 'ViewListTree' }
} }
] ]
}),
this.properties.pagesToDisplay === PagesToDisplay.Tree && PropertyFieldNumber('treeFrom', {
key: 'treeFrom',
value: this.properties.treeFrom,
label: strings.PropertyPane_Label_TreeFrom,
description: strings.PropertyPane_Description_TreeFrom,
minValue: 1,
disabled: false
}),
this.properties.pagesToDisplay === PagesToDisplay.Tree && PropertyFieldNumber('treeExpandTo', {
key: 'treeExpandTo',
value: this.properties.treeExpandTo,
label: strings.PropertyPane_Label_TreeExpandTo,
description: strings.PropertyPane_Description_TreeExpandTo,
minValue: 1,
disabled: false
}) })
] ]
}); });

View File

@ -7,10 +7,10 @@ import { IContainerProps } from './IContainerProps';
import { PagesToDisplay } from '@src/utilities'; import { PagesToDisplay } from '@src/utilities';
import { usePageApi } from '@src/apiHooks/usePageApi'; import { usePageApi } from '@src/apiHooks/usePageApi';
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder"; import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
import { TreeLayout } from '../Layouts/TreeLayout';
export const Container: React.FunctionComponent<IContainerProps> = props => { export const Container: React.FunctionComponent<IContainerProps> = props => {
const pagesApi = usePageApi(props.currentPageId, props.pageEditFinished, props.context); const pagesApi = usePageApi(props.currentPageId, props.pageEditFinished, props.context, props.treeFrom, props.treeExpandTo);
let controlToRender = undefined; let controlToRender = undefined;
switch (props.pagesToDisplay) { switch (props.pagesToDisplay) {
case PagesToDisplay.Ancestors: case PagesToDisplay.Ancestors:
@ -19,6 +19,9 @@ export const Container: React.FunctionComponent<IContainerProps> = props => {
case PagesToDisplay.Children: case PagesToDisplay.Children:
controlToRender = <ListLayout domElement={props.domElement} pages={pagesApi.state.childrenPages} themeVariant={props.themeVariant} />; controlToRender = <ListLayout domElement={props.domElement} pages={pagesApi.state.childrenPages} themeVariant={props.themeVariant} />;
break; break;
case PagesToDisplay.Tree:
controlToRender = <TreeLayout domElement={props.domElement} pages={pagesApi.state.childrenPages} themeVariant={props.themeVariant} nav={pagesApi.state.tree} pageId={props.currentPageId} />
break;
default: default:
controlToRender = <div> controlToRender = <div>
<Placeholder <Placeholder

View File

@ -6,6 +6,8 @@ import { WebPartContext } from '@microsoft/sp-webpart-base';
export interface IContainerProps { export interface IContainerProps {
currentPageId: number; currentPageId: number;
pagesToDisplay: PagesToDisplay; pagesToDisplay: PagesToDisplay;
treeFrom: number;
treeExpandTo: number;
themeVariant: IReadonlyTheme; themeVariant: IReadonlyTheme;
context: WebPartContext; context: WebPartContext;
domElement: HTMLElement; domElement: HTMLElement;
@ -15,6 +17,5 @@ export interface IContainerProps {
displayMode: DisplayMode; displayMode: DisplayMode;
updateTitle: (value: string) => void; updateTitle: (value: string) => void;
onConfigure: () => void; onConfigure: () => void;
pageEditFinished: boolean; pageEditFinished: boolean;
} }

View File

@ -1,8 +1,11 @@
import { IReadonlyTheme } from '@microsoft/sp-component-base'; import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { IPage } from '@src/models/IPage'; import { IPage } from '@src/models/IPage';
import { INavLink } from 'office-ui-fabric-react';
export interface ILayoutProps { export interface ILayoutProps {
domElement: HTMLElement; domElement: HTMLElement;
pages: IPage[]; pages: IPage[];
nav?: INavLink;
pageId?: number;
themeVariant: IReadonlyTheme; themeVariant: IReadonlyTheme;
} }

View File

@ -0,0 +1,18 @@
import * as React from 'react';
import styles from './Layouts.module.scss';
import { ILayoutProps } from './ILayoutProps';
import * as strings from 'PageHierarchyWebPartStrings';
import { Nav } from 'office-ui-fabric-react';
export const TreeLayout: React.FunctionComponent<ILayoutProps> = props => {
return(
<div className={styles.layouts}>
{props.nav ? (
<ul className={styles.listLayout}>
{<Nav groups={[{ links: [props.nav]}]} selectedKey={(props.pageId ?? '1').toString()} />}
</ul>
) : (
<span>{strings.Message_NoChildrenFound}</span>
)}
</div>);
};

View File

@ -5,6 +5,7 @@ define([], function() {
"Configuration_Placeholder_ButtonLabel": "Configure", "Configuration_Placeholder_ButtonLabel": "Configure",
"Message_NoAncestorsFound": "No ancestors found for page. Update the parent page property to select a parent", "Message_NoAncestorsFound": "No ancestors found for page. Update the parent page property to select a parent",
"Message_NoChildrenFound": "No children found for page. Update the parent page property for other pages to set this as their parent.", "Message_NoChildrenFound": "No children found for page. Update the parent page property for other pages to set this as their parent.",
"Message_NoTreeFound": "No tree found for page. Update the tree settings to ensure tree is rendered.",
"ParentPageMissing_Placeholder_IconText": "Parent Page Property is missing", "ParentPageMissing_Placeholder_IconText": "Parent Page Property is missing",
"ParentPageMissing_Placeholder_Description": "Click button to add Parent Page Property to Site Pages", "ParentPageMissing_Placeholder_Description": "Click button to add Parent Page Property to Site Pages",
"ParentPageMissing_Placeholder_Description_NoPermissions": "You don't have permissions to add the property. Have a Site Owner edit this web part to enable the Parent Page Property.", "ParentPageMissing_Placeholder_Description_NoPermissions": "You don't have permissions to add the property. Have a Site Owner edit this web part to enable the Parent Page Property.",
@ -15,9 +16,14 @@ define([], function() {
"PropertyPane_Label_PagesToDisplay": "Choose pages to show based on their relationships to this page", "PropertyPane_Label_PagesToDisplay": "Choose pages to show based on their relationships to this page",
"PropertyPane_PagesToDisplay_OptionText_Ancestors": "Ancestor Pages", "PropertyPane_PagesToDisplay_OptionText_Ancestors": "Ancestor Pages",
"PropertyPane_PagesToDisplay_OptionText_Children": "Children Pages", "PropertyPane_PagesToDisplay_OptionText_Children": "Children Pages",
"PropertyPane_PagesToDisplay_OptionText_Tree": "Tree Hierarchy",
"PropertyPane_Label_TreeFrom": "Page Id for the Top Level of the Tree",
"PropertyPane_GroupName_Debug": "Debug", "PropertyPane_GroupName_Debug": "Debug",
"PropertyPane_Label_DebugPageId": "Debug Page Id", "PropertyPane_Label_DebugPageId": "Debug Page Id",
"PropertyPane_Label_VersionInfo": "Version: ", "PropertyPane_Label_VersionInfo": "Version: ",
"PropertyPane_Description_DebugPageId": "Provide a valid page list item id to see how the web part would render for it" "PropertyPane_Description_DebugPageId": "Provide a valid page list item id to see how the web part would render for it",
"PropertyPane_Description_TreeFrom": "Please provide the page id for the root of the tree to render",
"PropertyPane_Label_TreeExpandTo": "Default Expand the Tree To Level",
"PropertyPane_Description_TreeExpandTo": "By default expand the tree to this level"
} }
}); });

View File

@ -4,6 +4,7 @@ declare interface IPageHierarchyWebPartStrings {
Configuration_Placeholder_ButtonLabel: string; Configuration_Placeholder_ButtonLabel: string;
Message_NoAncestorsFound: string; Message_NoAncestorsFound: string;
Message_NoChildrenFound: string; Message_NoChildrenFound: string;
Message_NoTreeFound: string;
ParentPageMissing_Placeholder_IconText: string; ParentPageMissing_Placeholder_IconText: string;
ParentPageMissing_Placeholder_Description: string; ParentPageMissing_Placeholder_Description: string;
ParentPageMissing_Placeholder_Description_NoPermissions: string; ParentPageMissing_Placeholder_Description_NoPermissions: string;
@ -14,10 +15,15 @@ declare interface IPageHierarchyWebPartStrings {
PropertyPane_Label_PagesToDisplay: string; PropertyPane_Label_PagesToDisplay: string;
PropertyPane_PagesToDisplay_OptionText_Ancestors: string; PropertyPane_PagesToDisplay_OptionText_Ancestors: string;
PropertyPane_PagesToDisplay_OptionText_Children: string; PropertyPane_PagesToDisplay_OptionText_Children: string;
PropertyPane_PagesToDisplay_OptionText_Tree: string;
PropertyPane_GroupName_Debug: string; PropertyPane_GroupName_Debug: string;
PropertyPane_Label_DebugPageId: string; PropertyPane_Label_DebugPageId: string;
PropertyPane_Label_VersionInfo: string; PropertyPane_Label_VersionInfo: string;
PropertyPane_Description_DebugPageId: string; PropertyPane_Description_DebugPageId: string;
PropertyPane_Label_TreeFrom: string;
PropertyPane_Description_TreeFrom: string;
PropertyPane_Label_TreeExpandTo: string;
PropertyPane_Description_TreeExpandTo: string;
} }
declare module 'PageHierarchyWebPartStrings' { declare module 'PageHierarchyWebPartStrings' {