Merge branch 'main' into dependabot/npm_and_yarn/samples/react-calendar/async-2.6.4

This commit is contained in:
Hugo Bernier 2024-08-09 10:23:00 -04:00 committed by GitHub
commit 5716debf66
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
80 changed files with 68503 additions and 22190 deletions

View File

@ -14228,7 +14228,7 @@
"At the time of developing this sample, the Office 365 UI fabric does not have any control for displaying hierarchical information. This web part helps to display the hierarchical information from SharePoint list." "At the time of developing this sample, the Office 365 UI fabric does not have any control for displaying hierarchical information. This web part helps to display the hierarchical information from SharePoint list."
], ],
"creationDateTime": "2020-11-21", "creationDateTime": "2020-11-21",
"updateDateTime": "2020-11-21", "updateDateTime": "2024-06-28",
"products": [ "products": [
"SharePoint" "SharePoint"
], ],
@ -14239,7 +14239,7 @@
}, },
{ {
"key": "SPFX-VERSION", "key": "SPFX-VERSION",
"value": "1.11.0" "value": "1.18.2"
} }
], ],
"thumbnails": [ "thumbnails": [
@ -26247,6 +26247,53 @@
} }
] ]
}, },
{
"name": "pnp-sp-dev-spfx-web-parts-react-site-secure-function-call",
"source": "pnp",
"title": "Site Secure Function Call",
"shortDescription": "This combined SharePoint Framework and Azure Function solution is to provide the potentially most secure access from SharePoint Framework to any kind of third party API or Microsoft Graph.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-office-offer-creation",
"longDescription": [
"This combined SharePoint Framework and Azure Function solution is to provide the potentially most secure access from SharePoint Framework to any kind of third party API, in fact here Microsoft Graph. It shows that AadHttpClient should be preferred over MSGraphClient."
],
"creationDateTime": "2024-07-12",
"updateDateTime": "2024-07-12",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "React"
},
{
"key": "SPFX-VERSION",
"value": "1.18.2"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-site-secure-function-call/assets/SetSiteDescreption.gif",
"alt": "App in action"
}
],
"authors": [
{
"gitHubAccount": "mmsharepoint",
"pictureUrl": "https://github.com/mmsharepoint.png",
"name": "Markus Moeller"
}
],
"references": [
{
"name": "Build your first SharePoint client-side web part",
"description": "Client-side web parts are client-side components that run in the context of a SharePoint page. Client-side web parts can be deployed to SharePoint environments that support the SharePoint Framework. You can also use modern JavaScript web frameworks, tools, and libraries to build them.",
"url": "https://learn.microsoft.com/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
},
{ {
"name": "pnp-sp-dev-spfx-web-parts-react-sitepages-metadata", "name": "pnp-sp-dev-spfx-web-parts-react-sitepages-metadata",
"source": "pnp", "source": "pnp",

File diff suppressed because it is too large Load Diff

View File

@ -52,7 +52,7 @@
}, },
"devDependencies": { "devDependencies": {
"@microsoft/rush-stack-compiler-3.9": "0.4.47", "@microsoft/rush-stack-compiler-3.9": "0.4.47",
"@microsoft/sp-build-web": "1.12.1", "@microsoft/sp-build-web": "1.20.1",
"@microsoft/sp-module-interfaces": "1.12.1", "@microsoft/sp-module-interfaces": "1.12.1",
"@microsoft/sp-tslint-rules": "1.12.1", "@microsoft/sp-tslint-rules": "1.12.1",
"@microsoft/sp-webpart-workbench": "1.12.1", "@microsoft/sp-webpart-workbench": "1.12.1",

View File

@ -0,0 +1,38 @@
{
"name": "SPFx 1.18.2",
"image": "docker.io/m365pnp/spfx:1.18.2",
"customizations": {
"vscode": {
"extensions": [
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint"
]
}
},
"forwardPorts": [
4321,
35729,
5432
],
"portsAttributes": {
"4321": {
"protocol": "https",
"label": "Manifest",
"onAutoForward": "silent",
"requireLocalPort": true
},
"5432": {
"protocol": "https",
"label": "Workbench",
"onAutoForward": "silent"
},
"35729": {
"protocol": "https",
"label": "LiveReload",
"onAutoForward": "silent",
"requireLocalPort": true
}
},
"postCreateCommand": "bash .devcontainer/spfx-startup.sh",
"remoteUser": "node"
}

View File

@ -0,0 +1,33 @@
echo
echo -e "\e[1;94mInstalling Node dependencies\e[0m"
npm install
## commands to create dev certificate and copy it to the root folder of the project
echo
echo -e "\e[1;94mGenerating dev certificate\e[0m"
gulp trust-dev-cert
# Convert the generated PEM certificate to a CER certificate
openssl x509 -inform PEM -in ~/.rushstack/rushstack-serve.pem -outform DER -out ./spfx-dev-cert.cer
# Copy the PEM ecrtificate for non-Windows hosts
cp ~/.rushstack/rushstack-serve.pem ./spfx-dev-cert.pem
## add *.cer to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.cer' ./.gitignore
then
echo "# .CER Certificates" >> .gitignore
echo "*.cer" >> .gitignore
fi
## add *.pem to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.pem' ./.gitignore
then
echo "# .PEM Certificates" >> .gitignore
echo "*.pem" >> .gitignore
fi
echo
echo -e "\e[1;92mReady!\e[0m"
echo -e "\n\e[1;94m**********\nOptional: if you plan on using gulp serve, don't forget to add the container certificate to your local machine. Please visit https://aka.ms/spfx-devcontainer for more information\n**********"

View File

@ -0,0 +1,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {}
}
]
};

View File

@ -9,9 +9,11 @@ node_modules
# Build generated files # Build generated files
dist dist
lib lib
release
solution solution
temp temp
*.sppkg *.sppkg
.heft
# Coverage directory used by tools like istanbul # Coverage directory used by tools like istanbul
coverage coverage

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 @@
v18.18.0

View File

@ -1,12 +1,21 @@
{ {
"@microsoft/generator-sharepoint": { "@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true, "isCreatingSolution": true,
"nodeVersion": "18.18.0",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.12.0"
},
"version": "1.18.2",
"libraryName": "spfx-new",
"libraryId": "d89e19bf-7bf0-4ca2-b131-ba9b8f2e5754",
"environment": "spo", "environment": "spo",
"version": "1.11.0",
"isDomainIsolated": false,
"libraryName": "spfx-react-hierarchy-view",
"libraryId": "2fd9a018-0cd9-4cca-9e84-4fac64b83333",
"packageManager": "npm", "packageManager": "npm",
"solutionName": "spfx-new",
"solutionShortDescription": "spfx-new description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart" "componentType": "webpart"
} }
} }

View File

