First Commit

This commit is contained in:
João Mendes 2020-07-09 00:11:28 +01:00
parent 800f21cd14
commit 7bab153cb0
42 changed files with 20505 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,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,32 @@
{
"@pnp/generator-spfx": {
"framework": "react",
"pnpFramework": "reactjs.plus",
"pnp-libraries": [
"jquery@3",
"msgraph",
"@pnp/pnpjs",
"@pnp/spfx-property-controls",
"spfx-uifabric-themes",
"lodash",
"@pnp/spfx-controls-react",
"ouifr@7",
"rush@3.7"
],
"pnp-ci": "azure-preview",
"pnp-vetting": [],
"spfxenv": "spo",
"pnp-testing": []
},
"@microsoft/generator-sharepoint": {
"environment": "spo",
"framework": "react",
"isCreatingSolution": true,
"version": "1.10.0",
"libraryName": "react-organization-chart",
"libraryId": "d28b8c44-5df1-4315-a6eb-a5be13ba4b88",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,84 @@
---
page_type: sample
products:
- office-sp
languages:
- javascript
- typescript
extensions:
contentType: samples
technologies:
- SharePoint Framework
platforms:
- react
createdDate: 8/7/2020 12:00:00 AM
---
# Modern Organization Chart
## Summary
This webpart show organization chart for current user, shows, managers and direct reports and there available status.
On Click the profile page of will be open.
## Screenshots
![](../react-modern-organization-chart/assets/Screenshot1.png)
![](../react-modern-organization-chart/assets/Screenshot2.png)
### Working with
Built with SharePoint Framework GA, Microsoft Graph API and @pnp/PnPjs
## Used SharePoint Framework Version
![version](https://img.shields.io/badge/version-1.10.0-green.svg)
## Applies to
* [SharePoint Framework Developer Preview](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)
--------|---------
react-modern-organization-chart|João Mendes)
## Version history
Version|Date|Comments
-------|----|--------
1.0.0.0|July 08, 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.**
---
## Prerequisites
- SharePoint Online tenant , Microsoft Graph,
This web part use Microsoft Graph API to get presence of users, and need to have the Permission "presence.Read.All".
## Minimal Path to Awesome
- clone this repo
- `npm i`
- `gulp build`
- `gulp bundle --ship`
- `gulp package-solution --ship`
- Add Package to AppCatalog
- On the API Management Approve Permission "presence.read.all"
-
![](https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-modern-organization-chart)

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 MiB

View File

@ -0,0 +1,51 @@
parameters:
name: ''
jobs:
- job: ${{ parameters.name }}
pool:
vmImage: 'ubuntu-latest'
demands:
- npm
- node.js
- java
variables:
npm_config_cache: $(Pipeline.Workspace)/.npm
steps:
- checkout: self
- task: NodeTool@0
displayName: 'Use Node 10.x'
inputs:
versionSpec: 10.x
checkLatest: true
- task: CacheBeta@1
inputs:
key: npm | $(Agent.OS) | package-lock.json
path: $(npm_config_cache)
cacheHitVar: CACHE_RESTORED
- script: npm ci
displayName: 'npm ci'
- task: Gulp@0
displayName: 'Bundle project'
inputs:
targets: bundle
arguments: '--ship'
- task: Gulp@0
displayName: 'Package Solution'
inputs:
targets: 'package-solution'
arguments: '--ship'
- task: CopyFiles@2
displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)'
inputs:
Contents: |
sharepoint/**/*.sppkg
TargetFolder: '$(Build.ArtifactStagingDirectory)'
- task: PublishBuildArtifacts@1
displayName: 'Publish Artifact: drop'

View File

@ -0,0 +1,39 @@
parameters:
# unique name of the job
job_name: deploy_sppkg
# friendly name of the job
display_name: Upload & deploy *.sppkg to SharePoint app catalog
# name of target enviroment deploying to
target_environment: ''
# app catalog scope (tenant|sitecollection)
o365cli_app_catalog_scope: 'tenant'
variable_group_name: ''
jobs:
- deployment: ${{ parameters.job_name }}
displayName: ${{ parameters.display_name }}
pool:
vmImage: 'ubuntu-latest'
environment: ${{ parameters.target_environment }}
variables:
- group: ${{parameters.variable_group_name}} #o365_user_login, o365_user_password, o365_app_catalog_site_url
strategy:
runOnce:
deploy:
steps:
- checkout: none
- download: current
artifact: drop
patterns: '**/*.sppkg'
- script: sudo npm install --global @pnp/office365-cli
displayName: Install Office365 CLI
- script: o365 login $(o365_app_catalog_site_url) --authType password --userName $(o365_user_login) --password $(o365_user_password)
displayName: Login to Office365
- script: |
CMD_GET_SPPKG_NAME=$(find $(Pipeline.Workspace)/drop -name '*.sppkg' -exec basename {} \;)
echo "##vso[task.setvariable variable=SpPkgFileName;isOutput=true]${CMD_GET_SPPKG_NAME}"
displayName: Get generated *.sppkg filename
name: GetSharePointPackage
- script: o365 spo app add --filePath "$(Pipeline.Workspace)/drop/sharepoint/solution/$(GetSharePointPackage.SpPkgFileName)" --appCatalogUrl $(o365_app_catalog_site_url) --scope ${{ parameters.o365cli_app_catalog_scope }} --overwrite
displayName: Upload SharePoint package to Site Collection App Catalog
- script: o365 spo app deploy --name $(GetSharePointPackage.SpPkgFileName) --appCatalogUrl $(o365_app_catalog_site_url) --scope ${{ parameters.o365cli_app_catalog_scope }}
displayName: Deploy SharePoint package

View File

@ -0,0 +1,26 @@
name: $(TeamProject)_$(BuildDefinitionName)_$(SourceBranchName)_$(Date:yyyyMMdd)$(Rev:.r)
resources:
- repo: self
trigger:
branches:
include:
- master
- develop
stages:
- stage: build
displayName: build
jobs:
- template: ./azure-pipelines-build-template.yml
parameters:
name: 'buildsolution'
- stage: 'deployqa'
# uncomment if you want deployments to occur only for a specific branch
#condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/develop'))
jobs:
- template: ./azure-pipelines-deploy-template.yml
parameters:
job_name: deploy_solution
target_environment: 'qa'
variable_group_name: qa_configuration

View File

@ -0,0 +1,20 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"organization-chart-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/organizationChart/OrganizationChartWebPart.js",
"manifest": "./src/webparts/organizationChart/OrganizationChartWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"OrganizationChartWebPartStrings": "lib/webparts/organizationChart/loc/{locale}.js",
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js",
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/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": "react-organization-chart",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,19 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-modern-organization-chart",
"id": "d28b8c44-5df1-4315-a6eb-a5be13ba4b88",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"webApiPermissionRequests": [{
"resource": "Microsoft Graph",
"scope": "Presence.Read.All"
}]
},
"paths": {
"zippedPackage": "solution/react-modern-organization-chart.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,29 @@
'use strict';
// check if gulp dist was called
if (process.argv.indexOf('dist') !== -1) {
// add ship options to command call
process.argv.push('--ship');
}
const path = require('path');
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
const gulpSequence = require('gulp-sequence');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
// Create clean distrubution package
gulp.task('dist', gulpSequence('clean', 'bundle', 'package-solution'));
// Create clean development package
gulp.task('dev', gulpSequence('clean', 'bundle', 'package-solution'));
/**
* Custom Framework Specific gulp tasks
*/
build.initialize(gulp);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,55 @@
{
"name": "react-organization-chart",
"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",
"preversion": "node ./tools/pre-version.js",
"postversion": "gulp dist"
},
"dependencies": {
"@microsoft/sp-core-library": "1.10.0",
"@microsoft/sp-lodash-subset": "1.10.0",
"@microsoft/sp-office-ui-fabric-core": "1.10.0",
"@microsoft/sp-property-pane": "1.10.0",
"@microsoft/sp-webpart-base": "1.10.0",
"@pnp/pnpjs": "^2.0.6",
"@pnp/spfx-controls-react": "1.19.0",
"@pnp/spfx-property-controls": "1.19.0",
"@types/es6-promise": "0.0.33",
"@types/jquery": "^3.3.38",
"@types/react": "16.8.8",
"@types/react-dom": "16.8.3",
"@types/webpack-env": "1.13.1",
"jquery": "^3.5.1",
"office-ui-fabric-react": "^7.121.10",
"react": "16.8.5",
"react-dom": "16.8.5"
},
"resolutions": {
"@types/react": "16.8.8"
},
"devDependencies": {
"@microsoft/microsoft-graph-types": "^1.12.0",
"@microsoft/rush-stack-compiler-3.7": "^0.4.x",
"@microsoft/sp-build-web": "1.10.0",
"@microsoft/sp-module-interfaces": "1.10.0",
"@microsoft/sp-tslint-rules": "1.10.0",
"@microsoft/sp-webpart-workbench": "1.10.0",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"@types/react": "^16.9.38",
"ajv": "~5.2.2",
"gulp": "~3.9.1",
"gulp-sequence": "1.0.0",
"lodash": "^4.17.15",
"spfx-uifabric-themes": "^0.8.0",
"typescript": "~3.7.x"
}
}

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#6264a7",
"themeLighterAlt": "#f7f7fb",
"themeLighter": "#e1e1f1",
"themeLight": "#c8c9e4",
"themeTertiary": "#989ac9",
"themeSecondary": "#7173b0",
"themeDarkAlt": "#585a95",
"themeDark": "#4a4c7e",
"themeDarker": "#37385d",
"neutralLighterAlt": "#0b0b0b",
"neutralLighter": "#151515",
"neutralLight": "#252525",
"neutralQuaternaryAlt": "#2f2f2f",
"neutralQuaternary": "#373737",
"neutralTertiaryAlt": "#595959",
"neutralTertiary": "#c8c8c8",
"neutralSecondary": "#d0d0d0",
"neutralPrimaryAlt": "#dadada",
"neutralPrimary": "#ffffff",
"neutralDark": "#f4f4f4",
"black": "#f8f8f8",
"white": "#000000"
}

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#6264a7",
"themeLighterAlt": "#f7f7fb",
"themeLighter": "#e1e1f1",
"themeLight": "#c8c9e4",
"themeTertiary": "#989ac9",
"themeSecondary": "#7173b0",
"themeDarkAlt": "#585a95",
"themeDark": "#4a4c7e",
"themeDarker": "#37385d",
"neutralLighterAlt": "#2d2c2c",
"neutralLighter": "#2c2b2b",
"neutralLight": "#2a2929",
"neutralQuaternaryAlt": "#272626",
"neutralQuaternary": "#252525",
"neutralTertiaryAlt": "#242323",
"neutralTertiary": "#c8c8c8",
"neutralSecondary": "#d0d0d0",
"neutralPrimaryAlt": "#dadada",
"neutralPrimary": "#ffffff",
"neutralDark": "#f4f4f4",
"black": "#f8f8f8",
"white": "#2d2c2c"
}

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#6264a7",
"themeLighterAlt": "#f7f7fb",
"themeLighter": "#e1e1f1",
"themeLight": "#c8c9e4",
"themeTertiary": "#989ac9",
"themeSecondary": "#7173b0",
"themeDarkAlt": "#585a95",
"themeDark": "#4a4c7e",
"themeDarker": "#37385d",
"neutralLighterAlt": "#ecebe9",
"neutralLighter": "#e8e7e6",
"neutralLight": "#dedddc",
"neutralQuaternaryAlt": "#cfcecd",
"neutralQuaternary": "#c6c5c4",
"neutralTertiaryAlt": "#bebdbc",
"neutralTertiary": "#b5b4b2",
"neutralSecondary": "#9d9c9a",
"neutralPrimaryAlt": "#868482",
"neutralPrimary": "#252423",
"neutralDark": "#565453",
"black": "#3e3d3b",
"white": "#f3f2f1"
}