@ -6,28 +6,30 @@ At the time of developing this sample, the Office 365 UI fabric does not have an
![Web part preview][figure1] ![Web part preview][figure1]
The web part is configured to render the mock data when added to the local SharePoint workbench.
![Local SharePoint Workbench Run][figure2]
When added to SharePoint site, the source list containing hierarchical information can be configured from web part properties. When added to SharePoint site, the source list containing hierarchical information can be configured from web part properties.
The sample also provisions the list called “Hierarchy” which can be used as an example to start using the web part. The sample also provisions the list called “Hierarchy” which can be used as an example to start using the web part.
![SharePoint Run][figure3]
![SharePoint Run][figure2]
### SharePoint Asset ### SharePoint Asset
A SharePoint list (named Hierarchy) is provisioned to store the hierarchical data. The schema of the list is as below. A SharePoint list (named Hierarchy) is provisioned to store the hierarchical data. The schema of the list is as below.
![List Schema][figure4]
![List Schema][figure3]
The Parent column is a lookup on same lists Title column. The Parent column is a lookup on same lists Title column.
The solution also provisions sample data to the Hierarchy list. The solution also provisions sample data to the Hierarchy list.
![List Sample Data][figure5]
![List Sample Data][figure4]
### NPM Packages Used ### NPM Packages Used
Below NPM packages are used to develop this sample. Below NPM packages are used to develop this sample.
1. sp-pnp-js (https://www.npmjs.com/package/sp-pnp-js) 1. @pnp/sp (https://pnp.github.io/pnpjs/)
2. react-orgchart (https://www.npmjs.com/package/react-orgchart) 2. react-orgchart (https://www.npmjs.com/package/react-orgchart)
3. array-to-tree (https://www.npmjs.com/package/array-to-tree) 3. array-to-tree (https://www.npmjs.com/package/array-to-tree)
## Compatibility ## Compatibility
@ -36,16 +38,16 @@ Below NPM packages are used to develop this sample.
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.| | Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. | |Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
![SPFx 1.11](https://img.shields.io/badge/SPFx-1.11.0-green.svg) ![SPFx 1.18.2](https://img.shields.io/badge/SPFx-1.18.2-green.svg)
![Node.js v10](https://img.shields.io/badge/Node.js-v10-green.svg) ![Node.js v16 | v18](https://img.shields.io/badge/Node.js-v16%20%7C%20v18-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg) ![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower") ![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1") ![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Teams Incompatible](https://img.shields.io/badge/Teams-Incompatible-lightgrey.svg) ![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Local Workbench Incompatible](https://img.shields.io/badge/Local%20Workbench-Incompatible-red.svg "The solution requires access to SharePoint content")
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg) ![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg) ![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)
## Applies to ## Applies to
* [SharePoint Framework Developer Preview](https://learn.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview) * [SharePoint Framework Developer Preview](https://learn.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
@ -55,11 +57,13 @@ Below NPM packages are used to develop this sample.
* [Nanddeep Nachan](https://github.com/nanddeepn) * [Nanddeep Nachan](https://github.com/nanddeepn)
* [Ravi Kulkarni](https://github.com/ravi16a87) * [Ravi Kulkarni](https://github.com/ravi16a87)
* [Smita Nachan](https://github.com/SmitaNachan)
## Version history ## Version history
Version|Date|Comments Version|Date|Comments
-------|----|-------- -------|----|--------
3.0.0|July 01, 2024|Upgraded to SPFx v1.18.2 (Nanddeep Nachan, Smita Nachan)
2.0.0|November 21, 2020|Upgraded to SPFx v1.11.0 (Nanddeep Nachan) 2.0.0|November 21, 2020|Upgraded to SPFx v1.11.0 (Nanddeep Nachan)
1.0.0|October 15, 2018|Initial release 1.0.0|October 15, 2018|Initial release
@ -87,17 +91,15 @@ This sample web part shows how data stored in SharePoint list can be transformed
- Rendering hierarchical information - Rendering hierarchical information
- SharePoint assets provisioning - SharePoint assets provisioning
- Creating extensible services - Creating extensible services
- Using mock data to test the web part locally
- Using @pnp/sp - Using @pnp/sp
- Using @react-orgchart - Using @react-orgchart
- Using @array-to-tree - Using @array-to-tree
[figure1]: ./assets/webpart-preview.png [figure1]: ./assets/webpart-preview.png
[figure2]: ./assets/local-sharepoint-workbench-run.png [figure2]: ./assets/sharepoint-run.gif
[figure3]: ./assets/sharepoint-run.gif [figure3]: ./assets/list-schema.png
[figure4]: ./assets/list-schema.png [figure4]: ./assets/list-sample-data.png
[figure5]: ./assets/list-sample-data.png
## Help ## Help

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

View File

@ -9,7 +9,7 @@
"At the time of developing this sample, the Office 365 UI fabric does not have any control for displaying hierarchical information. This web part helps to display the hierarchical information from SharePoint list." "At the time of developing this sample, the Office 365 UI fabric does not have any control for displaying hierarchical information. This web part helps to display the hierarchical information from SharePoint list."
], ],
"creationDateTime": "2020-11-21", "creationDateTime": "2020-11-21",
"updateDateTime": "2020-11-21", "updateDateTime": "2024-06-28",
"products": [ "products": [
"SharePoint" "SharePoint"
], ],
@ -20,7 +20,7 @@
}, },
{ {
"key": "SPFX-VERSION", "key": "SPFX-VERSION",
"value": "1.11.0" "value": "1.18.2"
} }
], ],
"thumbnails": [ "thumbnails": [

View File

@ -1,6 +1,6 @@
{ {
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json", "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./temp/deploy/", "workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->", "account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "spfx-react-hierarchy-view", "container": "spfx-react-hierarchy-view",
"accessKey": "<!-- ACCESS KEY -->" "accessKey": "<!-- ACCESS KEY -->"

View File

@ -7,6 +7,24 @@
"includeClientSideAssets": true, "includeClientSideAssets": true,
"skipFeatureDeployment": true, "skipFeatureDeployment": true,
"isDomainIsolated": false, "isDomainIsolated": false,
"developer": {
"name": "Contoso",
"privacyUrl": "https://contoso.com/privacy",
"termsOfUseUrl": "https://contoso.com/terms-of-use",
"websiteUrl": "https://contoso.com/my-app",
"mpnId": "m365pnp"
},
"metadata": {
"shortDescription": {
"default": "spfx-react-hierarchy-view description"
},
"longDescription": {
"default": "spfx-react-hierarchy-view description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [ "features": [
{ {
"title": "react-display-hierarchy-deployment", "title": "react-display-hierarchy-deployment",
@ -22,14 +40,7 @@
] ]
} }
} }
], ]
"developer": {
"name": "Contoso",
"privacyUrl": "https://contoso.com/privacy",
"termsOfUseUrl": "https://contoso.com/terms-of-use",
"websiteUrl": "https://contoso.com/my-app",
"mpnId": "m365pnp"
}
}, },
"paths": { "paths": {
"zippedPackage": "solution/spfx-react-hierarchy-view.sppkg" "zippedPackage": "solution/spfx-react-hierarchy-view.sppkg"

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

@ -1,10 +1,6 @@
{ {
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json", "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321, "port": 4321,
"https": true, "https": true,
"initialPage": "https://localhost:5432/workbench", "initialPage": "https://{tenantDomain}/_layouts/workbench.aspx"
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
} }

View File

@ -1,7 +1,16 @@
'use strict'; 'use strict';
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web'); 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.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
build.initialize(gulp); 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'));

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
"version": "0.0.1", "version": "0.0.1",
"private": true, "private": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=16.13.0 <17.0.0 || >=18.17.1 <19.0.0"
}, },
"scripts": { "scripts": {
"build": "gulp bundle", "build": "gulp bundle",
@ -11,31 +11,39 @@
"test": "gulp test" "test": "gulp test"
}, },
"dependencies": { "dependencies": {
"@microsoft/sp-core-library": "1.11.0", "@fluentui/react": "8.106.4",
"@microsoft/sp-lodash-subset": "1.11.0", "@microsoft/sp-adaptive-card-extension-base": "1.18.2",
"@microsoft/sp-office-ui-fabric-core": "1.11.0", "@microsoft/sp-core-library": "1.18.2",
"@microsoft/sp-property-pane": "1.16.1", "@microsoft/sp-lodash-subset": "1.18.2",
"@microsoft/sp-webpart-base": "1.16.1", "@microsoft/sp-office-ui-fabric-core": "1.18.2",
"@pnp/sp": "^2.0.6", "@microsoft/sp-property-pane": "1.18.2",
"@microsoft/sp-webpart-base": "1.18.2",
"@pnp/sp": "^4.2.0",
"array-to-tree": "^3.3.0", "array-to-tree": "^3.3.0",
"office-ui-fabric-react": "6.214.0", "react": "17.0.1",
"react": "16.8.5", "react-dom": "17.0.1",
"react-dom": "16.8.5", "react-orgchart": "^1.0.5",
"react-orgchart": "^1.0.5" "tslib": "2.3.1"
}, },
"resolutions": { "resolutions": {
"@types/react": "16.8.8" "@types/react": "16.8.8"
}, },
"devDependencies": { "devDependencies": {
"@microsoft/eslint-config-spfx": "1.18.2",
"@microsoft/eslint-plugin-spfx": "1.18.2",
"@microsoft/rush-stack-compiler-3.3": "0.3.5", "@microsoft/rush-stack-compiler-3.3": "0.3.5",
"@microsoft/sp-build-web": "1.16.1", "@microsoft/rush-stack-compiler-4.7": "0.1.0",
"@microsoft/sp-module-interfaces": "1.11.0", "@microsoft/sp-build-web": "1.18.2",
"@microsoft/sp-tslint-rules": "1.11.0", "@microsoft/sp-module-interfaces": "1.18.2",
"@microsoft/sp-webpart-workbench": "1.12.1", "@rushstack/eslint-config": "2.5.1",
"@types/chai": "3.4.34", "@types/react": "17.0.45",
"@types/mocha": "2.2.38", "@types/react-dom": "17.0.17",
"ajv": "~6.12.3", "@types/webpack-env": "1.15.2",
"gulp": "~4.0.2" "ajv": "6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.7.4"
}, },
"main": "lib/index.js" "main": "lib/index.js"
} }