View File

@ -0,0 +1,16 @@
$default-background: #f3f2f1;
$default-color: #252423;
$default-button-background: #6264a7;
$default-Button-color: #f3f2f1;
// dark theme
$dark-background: #2d2c2c;
$dark-color: #ffffff;
$dark-button-background: #6264a7;
$dark-button-color: #2d2c2c;
// contrast theme
$contrast-background: #000000;
$contrast-color: #ffffff;
$contrast-button-background: #b5c01c;
$contrast-Button-color: #000000;

View File

@ -0,0 +1,4 @@
import React from "react";
import { IAppContext } from '../Entities/IAppContext';
export const AppContext = React.createContext<IAppContext>(undefined);

View File

@ -0,0 +1,7 @@
import { IUser } from "./IUser";
import { WebPartContext } from "@microsoft/sp-webpart-base";
export interface IAppContext {
currentUser: IUser;
context: WebPartContext;
}

View File

@ -0,0 +1,9 @@
export interface IUser {
displayName:string;
email: string;
isAnonymousGuestUser?: boolean;
isExternalGuestUser?: boolean;
loginName?: string;
preferUserTimeZone?: boolean;
}

View File

@ -0,0 +1,10 @@
import { IUser } from "./IUser";
import { IUserPresence } from "./IUserPresence";
export interface IUserInfo extends IUser {
title:string;
pictureUrl?: string;
userUrl?:string;
presence?: IUserPresence;
id?:string;
}