View File

@ -3,29 +3,17 @@ import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library'; import { Version } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base"; import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IPropertyPaneConfiguration, PropertyPaneTextField } from "@microsoft/sp-property-pane"; import { IPropertyPaneConfiguration, PropertyPaneTextField } from "@microsoft/sp-property-pane";
import * as strings from 'ReactHierarchyViewWebPartStrings'; import * as strings from 'ReactHierarchyViewWebPartStrings';
import ReactHierarchyView from './components/ReactHierarchyView'; import ReactHierarchyView from './components/ReactHierarchyView';
import { IReactHierarchyViewProps } from './components/IReactHierarchyViewProps'; import { IReactHierarchyViewProps } from './components/IReactHierarchyViewProps';
import {
Environment,
EnvironmentType,
ServiceScope
} from '@microsoft/sp-core-library';
import { sp } from "@pnp/sp/presets/all";
export interface IReactHierarchyViewWebPartProps { export interface IReactHierarchyViewWebPartProps {
listName: string; listName: string;
} }
export default class ReactHierarchyViewWebPart extends BaseClientSideWebPart<IReactHierarchyViewWebPartProps> { export default class ReactHierarchyViewWebPart extends BaseClientSideWebPart<IReactHierarchyViewWebPartProps> {
public async onInit(): Promise<void> { public async onInit(): Promise<void> {
return super.onInit().then(_ => { await super.onInit();
sp.setup({
spfxContext: this.context
});
});
} }
public render(): void { public render(): void {

View File

@ -1,8 +1,7 @@
@import '~office-ui-fabric-react/dist/sass/References.scss'; @import '~@fluentui/react/dist/sass/References.scss';
@import '~react-orgchart/index.css';
:global(#workbenchPageContent) { :global(#workbenchPageContent) {
max-width: initial; max-width: initial;
} }
:global(.initechNode) { :global(.initechNode) {
@ -26,12 +25,59 @@
border-top: 2px solid #005a9e; border-top: 2px solid #005a9e;
} }
:global(.reactOrgChart .orgNodeChildGroup .nodeGroupLineVerticalMiddle) { :global(.reactOrgChart .orgNodeChildGroup .nodeGroupLineVerticalMiddle) {
border-right: 2px solid #005a9e; border-right: 2px solid #005a9e;
} }
:global(.reactOrgChart) {
margin: 2px;
}
:global(.reactOrgChart .orgNodeChildGroup .node) {
border: solid 1px #000000;
display: inline-block;
padding: 4px;
width: 100px;
}
:global(.reactOrgChart .orgNodeChildGroup .nodeCell) {
text-align: center;
}
:global(.reactOrgChart .orgNodeChildGroup .nodeGroupCell) {
vertical-align: top;
}
:global(.reactOrgChart .orgNodeChildGroup .nodeGroupLineVerticalMiddle) {
height: 25px;
width: 50%;
border-right: 2px solid #000;
}
:global(.reactOrgChart .nodeLineBorderTop) {
border-top: solid 2px #000;
}
:global(.reactOrgChart table) {
border-collapse: collapse;
border: none;
margin: 0 auto;
}
:global(.reactOrgChart td) {
padding: 0;
}
:global(.reactOrgChart table.nodeLineTable) {
width: 100%;
}
:global(.reactOrgChart table td.nodeCell) {
width: 50%;
}
.reactHierarchyView { .reactHierarchyView {
.container { .container {
max-width: 700px; max-width: 700px;
margin: 0px auto; 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); //box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
@ -85,7 +131,7 @@
// Basic Button // Basic Button
outline: transparent; outline: transparent;
position: relative; position: relative;
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif; font-family: "Segoe UI WestEuropean", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
font-size: $ms-font-size-m; font-size: $ms-font-size-m;
font-weight: $ms-font-weight-regular; font-weight: $ms-font-weight-regular;

View File

@ -1,16 +1,12 @@
import * as React from 'react'; import * as React from 'react';
import styles from './ReactHierarchyView.module.scss'; import styles from './ReactHierarchyView.module.scss';
import { IReactHierarchyViewProps } from './IReactHierarchyViewProps'; import { IReactHierarchyViewProps } from './IReactHierarchyViewProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { IHierarchyService } from '../interfaces'; import { IHierarchyService } from '../interfaces';
import { IHierarchyItem, Item } from '../interfaces/IHierarchyItem'; import { HierarchyItem, ISPHierarchyItem } from '../interfaces/IHierarchyItem';
import OrgChart from 'react-orgchart'; import OrgChart from 'react-orgchart';
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar'; import { MessageBar, MessageBarType, Spinner } from '@fluentui/react';
import { HierarchyService } from '../services'; import { HierarchyService } from '../services';
import { MockHierarchyService } from '../mocks'; import { ServiceScope } from '@microsoft/sp-core-library';
import { ServiceScope, Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner';
export interface IReactHierarchyState { export interface IReactHierarchyState {
hierarchyItems: any; hierarchyItems: any;
@ -32,74 +28,53 @@ export default class ReactHierarchyView extends React.Component<IReactHierarchyV
}; };
} }
public async componentDidMount() { public async componentDidMount(): Promise<void> {
this.loadHierarchyView(this.props.listName); this.loadHierarchyView(this.props.listName);
} }
public componentWillReceiveProps(nextProps: IReactHierarchyViewProps) { public componentDidUpdate(newProps: IReactHierarchyViewProps): void {
this.loadHierarchyView(nextProps.listName); this.loadHierarchyView(newProps.listName);
} }
private loadHierarchyView(listName: string): void { private loadHierarchyView(listName: string): void {
let serviceScope: ServiceScope = this.props.serviceScope; const serviceScope: ServiceScope = this.props.serviceScope;
// Based on the type of environment, return the correct instance of the IHierarchyServiceInstance interface // Mapping to be used when web part runs in SharePoint.
if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) { this.HierarchyServiceInstance = serviceScope.consume(HierarchyService.serviceKey);
// Mapping to be used when webpart runs in SharePoint.
this.HierarchyServiceInstance = serviceScope.consume(HierarchyService.serviceKey);
}
else {
// This means webpart is running in the local workbench or from a unit test.
// So we will need a non default implementation of the IHierarchyServiceInstance i.e. MockHierarchyService
this.HierarchyServiceInstance = serviceScope.consume(MockHierarchyService.serviceKey);
}
this.HierarchyServiceInstance.getHierarchyInfo(listName).then((hierarchyItems: any) => { this.HierarchyServiceInstance.getHierarchyInfo(listName).then((hierarchyItems: ISPHierarchyItem[]) => {
if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) { if (hierarchyItems.length > 0) {
if (hierarchyItems.length > 0) { const hierarchyNodes: Array<HierarchyItem> = [];
let hierarchyNodes: Array<Item> = []; for (let count = 0; count < hierarchyItems.length; count++) {
var count: number; hierarchyNodes.push(new HierarchyItem(hierarchyItems[count].Id, hierarchyItems[count].Title, hierarchyItems[count].Url!, hierarchyItems[count].Parent ? hierarchyItems[count].Parent.Id : undefined));
for (count = 0; count < hierarchyItems.length; count++) {
hierarchyNodes.push(new Item(hierarchyItems[count].Id, hierarchyItems[count].Title, hierarchyItems[count].Url, hierarchyItems[count].Parent ? hierarchyItems[count].Parent.Id : undefined));
}
var arrayToTree: any = require('array-to-tree');
var orgChartHierarchyNodes: any = arrayToTree(hierarchyNodes);
var output: any = JSON.stringify(orgChartHierarchyNodes[0]);
this.setState({
hierarchyItems: JSON.parse(output),
isLoading: false,
showErrorMessage: false
});
} }
else {
this.setState({ const arrayToTree: any = require('array-to-tree');
hierarchyItems: [], const orgChartHierarchyNodes: any = arrayToTree(hierarchyNodes);
isLoading: false, const output: any = JSON.stringify(orgChartHierarchyNodes[0]);
showErrorMessage: true,
errorMessage: "No records to be displayed"
});
}
}
else {
this.setState({ this.setState({
hierarchyItems: JSON.parse(hierarchyItems), hierarchyItems: JSON.parse(output),
isLoading: false, isLoading: false,
showErrorMessage: false showErrorMessage: false
}); });
} }
}) else {
.catch((error) =>
this.setState({ this.setState({
hierarchyItems: [], hierarchyItems: [],
errorMessage: "Please verify web part configuration. Error details: " + error.message,
isLoading: false, isLoading: false,
showErrorMessage: true showErrorMessage: true,
}) errorMessage: "No records to be displayed"
); });
}
}).catch((error) =>
this.setState({
hierarchyItems: [],
errorMessage: "Please verify web part configuration. Error details: " + error.message,
isLoading: false,
showErrorMessage: true
})
);
} }
public render(): React.ReactElement<IReactHierarchyViewProps> { public render(): React.ReactElement<IReactHierarchyViewProps> {
@ -123,7 +98,7 @@ export default class ReactHierarchyView extends React.Component<IReactHierarchyV
); );
} }
private MyNodeComponent = ({ node }) => { private MyNodeComponent = ({ node }: { node: any }): React.ReactElement => {
if (node.url) { if (node.url) {
return ( return (
<div className="initechNode"> <div className="initechNode">

View File

@ -1,4 +1,4 @@
export interface IHierarchyItem { export interface ISPHierarchyItem {
Title: string; Title: string;
Id: number; Id: number;
parent_id: number; parent_id: number;
@ -6,11 +6,12 @@ export interface IHierarchyItem {
Parent: any; Parent: any;
} }
export class Item { export class HierarchyItem {
private id: number; id: number;
private title: string; title: string;
private url: string; url: string;
private parent_id?: number; parent_id?: number;
children?: HierarchyItem[];
constructor(id: number, title: string, url: string, parent_id?: number) { constructor(id: number, title: string, url: string, parent_id?: number) {
this.id = id; this.id = id;

View File

@ -1,6 +1,5 @@
import { ISPHierarchyItem } from "./IHierarchyItem";
export interface IHierarchyService { export interface IHierarchyService {
getHierarchyInfo: (listName?: string) => Promise<any>; getHierarchyInfo: (listName?: string) => Promise<ISPHierarchyItem[]>;
} }

View File

@ -1,54 +0,0 @@
import { IHierarchyService } from '../interfaces';
import { ServiceScope, ServiceKey } from '@microsoft/sp-core-library';
export class MockHierarchyService implements IHierarchyService {
public static readonly serviceKey: ServiceKey<IHierarchyService> = ServiceKey.create<IHierarchyService>('datacenter:MockHierarchyService', MockHierarchyService);
constructor(serviceScope: ServiceScope) {
}
public getHierarchyInfo(listName: string): Promise<any> {
const initechOrg: any =
{
id: 1,
title: "Microsoft",
url: {Description: "Microsoft", Url: "http://www.microsoft.com"},
children:[
{
id: 2,
title: "CMS",
url: null,
parent_id: 1,
children:[
{ id: 3, title: "SharePoint", parent_id: 2, url: null },
{ id: 5, title: "DotNetNuke", parent_id: 2, url: null },
{ id: 6, title: "Sitefinity", parent_id: 2, url: null }
]
},
{
id: 7,
title: "E-Commerce",
url: null,
parent_id: 1,
children:[
{ id: 8, title: "nopCommerce", parent_id: 7, url: null },
{ id: 9, title: "asp.net storetront", parent_id: 7, url: null }
]
},
{
id: 10,
title: "3rd Party",
url: null,
parent_id: 1,
children:[
{ id: 11, title: "Telerik", parent_id: 10, url: null },
{ id: 12, title: "DevExpress", parent_id: 10, url: null }
]
}
]
}
;
return new Promise<any>((resolve, reject) => {
resolve(JSON.stringify(initechOrg));
});
}
}

View File

@ -1 +0,0 @@
export { MockHierarchyService } from './MockHierarchyService';

View File

@ -1,32 +1,30 @@
import { IHierarchyService } from '../interfaces';
import { ServiceKey, ServiceScope } from '@microsoft/sp-core-library'; import { ServiceKey, ServiceScope } from '@microsoft/sp-core-library';
import { PageContext } from '@microsoft/sp-page-context'; import { PageContext } from '@microsoft/sp-page-context';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http'; import { IHierarchyService } from '../interfaces';
import { IHierarchyItem } from '../interfaces/IHierarchyItem'; import { ISPHierarchyItem } from '../interfaces/IHierarchyItem';
import { sp } from "@pnp/sp/presets/all"; import { SPFI, spfi, SPFx as spSPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
export class HierarchyService implements IHierarchyService { export class HierarchyService implements IHierarchyService {
public static readonly serviceKey: ServiceKey<IHierarchyService> = ServiceKey.create<IHierarchyService>('datacenter:hierarchyService', HierarchyService); public static readonly serviceKey: ServiceKey<IHierarchyService> = ServiceKey.create<IHierarchyService>('datacenter:hierarchyService', HierarchyService);
private _spHttpClient: SPHttpClient; private _sp: SPFI;
private _pageContext: PageContext;
private _currentWebUrl: string;
constructor(serviceScope: ServiceScope) { constructor(serviceScope: ServiceScope) {
serviceScope.whenFinished(() => { serviceScope.whenFinished(() => {
this._spHttpClient = serviceScope.consume(SPHttpClient.serviceKey); const pageContext = serviceScope.consume(PageContext.serviceKey);
this._pageContext = serviceScope.consume(PageContext.serviceKey); this._sp = spfi().using(spSPFx({ pageContext }));
this._currentWebUrl = this._pageContext.web.absoluteUrl;
}); });
} }
public getHierarchyInfo(listName: string): Promise<IHierarchyItem[]> { public getHierarchyInfo(listName: string): Promise<ISPHierarchyItem[]> {
return sp.web.lists.getByTitle(listName) return this._sp.web.lists.getByTitle(listName)
.items .items
.select('Title,Id,URL,Parent/Id,Parent/Title') .select("Title", "Id", "URL", "Parent/Id", "Parent/Title")
.expand('Parent') .expand("Parent")()
.get() .then((items: ISPHierarchyItem[]) => {
.then((items: IHierarchyItem[]) => {
return Promise.resolve(items); return Promise.resolve(items);
}).catch((error) => Promise.reject(error)); }).catch((error) => Promise.reject(error));
} }

View File

@ -1,5 +1,5 @@
{ {
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.3/includes/tsconfig-web.json", "extends": "./node_modules/@microsoft/rush-stack-compiler-4.7/includes/tsconfig-web.json",
"compilerOptions": { "compilerOptions": {
"target": "es5", "target": "es5",
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
@ -12,28 +12,24 @@
"skipLibCheck": true, "skipLibCheck": true,
"outDir": "lib", "outDir": "lib",
"inlineSources": false, "inlineSources": false,
"strictNullChecks": false, "noImplicitAny": false,
"noUnusedLocals": false,
"typeRoots": [ "typeRoots": [
"./node_modules/@types", "./node_modules/@types",
"./node_modules/@microsoft" "./node_modules/@microsoft"
], ],
"types": [ "types": [
"es6-promise",
"webpack-env" "webpack-env"
], ],
"lib": [ "lib": [
"es5", "es5",
"dom", "dom",
"es2015.collection" "es2015.collection",
"es2015.promise"
] ]
}, },
"include": [ "include": [
"src/**/*.ts", "src/**/*.ts",
"src/**/*.tsx" "src/**/*.tsx"
],
"exclude": [
"node_modules",
"lib"
] ]
} }

View File

@ -1,30 +0,0 @@
{
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}

View File

@ -15115,17 +15115,17 @@
"integrity": "sha512-8EZzEP0eKkEEVX+drtd9mtuQ+/QrlfW/5MlwcwK5Nds6EkZ/tRzEexkzUY2mIssnAyVLT+TKHuRXmFNNXYUd6g==" "integrity": "sha512-8EZzEP0eKkEEVX+drtd9mtuQ+/QrlfW/5MlwcwK5Nds6EkZ/tRzEexkzUY2mIssnAyVLT+TKHuRXmFNNXYUd6g=="
}, },
"node_modules/fast-xml-parser": { "node_modules/fast-xml-parser": {
"version": "4.2.4", "version": "4.4.1",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.2.4.tgz", "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz",
"integrity": "sha512-fbfMDvgBNIdDJLdLOwacjFAPYt67tr31H9ZhWSm45CDAxvd0I6WTlSOUo7K2P/K5sA5JgMKG64PI3DMcaFdWpQ==", "integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==",
"funding": [ "funding": [
{
"type": "paypal",
"url": "https://paypal.me/naturalintelligence"
},
{ {
"type": "github", "type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence" "url": "https://github.com/sponsors/NaturalIntelligence"
},
{
"type": "paypal",
"url": "https://paypal.me/naturalintelligence"
} }
], ],
"dependencies": { "dependencies": {
@ -41115,9 +41115,9 @@
"integrity": "sha512-8EZzEP0eKkEEVX+drtd9mtuQ+/QrlfW/5MlwcwK5Nds6EkZ/tRzEexkzUY2mIssnAyVLT+TKHuRXmFNNXYUd6g==" "integrity": "sha512-8EZzEP0eKkEEVX+drtd9mtuQ+/QrlfW/5MlwcwK5Nds6EkZ/tRzEexkzUY2mIssnAyVLT+TKHuRXmFNNXYUd6g=="
}, },
"fast-xml-parser": { "fast-xml-parser": {
"version": "4.2.4", "version": "4.4.1",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.2.4.tgz", "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz",
"integrity": "sha512-fbfMDvgBNIdDJLdLOwacjFAPYt67tr31H9ZhWSm45CDAxvd0I6WTlSOUo7K2P/K5sA5JgMKG64PI3DMcaFdWpQ==", "integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==",
"requires": { "requires": {
"strnum": "^1.0.5" "strnum": "^1.0.5"
} }

View File

@ -0,0 +1,38 @@
{
"name": "SPFx 1.18.2",
"image": "docker.io/m365pnp/spfx:1.18.2",
"customizations": {
"vscode": {
"extensions": [
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint"
]
}
},
"forwardPorts": [
4321,
35729,
5432
],
"portsAttributes": {
"4321": {
"protocol": "https",
"label": "Manifest",
"onAutoForward": "silent",
"requireLocalPort": true
},
"5432": {
"protocol": "https",
"label": "Workbench",
"onAutoForward": "silent"
},
"35729": {
"protocol": "https",
"label": "LiveReload",
"onAutoForward": "silent",
"requireLocalPort": true
}
},
"postCreateCommand": "bash .devcontainer/spfx-startup.sh",
"remoteUser": "node"
}

View File

@ -0,0 +1,33 @@
echo
echo -e "\e[1;94mInstalling Node dependencies\e[0m"
npm install
## commands to create dev certificate and copy it to the root folder of the project
echo
echo -e "\e[1;94mGenerating dev certificate\e[0m"
gulp trust-dev-cert
# Convert the generated PEM certificate to a CER certificate
openssl x509 -inform PEM -in ~/.rushstack/rushstack-serve.pem -outform DER -out ./spfx-dev-cert.cer
# Copy the PEM ecrtificate for non-Windows hosts
cp ~/.rushstack/rushstack-serve.pem ./spfx-dev-cert.pem
## add *.cer to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.cer' ./.gitignore
then
echo "# .CER Certificates" >> .gitignore
echo "*.cer" >> .gitignore
fi
## add *.pem to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.pem' ./.gitignore
then
echo "# .PEM Certificates" >> .gitignore
echo "*.pem" >> .gitignore
fi
echo
echo -e "\e[1;92mReady!\e[0m"
echo -e "\n\e[1;94m**********\nOptional: if you plan on using gulp serve, don't forget to add the container certificate to your local machine. Please visit https://aka.ms/spfx-devcontainer for more information\n**********"

View File

@ -0,0 +1,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'off',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {}
}
]
};

View File

@ -0,0 +1,35 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
.heft
# 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
src/services/azFunct.json

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 @@
v18.18.2

View File

@ -0,0 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"nodeVersion": "18.18.2",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.12.0"
},
"version": "1.18.2",
"libraryName": "react-site-secure-function-call-smpl",
"libraryId": "4c840868-01ef-4d2a-9168-5b10524c0096",
"environment": "spo",
"packageManager": "npm",
"solutionName": "react-site-secure-function-call-smpl",
"solutionShortDescription": "react-site-secure-function-call-smpl description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.34928.147
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleConsumeFunc", "SampleConumeFunc\SampleConsumeFunc.csproj", "{14E45904-2865-41B8-8F50-CD0482388B99}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{14E45904-2865-41B8-8F50-CD0482388B99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{14E45904-2865-41B8-8F50-CD0482388B99}.Debug|Any CPU.Build.0 = Debug|Any CPU
{14E45904-2865-41B8-8F50-CD0482388B99}.Release|Any CPU.ActiveCfg = Release|Any CPU
{14E45904-2865-41B8-8F50-CD0482388B99}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A1798142-70B2-43F3-A317-290D752AB945}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,264 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# Azure Functions localsettings file
local.settings.json
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
#*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

View File

@ -0,0 +1,9 @@

namespace SampleConsumeFunc.Model
{
internal class Request
{
public string URL { get; set; }
public string Descreption { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SampleConsumeFunc.Services;
var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureAppConfiguration((hostContext, config) =>
{
config.AddJsonFile("host.json", optional: true);
})
.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetryWorkerService();
services.AddSingleton<ITokenValidationService, TokenValidationService>();
services.AddSingleton<IGraphService, GraphService>();
services.ConfigureFunctionsApplicationInsights();
})
.Build();
host.Run();

View File

@ -0,0 +1,9 @@
{
"profiles": {
"SampleConumeFunc": {
"commandName": "Project",
"commandLineArgs": "--port 7241",
"launchBrowser": false
}
}
}

View File

@ -0,0 +1,11 @@
{
"dependencies": {
"appInsights1": {
"type": "appInsights"
},
"storage1": {
"type": "storage",
"connectionId": "AzureWebJobsStorage"
}
}
}

View File

@ -0,0 +1,11 @@
{
"dependencies": {
"appInsights1": {
"type": "appInsights.sdk"
},
"storage1": {
"type": "storage.emulator",
"connectionId": "AzureWebJobsStorage"
}
}
}

View File

@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Azure.Identity" Version="1.11.3" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.22.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.2.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="1.3.1" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.17.0" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.2.0" />
<PackageReference Include="Microsoft.Graph" Version="5.56.0" />
<PackageReference Include="Microsoft.IdentityModel" Version="7.0.0" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="7.6.0" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.sample.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,69 @@
using Azure.Core;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Sites.Item;
namespace SampleConsumeFunc.Services
{
public class GraphService : IGraphService
{
private readonly IConfiguration _config;
private readonly ILogger _logger;
private GraphServiceClient? _appGraphClient;
public GraphService(IConfiguration config, ILogger<GraphService> logger)
{
_config = config;
_logger = logger;
}
public async Task<bool> UpdateSiteDescreption(string userAssertion, string siteUrl, string newSiteDescreption)
{
_appGraphClient = GetUserGraphClient(userAssertion);
Uri uri = new Uri(siteUrl);
string domain = uri.Host;
var path = uri.LocalPath;
var site = await _appGraphClient.Sites[$"{domain}:{path}"].GetAsync();
var newSite = new Site
{
Description = newSiteDescreption
};
try
{
await _appGraphClient.Sites[site.Id].PatchAsync(newSite);
}
catch (Microsoft.Graph.Models.ODataErrors.ODataError ex)
{
_logger.LogError(ex.Message);
}
return true;
}
public GraphServiceClient? GetUserGraphClient(string userAssertion)
{
var tenantId = _config["tenantId"];
var clientId = _config["clientId"];
var clientSecret = _config["clientSecret"];
var scopes = new[] { "https://graph.microsoft.com/.default" };
if (string.IsNullOrEmpty(tenantId) ||
string.IsNullOrEmpty(clientId) ||
string.IsNullOrEmpty(clientSecret))
{
_logger.LogError("Required settings missing: 'tenantId', 'clientId', or 'clientSecret'.");
return null;
}
var onBehalfOfCredential = new OnBehalfOfCredential(
tenantId, clientId, clientSecret, userAssertion);
return new GraphServiceClient(onBehalfOfCredential, scopes);
}
}
}

View File

@ -0,0 +1,10 @@
using Microsoft.Graph;
namespace SampleConsumeFunc.Services
{
public interface IGraphService
{
public GraphServiceClient? GetUserGraphClient(string userAssertion);
public Task<bool> UpdateSiteDescreption(string userAssertion, string siteUrl, string newSiteDescreption);
}
}

View File

@ -0,0 +1,10 @@
using Microsoft.Azure.Functions.Worker.Http;
namespace SampleConsumeFunc.Services
{
public interface ITokenValidationService
{
public Task<string?> ValidateAuthorizationHeaderAsync(
HttpRequestData request);
}
}

View File

@ -0,0 +1,99 @@
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
namespace SampleConsumeFunc.Services
{
public class TokenValidationService : ITokenValidationService
{
private TokenValidationParameters? _validationParameters;
private readonly IConfiguration _config;
private readonly ILogger _logger;
public TokenValidationService(IConfiguration config, ILogger<TokenValidationService> logger)
{
_config = config;
_logger = logger;
}
public async Task<string> ValidateAuthorizationHeaderAsync(Microsoft.Azure.Functions.Worker.Http.HttpRequestData request)
{
// The incoming request should have an Authorization header
if (request.Headers.TryGetValues("authorization", out IEnumerable<string>? authValues))
{
var authHeader = AuthenticationHeaderValue.Parse(authValues.ToArray().First());
// Make sure that the value is "Bearer token-value"
if (authHeader != null &&
string.Compare(authHeader.Scheme, "bearer", true, CultureInfo.InvariantCulture) == 0 &&
!string.IsNullOrEmpty(authHeader.Parameter))
{
var validationParameters = await GetTokenValidationParametersAsync();
if (validationParameters == null)
{
return null;
}
var tokenHandler = new JwtSecurityTokenHandler();
try
{
// Validate the token
var result = tokenHandler.ValidateToken(authHeader.Parameter,
_validationParameters, out SecurityToken jwtToken);
// If ValidateToken did not throw an exception, token is valid.
return authHeader.Parameter;
}
catch (Exception exception)
{
_logger.LogError(exception, "Error validating bearer token");
}
}
}
return null;
}
private async Task<TokenValidationParameters?> GetTokenValidationParametersAsync()
{
if (_validationParameters == null)
{
// Get tenant ID and client ID
var tenantId = _config["tenantId"];
var clientId = _config["clientId"];
var domain = _config["domain"];
if (string.IsNullOrEmpty(tenantId) ||
string.IsNullOrEmpty(clientId))
{
_logger.LogError("Required settings missing: 'tenantId' and 'clientId'.");
return null;
}
// Load the tenant-specific OpenID config from Azure
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(
$"https://login.microsoftonline.com/{tenantId}/.well-known/openid-configuration",
new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync();
_validationParameters = new TokenValidationParameters
{
// Use signing keys retrieved from Azure
IssuerSigningKeys = config.SigningKeys,
ValidateAudience = true,
// Audience MUST be the Expoxed app ID for the Web API
ValidAudience = $"api://{domain}/{clientId}",
ValidateIssuer = true,
// Use the issuer retrieved from Azure
ValidIssuer = config.Issuer,
ValidateLifetime = true
};
}
return _validationParameters;
}
}
}

View File

@ -0,0 +1,59 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SampleConsumeFunc.Model;
using SampleConsumeFunc.Services;
using System.Text;
using System.Text.Json;
namespace SampleConsumeFunc
{
public class SiteFunction
{
private readonly ITokenValidationService _tokenValidationService;
private readonly IGraphService _graphClientService;
private readonly ILogger<SiteFunction> _logger;
private readonly IConfiguration _config;
public SiteFunction(ITokenValidationService tokenValidationService, IGraphService graphClientService, ILogger<SiteFunction> logger, IConfiguration config)
{
_tokenValidationService = tokenValidationService;
_graphClientService = graphClientService;
_logger = logger;
_config = config;
}
[Function("SiteFunction")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
{
_logger.LogInformation("C# HTTP trigger function processed a request.");
var bearerToken = await _tokenValidationService
.ValidateAuthorizationHeaderAsync(req);
string siteUrl = req.Query["URL"];
string siteDescreption = req.Query["Descreption"];
// For a potential POST
//string bodyContents;
//using (Stream receiveStream = req.Body)
//{
// using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
// {
// bodyContents = readStream.ReadToEndAsync().Result;
// }
//}
//var body = JsonSerializer.Deserialize<Request>(bodyContents);
//_logger.LogInformation($"URL: {body.URL}");
//_logger.LogInformation($"URL: {body.Descreption}");
//string siteUrl = body.URL;
//string siteDescreption = body.Descreption;
bool siteDescreptionUpdated = await _graphClientService.UpdateSiteDescreption(bearerToken, siteUrl, siteDescreption);
return siteDescreptionUpdated ? new OkObjectResult("") : new BadRequestResult();
}
}
}

View File

@ -0,0 +1,12 @@
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
},
"enableLiveMetricsFilters": true
}
}
}

View File

@ -0,0 +1,14 @@
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"tenantId": "",
"clientId": "",
"clientSecret": "",
"domain": "xxx.azurewebsites.net"
},
"Host": {
"CORS": "*"
}
}

View File

@ -0,0 +1,109 @@
# Site Secure Function Call
## Summary
This combined SharpPoint Framework and Azure Function solution is to provide the potentially most secure access from SharePoint Framework to any kind of third party API, in fact here Microsoft Graph. It shows that AadHttpClient should be preferred over MSGraphClient.
|Update site description|
:-------------------------:
![Update site description](assets/SetSiteDescreption.png)
For further details see the author's [blog post](https://mmsharepoint.wordpress.com/2024/06/18/calling-microsoft-graph-in-spfx-the-secure-way/SS)
## Compatibility
| :warning: Important |
|:---------------------------|
| Every SPFx version is optimally compatible with specific versions of Node.js. In order to be able to build this sample, you need to ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
This sample is optimally compatible with the following environment configuration:
![SPFx 1.18.2](https://img.shields.io/badge/SPFx-1.18.2-green.svg)
![Node.js v16 | v18](https://img.shields.io/badge/Node.js-v16%20%7C%20v18-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![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)
- [AzureFunctions .Net8 *LTS](https://learn.microsoft.com/en-us/azure/azure-functions/functions-overview?pivots=programming-language-csharp?WT.mc_id=M365-MVP-5004617)
## Version history
Version|Date|Author|Comments
-------|----|--------|--------
1.0|July 12, 2024|[Markus Moeller](http://www.twitter.com/moeller2_0)|Initial release
## Minimal Path to Awesome
- Clone this repository
```bash
git clone https://github.com/pnp/sp-dev-fx-webparts.git
```
- You will need to register an app in Entra ID
- with client secret
- with **delegated** Graph permission Sites.FullControl.All
- With exposed Api "access_as_user" and App ID Uri api://[Your-Desired-Func-Url]/[Your-ClienID]
- Azure Function:
- Rename local.sample.settings.json to local.settings.json and fill out tenantId, clientId, clientSecret and domain [Your-Desired-Func-Url]
- Run F5
- SPFx web part
- Move to web part folder
```bash
cd samples\react-site-secure-function-call
```
- Rename azFunct.sample.json to azFunct.json and fill out appIdUri api://[Your-Desired-Func-Url]/[Your-ClienID]
- Ensure that you are at the solution folder
- in the command-line run:
- `npm install`
- `gulp serve`
> Include any additional steps as needed.
## Features
Description of the extension that expands upon high-level summary above.
This extension illustrates the following concepts:
- [Consume multi-tenant enterprise APIs secured with Azure AD in SharePoint Framework](https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient-enterpriseapi-multitenant?WT.mc_id=M365-MVP-5004617)
## References
- [Getting started with SharePoint Framework](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
- [Building for Microsoft teams](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/build-for-teams-overview)
- [Use Microsoft Graph in your solution](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/using-microsoft-graph-apis?WT.mc_id=M365-MVP-5004617)
- [Publish SharePoint Framework applications to the Marketplace](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/publish-to-marketplace-overview)
- [Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) - Guidance, tooling, samples and open-source controls for your Microsoft 365 development
## Help
We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.
You can try looking at [issues related to this sample](https://github.com/pnp/sp-dev-fx-webparts/issues?q=label%3A%22sample%3A%20react-site-secure-function-call%22) to see if anybody else is having the same issues.
You can also try looking at [discussions related to this sample](https://github.com/pnp/sp-dev-fx-webparts/discussions?discussions_q=react-site-secure-function-call) and see what the community is saying.
If you encounter any issues using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-site-secure-function-call&template=bug-report.yml&sample=react-site-secure-function-call&authors=@mmsharepoint&title=react-site-secure-function-call%20-%20).
For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aquestion%2Csample%3A%20react-site-secure-function-call&template=question.yml&sample=react-site-secure-function-call&authors=@mmsharepoint&title=react-site-secure-function-call%20-%20).
Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aenhancement%2Csample%3A%20react-site-secure-function-call&template=suggestion.yml&sample=react-site-secure-function-call&authors=@mmsharepoint&title=react-site-secure-function-call%20-%20).
## 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.**
<img src="https://m365-visitor-stats.azurewebsites.net/sp-dev-fx-webparts/samples/react-site-secure-function-call" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View File

@ -0,0 +1,49 @@
[
{
"name": "pnp-sp-dev-spfx-web-parts-react-site-secure-function-call",
"source": "pnp",
"title": "Site Secure Function Call",
"shortDescription": "This combined SharePoint Framework and Azure Function solution is to provide the potentially most secure access from SharePoint Framework to any kind of third party API or Microsoft Graph.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-office-offer-creation",
"longDescription": [
"This combined SharePoint Framework and Azure Function solution is to provide the potentially most secure access from SharePoint Framework to any kind of third party API, in fact here Microsoft Graph. It shows that AadHttpClient should be preferred over MSGraphClient."
],
"creationDateTime": "2024-07-12",
"updateDateTime": "2024-07-12",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "React"
},
{
"key": "SPFX-VERSION",
"value": "1.18.2"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-site-secure-function-call/assets/SetSiteDescreption.gif",
"alt": "App in action"
}
],
"authors": [
{
"gitHubAccount": "mmsharepoint",
"pictureUrl": "https://github.com/mmsharepoint.png",
"name": "Markus Moeller"
}
],
"references": [
{
"name": "Build your first SharePoint client-side web part",
"description": "Client-side web parts are client-side components that run in the context of a SharePoint page. Client-side web parts can be deployed to SharePoint environments that support the SharePoint Framework. You can also use modern JavaScript web frameworks, tools, and libraries to build them.",
"url": "https://learn.microsoft.com/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
}
]

View File

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"sample-site-function-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/sampleSiteFunction/SampleSiteFunctionWebPart.js",
"manifest": "./src/webparts/sampleSiteFunction/SampleSiteFunctionWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"SampleSiteFunctionWebPartStrings": "lib/webparts/sampleSiteFunction/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-site-secure-function-call-smpl",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,46 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-site-secure-function-call-smpl-client-side-solution",
"id": "4c840868-01ef-4d2a-9168-5b10524c0096",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.18.2"
},
"metadata": {
"shortDescription": {
"default": "react-site-secure-function-call-smpl description"
},
"longDescription": {
"default": "react-site-secure-function-call-smpl description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-site-secure-function-call-smpl Feature",
"description": "The feature that activates elements of the react-site-secure-function-call-smpl solution.",
"id": "b95485a2-0f8a-4027-9091-383c9138841d",
"version": "1.0.0.0"
}
],
"webApiPermissionRequests": [
{
"resource": "0a8dfbc9-0423-495b-a1e6-1055f0ca69c2",
"scope": "user_impersonation"
}
]
},
"paths": {
"zippedPackage": "solution/react-site-secure-function-call-smpl.sppkg"
}
}

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://{tenantDomain}/_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 -->"
}

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'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,42 @@
{
"name": "react-site-secure-function-call-smpl",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=16.13.0 <17.0.0 || >=18.17.1 <19.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"tslib": "2.3.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"@fluentui/react": "^8.106.4",
"@microsoft/sp-core-library": "1.18.2",
"@microsoft/sp-component-base": "1.18.2",
"@microsoft/sp-property-pane": "1.18.2",
"@microsoft/sp-webpart-base": "1.18.2",
"@microsoft/sp-lodash-subset": "1.18.2",
"@microsoft/sp-office-ui-fabric-core": "1.18.2"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-4.7": "0.1.0",
"@rushstack/eslint-config": "2.5.1",
"@microsoft/eslint-plugin-spfx": "1.18.2",
"@microsoft/eslint-config-spfx": "1.18.2",
"@microsoft/sp-build-web": "1.18.2",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"eslint": "8.7.0",
"gulp": "4.0.2",
"typescript": "4.7.4",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"eslint-plugin-react-hooks": "4.3.0",
"@microsoft/sp-module-interfaces": "1.18.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,45 @@
import { ServiceKey, ServiceScope } from "@microsoft/sp-core-library";
import { AadHttpClientFactory, AadHttpClient, HttpClientResponse } from "@microsoft/sp-http";
const config = require('./azFunct.json');
export default class FunctionService {
private aadHttpClientFactory: AadHttpClientFactory;
private client: AadHttpClient;
public static readonly servicaeKey: ServiceKey<FunctionService> =
ServiceKey.create<FunctionService>('react-site-secure-function-call-smpl', FunctionService);
constructor(serviceScope: ServiceScope) {
serviceScope.whenFinished(async () => {
this.aadHttpClientFactory = serviceScope.consume(AadHttpClientFactory.serviceKey);
});
}
public async setNewSiteDescreption(siteUrl: string, siteDescreption: string): Promise<boolean> {
this.client = await this.aadHttpClientFactory.getClient(`${config.appIdUri}`);
const requestUrl = `${config.hostUrl}/api/SiteFunction?URL=${siteUrl}&Descreption=${siteDescreption}`;
return this.client
.get(requestUrl, AadHttpClient.configurations.v1)
.then((response: HttpClientResponse) => {
return response.ok;
});
// POST alternative
/* const requestUrl = `http://localhost:7241/api/SiteFunction`;
const requestBody = {
URL: siteUrl,
Descreption: siteDescreption
};
return this.client
.post(requestUrl, AadHttpClient.configurations.v1,
{
body: JSON.stringify(requestBody)
}
)
.then((response: HttpClientResponse) => {
return response.json();
}); */
}
}

View File

@ -0,0 +1,4 @@
{
"hostUrl": "http://localhost:7241",
"appIdUri": "api://xxx.azurewebsites.net/CLIENTID"
}

View File

@ -0,0 +1,28 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "57fee02a-4599-4034-b0d4-eee96dd9137a",
"alias": "SampleSiteFunctionWebPart",
"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", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Advanced
"group": { "default": "Advanced" },
"title": { "default": "SampleSiteFunction" },
"description": { "default": "SampleSiteFunction description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "SampleSiteFunction"
}
}]
}

View File

@ -0,0 +1,88 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
type IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import * as strings from 'SampleSiteFunctionWebPartStrings';
import { SampleSiteFunction } from './components/SampleSiteFunction';
import { ISampleSiteFunctionProps } from './components/ISampleSiteFunctionProps';
export interface ISampleSiteFunctionWebPartProps {
description: string;
}
export default class SampleSiteFunctionWebPart extends BaseClientSideWebPart<ISampleSiteFunctionWebPartProps> {
private _isDarkTheme: boolean = false;
public render(): void {
const element: React.ReactElement<ISampleSiteFunctionProps> = React.createElement(
SampleSiteFunction,
{
serviceScope: this.context.serviceScope,
isDarkTheme: this._isDarkTheme,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userDisplayName: this.context.pageContext.user.displayName
}
);
ReactDom.render(element, this.domElement);
}
protected onInit(): Promise<void> {
return Promise.resolve();
}
protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void {
if (!currentTheme) {
return;
}
this._isDarkTheme = !!currentTheme.isInverted;
const {
semanticColors
} = currentTheme;
if (semanticColors) {
this.domElement.style.setProperty('--bodyText', semanticColors.bodyText || null);
this.domElement.style.setProperty('--link', semanticColors.link || null);
this.domElement.style.setProperty('--linkHovered', semanticColors.linkHovered || null);
}
}
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
})
]
}
]
}
]
};
}
}

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,8 @@
import { ServiceScope } from "@microsoft/sp-core-library";
export interface ISampleSiteFunctionProps {
hasTeamsContext: boolean;
userDisplayName: string;
serviceScope: ServiceScope;
isDarkTheme: boolean;
}