View File

@ -0,0 +1,6 @@
export interface IUserPresence {
"@odata.context"?: string;
id?: string;
availability: string;
activity: string;
}

View File

@ -0,0 +1,12 @@
import { IUser } from "../../Entities/IUser";
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { DisplayMode } from "@microsoft/sp-core-library";
export interface IOrganizationChartProps {
title: string;
currentUser: IUser ;
context: WebPartContext;
themeVariant: IReadonlyTheme | undefined;
displayMode: DisplayMode;
updateProperty: (value: string) => void;
}

View File

@ -0,0 +1,10 @@
import { IUserInfo } from "../../Entities/IUserInfo";
export interface IOrganizationChartState {
hasError: boolean;
isloading: boolean;
errorMessage: string;
managerList: IUserInfo[];
userProfile: any;
reportsList: IUserInfo[];
}

View File

@ -0,0 +1,80 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.container {
min-width: 257px;
display: block;
max-width: 300px;
max-height: 600px;
overflow: "auto";
padding: 10px;
}
.organizationChart {
.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,368 @@
import * as React from "react";
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import { IOrganizationChartProps } from "./IOrganizationChartProps";
import { escape } from "@microsoft/sp-lodash-subset";
import { Customizer } from "@uifabric/utilities/lib/";
import * as strings from "OrganizationChartWebPartStrings";
import {
IStyle,
mergeStyles,
Persona,
IPersonaSharedProps,
PersonaSize,
PersonaPresence,
DocumentCard,
IPersonaStyles,
mergeStyleSets,
IDocumentCardStyles,
Spinner,
SpinnerSize,
Stack,
IPersonaProps,
Label,
MessageBar,
MessageBarType,
} from "office-ui-fabric-react";
//import { AppContext } from "../../Entities/AppContext";
import { IAppContext } from "../../Entities/IAppContext";
import { IUserInfo } from "../../Entities/IUserInfo";
import { useState } from "react";
import { useGetUserProperties } from "../../hooks/useGetUserProperties";
import { IOrganizationChartState } from "./IOrganizationChartState";
// Persona Styles
const personaStyles: Partial<IPersonaStyles> = {
root: {},
primaryText: {
fontSize: 14,
fontWeight: 500,
},
};
// Maping presence status MSGraph to persona presence status
const presenceStatus: any[] = [];
presenceStatus["Available"] = PersonaPresence.online;
presenceStatus["AvailableIdle"] = PersonaPresence.online;
presenceStatus["Away"] = PersonaPresence.away;
presenceStatus["BeRightBack"] = PersonaPresence.away;
presenceStatus["Busy"] = PersonaPresence.busy;
presenceStatus["BusyIdle"] = PersonaPresence.busy;
presenceStatus["DoNotDisturb"] = PersonaPresence.dnd;
presenceStatus["Offline"] = PersonaPresence.offline;
presenceStatus["PresenceUnknown"] = PersonaPresence.none;
// Functional Component
export const OrganizationChart: React.FunctionComponent<IOrganizationChartProps> = (
props: IOrganizationChartProps
) => {
const applicationContext: IAppContext = {
currentUser: props.currentUser,
context: props.context,
};
// State
const [state, setState] = useState<IOrganizationChartState>({
isloading: true,
hasError: false,
errorMessage: "",
managerList: [],
userProfile: undefined,
reportsList: [],
});
// Global Compoment Styles
const stylesComponent = mergeStyleSets({
container: {
minWidth: 257,
display: "block",
maxWidth: 300,
maxHeight: 620,
overflow: "auto",
padding: 10,
paddingBottom: 20,
},
managerList: {
display: "block",
marginLeft: 30,
marginRight: 10,
height: "auto",
paddingBottom: 40,
borderLeftStyle: "solid",
borderLeftWidth: 2,
borderLeftColor: props.themeVariant.palette.neutralQuaternary,
borderBottomColor: props.themeVariant.palette.neutralQuaternary,
borderBottomStyle: "solid",
borderBottomWidth: 2,
},
currentUser: {
marginLeft: 75,
height: "auto",
marginRight: 10,
borderLeftStyle: state.reportsList.length > 0 ? "solid" : "none",
borderLeftWidth: state.reportsList.length > 0 ? 2 : 0,
borderLeftColor: props.themeVariant.palette.neutralQuaternary,
borderBottomColor: props.themeVariant.palette.neutralQuaternary,
},
directReportList: {
marginLeft: 85,
height: "auto",
marginRight: 10,
},
directReportInfo: {
width: "70%",
padding: 5,
height: "auto",
backgroundColor: props.themeVariant.palette.neutralLight,
marginLeft: 1,
marginTop: 20,
},
webPartTile: {
paddingLeft: 30,
paddingTop: 20,
},
});
// Document Card Styles
const documentCardManagerStyles: Partial<IDocumentCardStyles> = {
root: {
marginLeft: -25,
marginTop: 15,
padding: 5,
paddingBottom: 5,
borderStyle: "none",
borderWidth: 0,
selectors: {
":hover": {
backgroundColor: props.themeVariant.palette.themeLighter,
},
":hover::after": {
borderWidth: 0,
borderStyle: "none",
},
},
},
};
const documentCardUserStyles: Partial<IDocumentCardStyles> = {
root: {
marginLeft: 0,
marginTop: 15,
padding: 5,
paddingBottom: 5,
borderStyle: "none",
borderWidth: 0,
selectors: {
":hover": {
backgroundColor: props.themeVariant.palette.themeLighter,
},
":hover::after": {
borderWidth: 0,
borderStyle: "none",
},
},
},
};
const documentCardCurrentUserStyles: Partial<IDocumentCardStyles> = {
root: {
marginLeft: -25,
padding: 5,
borderStyle: "none",
borderWidth: 0,
marginTop: state.managerList.length > 0 ? -25 : 15,
selectors: {
":hover": {
backgroundColor: props.themeVariant.palette.themeLighter,
},
":hover::after": {
borderWidth: 0,
borderStyle: "none",
},
},
},
};
const _onRenderCoin = (iconProps: IPersonaProps): JSX.Element => {
const { coinSize, imageAlt, imageUrl } = iconProps;
return (
<img
src={imageUrl}
alt={imageAlt}
width={coinSize}
height={coinSize}
style={{
display: "block",
background: "transparent",
border: `2px solid ${props.themeVariant.palette.neutralTertiary}`,
borderRadius: "50%",
}}
/>
);
};
const _userPersonaCard = (userInfo: IUserInfo): JSX.Element => {
return (
<>
<DocumentCard
styles={documentCardUserStyles}
onClickHref={userInfo.userUrl}
key={userInfo.email}
>
<Persona
styles={personaStyles}
imageUrl={userInfo.pictureUrl}
text={userInfo.displayName}
secondaryText={userInfo.title}
size={PersonaSize.size40}
coinSize={40}
onRenderCoin={_onRenderCoin}
presence={presenceStatus[userInfo.presence.availability]}
presenceTitle={userInfo.presence.activity}
/>
</DocumentCard>
</>
);
};
const _managerPersonaCard = (managerInfo: IUserInfo): JSX.Element => {
return (
<>
<DocumentCard
styles={documentCardManagerStyles}
onClickHref={managerInfo.userUrl}
key={managerInfo.email}
>
<Persona
styles={personaStyles}
imageUrl={managerInfo.pictureUrl}
text={managerInfo.displayName}
secondaryText={managerInfo.title}
size={PersonaSize.size40}
coinSize={40}
onRenderCoin={_onRenderCoin}
presence={presenceStatus[managerInfo.presence.availability]}
presenceTitle={managerInfo.presence.activity}
/>
</DocumentCard>
</>
);
};
React.useEffect(() => {
(async () => {
try {
let {
_managersList,
_currentUserProfile,
_reportsList,
} = await useGetUserProperties(
applicationContext.currentUser.loginName,
applicationContext.context
);
setState({
...state,
isloading: false,
managerList: _managersList,
reportsList: _reportsList,
userProfile: _currentUserProfile,
});
//
} catch (error) {
setState({
...state,
isloading: false,
hasError: true,
errorMessage: `${strings.errorMessage} ${error.message}`,
});
}
})();
}, [props]);
// Render component
return (
<>
<div className={stylesComponent.container}>
<WebPartTitle
displayMode={props.displayMode}
title={props.title}
updateProperty={props.updateProperty}
themeVariant={props.themeVariant}
/>
{state.isloading ? (
<Stack horizontal horizontalAlign={"center"}>
<Spinner size={SpinnerSize.small} label={"loading..."} />
</Stack>
) : state.hasError ? (
<MessageBar messageBarType={MessageBarType.error}>
{state.errorMessage}
</MessageBar>
) : (
<ol style={{ listStyle: "none", paddingLeft: 0 }}>
<li style={{ display: "list-item" }}>
{state.managerList.length > 0 ? (
<div className={stylesComponent.managerList} key={1}>
{state.managerList.map((manager, i) => {
return _managerPersonaCard(manager);
})}
</div>
) : null}
</li>
<li style={{ display: "list-item" }}>
{state.userProfile ? (
<div
className={stylesComponent.currentUser}
style={{
marginLeft: state.managerList.length > 0 ? 80 : 40,
}}
>
<DocumentCard
onClickHref={state.userProfile.UserUrl}
styles={documentCardCurrentUserStyles}
>
<Persona
styles={{
...personaStyles,
primaryText: { fontWeight: 700 },
}}
imageUrl={state.userProfile.PictureUrl}
text={state.userProfile.DisplayName}
secondaryText={state.userProfile.Title}
size={PersonaSize.size40}
coinSize={40}
onRenderCoin={_onRenderCoin}
presence={
presenceStatus[state.userProfile.presence.availability]
}
presenceTitle={state.userProfile.presence.activity}
// imageAlt={"Annie Linguist, status is away"}
/>
</DocumentCard>
{state.reportsList.length > 0 ? (
<div className={stylesComponent.directReportInfo}>
<Label style={{ fontWeight: 500, fontSize: 12 }}>
Direct Reports ({state.reportsList.length})
</Label>
</div>
) : null}
</div>
) : null}
<div
className={stylesComponent.directReportList}
style={{
marginLeft: state.managerList.length > 0 ? 80 : 40,
}}
>
{state.reportsList.length > 0
? state.reportsList.map((user, i) => {
return _userPersonaCard(user);
})
: null}
</div>
</li>
</ol>
)}
</div>
</>
);
};

View File

@ -0,0 +1,223 @@
import { sp } from "@pnp/sp";
import "@pnp/sp/profiles";
import { IUserInfo } from "../Entities/IUserInfo";
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { MSGraphClient } from "@microsoft/sp-http";
import { IUserPresence } from "../Entities/IUserPresence";
import * as _ from "lodash";
import { PnPClientStorage } from "@pnp/common";
/*************************************************************************************/
// Hook to get user profile information
//*************************************************************************************/
export const useGetUserProperties = async (
userEmail: string,
context?: WebPartContext
): Promise<any> => {
/*************************************************************************************/
// vars and const
//*************************************************************************************/
const _MSGraphClient: MSGraphClient = await context.msGraphClientFactory.getClient();
const loginName: string = `i:0#.f|membership|${userEmail}`;
const storage = new PnPClientStorage();
let _managersList: IUserInfo[] = [];
let _reportsList: IUserInfo[] = [];
/* sp.setup({
spfxContext: context
}); */
/*************************************************************************************/
// Functions
//*************************************************************************************//
// function Get UserId from UserProfileProperties
//*************************************************************************************//
const getUserId = async (userProfileProperties: any[]): Promise<string> => {
// Get User Properties
let props = {};
userProfileProperties.forEach((prop) => {
props[prop.Key] = prop.Value;
});
// Get UserID
return props["msOnline-ObjectId"];
};
//*************************************************************************************//
// functions convert image to Base64
//*************************************************************************************//
const getImageBase64 = (pictureUrl: string, userId:string): Promise<string> => {
return new Promise((resolve, reject) => {
const value = storage.local.get(userId);
if (value) {
resolve(value);
}
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 "";
}
storage.local.put(userId, base64Str);
resolve(base64Str);
});
image.src = pictureUrl;
});
};
//*************************************************************************************//
// function Get Users Presence
//*************************************************************************************//
const getUserPresence = async (
userObjIds: string[]
): Promise<IUserPresence[]> => {
// Get presences for Users Ids
const _presence: any = await _MSGraphClient
.api(`/communications/getPresencesByUserId`)
.version("beta")
.post({ ids: userObjIds });
return _presence.value;
};
//*************************************************************************************//
// Get User Managers
//*************************************************************************************//
const getManagers = async (extendedManagers) => {
let _managersObjIds: string[] = [];
// Get Managers
for (const _manager of extendedManagers) {
// get Profile for Manager
const _profile: any = await sp.profiles
.usingCaching()
.getPropertiesFor(_manager);
// Get Object Id from userProperties
const _managerObjId: string = await getUserId(
_profile.UserProfileProperties
);
_managersObjIds.push(_managerObjId);
// Add manager to list
_managersList.push({
displayName: _profile.DisplayName as string,
email: _profile.Email as string,
title: _profile.Title as string,
pictureUrl: await getImageBase64(
`/_layouts/15/userphoto.aspx?size=M&accountname=${_profile.Email}`,_managerObjId
),
id: _managerObjId,
// presence: await getUserPresence(_profile.UserProfileProperties),
userUrl: _profile.UserUrl,
});
}
//*************************************************************************************//
// Get presence for all managers
//*************************************************************************************//
const _managersPresences: IUserPresence[] = await getUserPresence(
_managersObjIds
);
// Update Array of managers with presence
if (_managersPresences.length > 0) {
for (const _presence of _managersPresences) {
const i = _.findIndex(_managersList, (v) => {
return v.id == _presence.id;
});
_managersList[i] = {
..._managersList[i],
presence: {
activity: _presence.activity,
availability: _presence.availability,
},
};
}
}
};
//************************************************************************************//
// Get Direct Reports
//*************************************************************************************//
const getDirectReports = async (directReports) => {
let _userReportObjIds: string[] = [];
for (const _userReport of directReports) {
const _profile: any = await sp.profiles
.usingCaching()
.getPropertiesFor(_userReport);
const _userReportObjId: string = await getUserId(
_profile.UserProfileProperties
);
_userReportObjIds.push(_userReportObjId);
// Get Presence to the user
_reportsList.push({
displayName: _profile.DisplayName as string,
email: _profile.Email as string,
title: _profile.Title as string,
pictureUrl: await getImageBase64(
`/_layouts/15/userphoto.aspx?size=M&accountname=${_profile.Email}`, _userReportObjId
),
id: _userReportObjId,
userUrl: _profile.UserUrl,
});
}
//*************************************************************************************//
// Get presence for all direct Reports and update list
//*************************************************************************************//
const _directReportsPresences: IUserPresence[] = await getUserPresence(
_userReportObjIds
);
// Update Array of managers with presence
if (_directReportsPresences.length > 0) {
for (const _presence of _directReportsPresences) {
const i = _.findIndex(_reportsList, (v) => {
return v.id == _presence.id;
});
_reportsList[i] = {
..._reportsList[i],
presence: {
activity: _presence.activity,
availability: _presence.availability,
},
};
}
}
};
//*************************************************************************************//
// End Functions
//*************************************************************************************//
//*************************************************************************************//
// Get Current User Profile
//*************************************************************************************//
const _currentUserProfile: any = await sp.profiles
.usingCaching()
.getPropertiesFor(loginName);
console.log(_currentUserProfile);
const _extendedManagers: string[] = _currentUserProfile.ExtendedManagers;
const _directReports: string[] = _currentUserProfile.DirectReports;
const _currentUserObjId: string = await getUserId( _currentUserProfile.UserProfileProperties);
// Get Current user Picture and User Presence
_currentUserProfile.PictureUrl = await getImageBase64(
`/_layouts/15/userphoto.aspx?size=M&accountname=${_currentUserProfile.Email}`, _currentUserObjId);
// get Current User Presence
const _currentUserPresence: IUserPresence[] = await getUserPresence([_currentUserObjId]);
_currentUserProfile.presence = { activity: _currentUserPresence[0].activity, availability: _currentUserPresence[0].availability};
// Get Manager if exists
if (_extendedManagers.length > 0) await getManagers(_extendedManagers);
// Get Direct Reports if exists
if (_directReports.length > 0) await getDirectReports(_directReports);
//*************************************************************************************//
// Return objects
// _managersList , _currentUserProfile , DirectReports
//*************************************************************************************//
return { _managersList, _currentUserProfile, _reportsList };
};

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,27 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "ea67ede9-e4e7-411c-aee1-843dca97a4a8",
"alias": "OrganizationChartWebPart",
"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": "Organization Chart" },
"description": { "default": "Organization Chart" },
"officeFabricIconFontName": "Org",
"properties": {
"title": "Organization Chart"
}
}]
}

View File

@ -0,0 +1,137 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { ThemeProvider, ThemeChangedEventArgs, IReadonlyTheme } from '@microsoft/sp-component-base';
import * as strings from 'OrganizationChartWebPartStrings';
import {OrganizationChart} from '../../components/OrganizationChart/OrganizationChart';
import { IOrganizationChartProps } from '../../components/OrganizationChart/IOrganizationChartProps';
import { loadTheme } from "office-ui-fabric-react";
import { DisplayMode } from '@microsoft/sp-core-library';
import { sp } from "@pnp/sp";
const teamsDefaultTheme = require("../../common/TeamsDefaultTheme.json");
const teamsDarkTheme = require("../../common/TeamsDarkTheme.json");
const teamsContrastTheme = require("../../common/TeamsContrastTheme.json");
export interface IOrganizationChartWebPartProps {
title: string;
displayMode: DisplayMode;
updateProperty: (value: string) => void;
}
export default class OrganizationChartWebPart extends BaseClientSideWebPart <IOrganizationChartWebPartProps> {
private _themeProvider: ThemeProvider;
private _themeVariant: IReadonlyTheme | undefined;
protected async onInit(): Promise<void> {
sp.setup({
spfxContext: this.context
});
this._themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
// If it exists, get the theme variant
this._themeVariant = this._themeProvider.tryGetTheme();
// Register a handler to be notified if the theme variant changes
this._themeProvider.themeChangedEvent.add(this, this._handleThemeChangedEvent);
if (this.context.sdks.microsoftTeams) {
// in teams ?
const context = this.context.sdks.microsoftTeams!.context;
this._applyTheme(context.theme || "default");
this.context.sdks.microsoftTeams.teamsJs.registerOnThemeChangeHandler(
this._applyTheme
);
}
return Promise.resolve();
}
/**
* Update the current theme variant reference and re-render.
*
* @param args The new theme
*/
private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void {
this._themeVariant = args.theme;
this.render();
}
// Apply btheme id in Teams
private _applyTheme = (theme: string): void => {
this.context.domElement.setAttribute("data-theme", theme);
document.body.setAttribute("data-theme", theme);
if (theme == "dark") {
loadTheme({
palette: teamsDarkTheme
});
}
if (theme == "default") {
loadTheme({
palette: teamsDefaultTheme
});
}
if (theme == "contrast") {
loadTheme({
palette: teamsContrastTheme
});
}
}
public render(): void {
const element: React.ReactElement<IOrganizationChartProps> = React.createElement(
OrganizationChart,
{
title: this.properties.title,
currentUser: this.context.pageContext.user,
context: this.context,
themeVariant: this._themeVariant,
displayMode: this.displayMode,
updateProperty: (value: string) => {
this.properties.title = value;
}
}
);
ReactDom.render(element, this.domElement);
}
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('title', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,9 @@
define([], function() {
return {
errorMessage: "Error on loading Organization Chart",
"PropertyPaneDescription": "Modern Organization Chart, With Presence",
"BasicGroupName": "Properties",
"DescriptionFieldLabel": "Title",
}
});

View File

@ -0,0 +1,11 @@
declare interface IOrganizationChartWebPartStrings {
errorMessage: string;
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'OrganizationChartWebPartStrings' {
const strings: IOrganizationChartWebPartStrings;
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,64 @@
/**
* This script updates the package-solution version analogue to the
* the package.json file.
*/
if (process.env.npm_package_version === undefined) {
throw 'Package version cannot be evaluated';
}
// define path to package-solution file
const solution = './config/package-solution.json',
teams = './teams/manifest.json';
// require filesystem instance
const fs = require('fs');
// get next automated package version from process variable
const nextPkgVersion = process.env.npm_package_version;
// make sure next build version match
const nextVersion = nextPkgVersion.indexOf('-') === -1 ?
nextPkgVersion : nextPkgVersion.split('-')[0];
// Update version in SPFx package-solution if exists
if (fs.existsSync(solution)) {
// read package-solution file
const solutionFileContent = fs.readFileSync(solution, 'UTF-8');
// parse file as json
const solutionContents = JSON.parse(solutionFileContent);
// set property of version to next version
solutionContents.solution.version = nextVersion + '.0';
// save file
fs.writeFileSync(
solution,
// convert file back to proper json
JSON.stringify(solutionContents, null, 2),
'UTF-8');
}
// Update version in teams manifest if exists
if (fs.existsSync(teams)) {
// read package-solution file
const teamsManifestContent = fs.readFileSync(teams, 'UTF-8');
// parse file as json
const teamsContent = JSON.parse(teamsManifestContent);
// set property of version to next version
teamsContent.version = nextVersion;
// save file
fs.writeFileSync(
teams,
// convert file back to proper json
JSON.stringify(teamsContent, null, 2),
'UTF-8');
}

View File

@ -0,0 +1,40 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.7/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"
],
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"lib"
]
}

View File

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