View File

@ -0,0 +1,20 @@
@import '~@fluentui/react/dist/sass/References.scss';
.sampleSiteFunction {
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
.welcome {
text-align: center;
}
.field {
text-align: center;
padding: 12px;
}

View File

@ -0,0 +1,56 @@
import * as React from 'react';
import styles from './SampleSiteFunction.module.scss';
import * as strings from 'SampleSiteFunctionWebPartStrings';
import type { ISampleSiteFunctionProps } from './ISampleSiteFunctionProps';
import { PrimaryButton } from '@fluentui/react/lib/Button';
import { TextField } from "@fluentui/react/lib/TextField";
import FunctionService from '../../../services/FunctionService';
export const SampleSiteFunction: React.FC<ISampleSiteFunctionProps> = (props) => {
const [url, setUrl] = React.useState<string>('');
const [description, setDescription] = React.useState<string>('');
const onUrlChange = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, value: string): void => {
setUrl(value);
};
const onDescriptionChange = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, value: string): void => {
setDescription(value);
};
const assignPermissions = async (): Promise<void> => {
const graphService = new FunctionService(props.serviceScope);
const resp = await graphService.setNewSiteDescreption(url, description);
console.log(resp);
};
return (
<section className={`${styles.sampleSiteFunction} ${props.hasTeamsContext ? styles.teams : ''}`}>
<div className={styles.field}>
<h2>{strings.HeaderLabel}</h2>
</div>
<div className={styles.field}>
<TextField
label={strings.URLLabel}
value={url}
// eslint-disable-next-line react/jsx-no-bind
onChange={onUrlChange}
placeholder={strings.URLPlaceholder} />
</div>
<div className={styles.field}>
<TextField
label={strings.NewDescriptionLabel}
value={description}
// eslint-disable-next-line react/jsx-no-bind
onChange={onDescriptionChange}
placeholder={strings.NewDescriptionPlaceholder} />
</div>
<div className={styles.field}>
<PrimaryButton text={strings.SetNewDescriptionLabel}
onClick={assignPermissions}
allowDisabledFocus />
</div>
</section>
);
}

View File

@ -0,0 +1,22 @@
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",
"AppLocalEnvironmentOffice": "The app is running on your local environment in office.com",
"AppLocalEnvironmentOutlook": "The app is running on your local environment in Outlook",
"AppSharePointEnvironment": "The app is running on SharePoint page",
"AppTeamsTabEnvironment": "The app is running in Microsoft Teams",
"AppOfficeEnvironment": "The app is running in office.com",
"AppOutlookEnvironment": "The app is running in Outlook",
"UnknownEnvironment": "The app is running in an unknown environment",
"HeaderLabel": "Update Site description",
"URLLabel": "URL",
"URLPlaceholder": "Please enter a URL",
"NewDescriptionLabel": "New description",
"NewDescriptionPlaceholder": "Please enter a New description",
"SetNewDescriptionLabel": "Set new description"
}
});

View File

@ -0,0 +1,25 @@
declare interface ISampleSiteFunctionWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppLocalEnvironmentOffice: string;
AppLocalEnvironmentOutlook: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
AppOfficeEnvironment: string;
AppOutlookEnvironment: string;
UnknownEnvironment: string;
HeaderLabel: string;
URLLabel: string;
URLPlaceholder: string;
NewDescriptionLabel: string;
NewDescriptionPlaceholder: string;
SetNewDescriptionLabel: string;
}
declare module 'SampleSiteFunctionWebPartStrings' {
const strings: ISampleSiteFunctionWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 249 B

View File

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