react-news-extension sample added

This commit is contained in:
Ejaz Hussain 2023-10-04 21:22:21 +01:00
parent 5459dd34de
commit 5a58f4f414
53 changed files with 81472 additions and 0 deletions

View File

@ -0,0 +1,379 @@
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: {
semi: 2, //Added by //O3C
"react/jsx-no-target-blank": 0, //O3C
// 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": [
0, //O3C
{
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": 0, //O3C
// 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": 0, // FRESH
// 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/no-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": 0, //O3C
// 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": 0, //O3C
},
},
{
// 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: {
"no-new": 0,
"class-name": 0,
"export-name": 0,
forin: 0,
"label-position": 0,
"member-access": 2,
"no-arg": 0,
"no-console": 0,
"no-construct": 0,
"no-duplicate-variable": 2,
"no-eval": 0,
"no-function-expression": 2,
"no-internal-module": 2,
"no-shadowed-variable": 2,
"no-switch-case-fall-through": 2,
"no-unnecessary-semicolons": 2,
"no-unused-expression": 2,
"no-with-statement": 2,
semicolon: 2,
"trailing-comma": 0,
typedef: 0,
"typedef-whitespace": 0,
"use-named-parameter": 2,
"variable-name": 0,
whitespace: 0,
},
},
],
};

35
samples/react-news-extension/.gitignore vendored Normal file
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
*.scss.d.ts

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": false,
"nodeVersion": "16.18.1",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.9.1"
},
"version": "1.17.4",
"libraryName": "o-3-c-spfx-preferences",
"libraryId": "30d84e8b-961a-4ef2-87a6-819fa1222ac3",
"environment": "spo",
"packageManager": "npm",
"solutionName": "o3c-spfx-preferences",
"solutionShortDescription": "o3c-spfx-preferences description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,109 @@
# Targeted News using Microsoft Graph Open Extension
## Summary
This samples contains two SPFx web parts:
**User preferences web part:**
This web part allows users to save their preferences in the Microsoft Graph Open Extension. This means that users can access their preferences from any device or application that uses the Microsoft Graph.
**Curated news web part:**
This web part allows users to view news topics they care about based on the selected preferences. This is a great way to help users stay informed about the topics that are most important to them.
![Targeted news web part](./assets/curated-news.png)
![User preferences web part](./assets/user-preferences-model.png)
![Targeted news using Microsoft Graph Open Extension](./assets/demo.gif)
## Compatibility
| :warning: Important |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 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. |
![SPFx 1.17.4](https://img.shields.io/badge/SPFx-1.17.4-green.svg)
![Node.js v16.18.1](https://img.shields.io/badge/Node.js-v16.18.1-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")
![Teams Incompatible](https://img.shields.io/badge/Teams-Incompatible-lightgrey.svg)
![Local Workbench Incompatible](https://img.shields.io/badge/Local%20Workbench-Incompatible-red.svg "This solution requires access to a user's user and group ids")
![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://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-developer-tenant)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/m365devprogram)
## Prerequisites
Access to a SharePoint online site with various tenant users granted access to various site resources directly, via AAD groups and via SharePoint groups.
> User Preferences web part configurations
1. Provide name for Microsoft Graph Open Extension
2. Provide Term Set ID for terms you would like to use for user preferences
![User preferences web part](./assets/user-preferences-config.jpg)
> Targeted news web part configurations
1. Provide name for Microsoft Graph Open Extension.
2. Provide Search managed property which you want to use to filter results. For example department or topic etc
![User preferences web part](./assets/targted-news-config.jpg)
## Contributors
- [Ejaz Hussain](https://github.com/ejazhussain)
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.0.0 | October 04, 2023 | Initial release |
## Minimal Path to Awesome
1. Clone this repository
2. From your command line, change your current directory to the directory containing this sample (`react-news-extension`, located under `samples`)
3. In the command line run:
```cmd
`npm install`
`gulp bundle`
`gulp package-solution`
```
4. Deploy the package to your app catalog
5. Approve the following API permission request from the SharePoint admin
```JSON
{
"resource": "Microsoft Graph",
"scope": "User.ReadWrite"
}
```
7. In the command-line run:
```cmd
gulp serve --nobrowser
```
8. Open the hosted workbench on a SharePoint site - i.e. https://_tenant_.sharepoint.com/site/_sitename_/_layouts/workbench.aspx
9. Configure user preferences and targeted news web parts as per above configurations
## Features
- User preferences web part allows users to save their preferences in the Microsoft Graph Open Extension. This means that users can access their preferences from any device or application that uses the Microsoft Graph.
- This web part allows users to view news topics they care about based on the selected preferences. This is a great way to help users stay informed about the topics that are most important to them.

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

View File

@ -0,0 +1,28 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"preferences-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/preferences/PreferencesWebPart.js",
"manifest": "./src/webparts/preferences/PreferencesWebPart.manifest.json"
}
]
},
"curated-news-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/curatedNews/CuratedNewsWebPart.js",
"manifest": "./src/webparts/curatedNews/CuratedNewsWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"PreferencesWebPartStrings": "lib/webparts/preferences/loc/{locale}.js",
"CuratedNewsWebPartStrings": "lib/webparts/curatedNews/loc/{locale}.js",
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "o-3-c-spfx-preferences",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,46 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "O3C Preferences",
"id": "30d84e8b-961a-4ef2-87a6-819fa1222ac3",
"version": "1.1.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.17.4"
},
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "User.ReadWrite"
}
],
"metadata": {
"shortDescription": {
"default": "O3C Preferences description"
},
"longDescription": {
"default": "O3C Preferences description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "O3C Preferences Feature",
"description": "The feature that activates elements of the O3C Preferences solution.",
"id": "17816985-2fdf-443e-b9ed-8e9569dbb78c",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/o3c-preferences.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,6 @@
{
"$schema": "https://raw.githubusercontent.com/s-KaiNet/spfx-fast-serve/master/schema/config.latest.schema.json",
"cli": {
"isLibraryComponent": false
}
}

View File

@ -0,0 +1,24 @@
/*
* User webpack settings file. You can add your own settings here.
* Changes from this file will be merged into the base webpack configuration file.
* This file will not be overwritten by the subsequent spfx-fast-serve calls.
*/
// you can add your project related webpack configuration here, it will be merged using webpack-merge module
// i.e. plugins: [new webpack.Plugin()]
const webpackConfig = {
}
// for even more fine-grained control, you can apply custom webpack settings using below function
const transformConfig = function (initialWebpackConfig) {
// transform the initial webpack config here, i.e.
// initialWebpackConfig.plugins.push(new webpack.Plugin()); etc.
return initialWebpackConfig;
}
module.exports = {
webpackConfig,
transformConfig
}

View File

@ -0,0 +1,22 @@
'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;
};
/* fast-serve */
const { addFastServe } = require("spfx-fast-serve-helpers");
addFastServe(build);
/* end of fast-serve */
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,56 @@
{
"name": "o-3-c-spfx-preferences",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=16.13.0 <17.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test",
"serve": "gulp bundle --custom-serve --max_old_space_size=4096 && fast-serve"
},
"dependencies": {
"@fluentui/react": "^7.199.1",
"@mantine/core": "^6.0.21",
"@mantine/hooks": "^6.0.21",
"@microsoft/sp-component-base": "1.17.4",
"@microsoft/sp-core-library": "1.17.4",
"@microsoft/sp-lodash-subset": "1.17.4",
"@microsoft/sp-office-ui-fabric-core": "1.17.4",
"@microsoft/sp-property-pane": "1.17.4",
"@microsoft/sp-webpart-base": "1.17.4",
"@pnp/core": "^3.18.0",
"@pnp/logging": "^3.18.0",
"@pnp/queryable": "^3.18.0",
"@pnp/sp": "^3.18.0",
"@pnp/spfx-controls-react": "3.15.0",
"@tabler/icons-react": "^2.35.0",
"antd": "^4.24.13",
"office-ui-fabric-react": "^7.199.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"recoil": "^0.7.7",
"styled-components": "^6.0.8",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.17.4",
"@microsoft/eslint-plugin-spfx": "1.17.4",
"@microsoft/rush-stack-compiler-4.5": "0.5.0",
"@microsoft/sp-build-web": "1.17.4",
"@microsoft/sp-module-interfaces": "1.17.4",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"spfx-fast-serve-helpers": "~1.17.0",
"typescript": "4.5.5"
}
}

View File

@ -0,0 +1,36 @@
import { Logger, LogLevel } from "@pnp/logging";
export class LogHelper {
public static verbose(className: string, methodName: string, message: string):void {
message = this._formatMessage(className, methodName, message);
Logger.write(message, LogLevel.Verbose);
}
public static info(className: string, methodName: string, message: string):void {
message = this._formatMessage(className, methodName, message);
Logger.write(message, LogLevel.Info);
}
public static warning(className: string, methodName: string, message: string):void {
message = this._formatMessage(className, methodName, message);
Logger.write(message, LogLevel.Warning);
}
public static error(className: string, methodName: string, message: string):void {
message = this._formatMessage(className, methodName, message);
Logger.write(message, LogLevel.Error);
}
public static exception(className: string, methodName: string, error: Error):void {
error.message = this._formatMessage(className, methodName, error.message);
Logger.error(error);
}
private static _formatMessage(className: string, methodName: string, message: string): string {
const d:Date = new Date();
const dateStr:string = d.getDate() + '-' + (d.getMonth() + 1) + '-' + d.getFullYear() + ' ' +
d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '.' + d.getMilliseconds();
return `${dateStr} ${className} > ${methodName} > ${message}`;
}
}

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,37 @@
import { LogHelper } from "../helpers/LogHelper";
class CachingService {
private static _storage: Storage;
public static Init(): void {
this._storage = window.localStorage;
LogHelper.info("CachingService", "Init", "Caching service initialised");
}
// Save data to local storage by key.
public static set(key: string, data: any): void {
this._storage.setItem(key, JSON.stringify(data));
}
// Retrieve data from the cache by key.
public static get<T>(key: string): T | null {
const data = this._storage.getItem(key);
if (data !== null) {
return JSON.parse(data) as T;
} else {
return null;
}
}
// Check if a key exists in the cache.
public static has(key: string): boolean {
return this._storage.getItem(key) !== null;
}
// Clear the cache.
public static clear(): void {
this._storage.clear();
}
}
export default CachingService;

View File

@ -0,0 +1,132 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { LogHelper } from "../helpers/LogHelper";
import { MSGraphClientV3 } from "@microsoft/sp-http";
class GraphService {
private static _context: WebPartContext;
public static async Init(context: WebPartContext): Promise<void> {
this._context = context;
LogHelper.info("GraphService", "Init", "Context initialized");
}
public static async GetExtension(extensionName: string): Promise<any> {
try {
const result = await this.GET(`/me/extensions/${extensionName}`);
return result;
} catch (error) {
console.log("Error in GetExtension:", error);
return null;
}
}
public static async GetPreferences(extensionName: string): Promise<any> {
try {
const result = await this.GET(`/me/extensions/${extensionName}`);
return result;
} catch (error) {
LogHelper.error("GraphService", "GetPreferences", `${error}`);
return null;
}
}
/**
* Saves preferences
* @param userSettings
* @returns preferences
*/
public static async SavePreferences(userSettings: any): Promise<any> {
try {
const result = await this.POST(
`/me/extensions`,
JSON.stringify(userSettings)
);
return result;
} catch (error) {
LogHelper.error("GraphService", "SavePreferences", `${error}`);
return null;
}
}
/**
* Updates preferences
* @param userSettings
* @returns preferences
*/
public static async UpdatePreferences(
userSettings: any,
extensionName: string
): Promise<any> {
try {
const result = await this.PATCH(
`/me/extensions/${extensionName}`,
JSON.stringify(userSettings)
);
return result;
} catch (error) {
LogHelper.error("GraphService", "UpdatePreferences", `${error}`);
return null;
}
}
private static GET(query: string): Promise<any> {
return new Promise<any>((resolve, reject) => {
this._context.msGraphClientFactory
.getClient("3")
.then((client: MSGraphClientV3): void => {
client.api(query).get((error, response) => {
if (error) {
reject(error);
return;
}
resolve(response);
});
});
});
}
private static POST(query: string, content: string) {
return new Promise<any>((resolve, reject) => {
this._context.msGraphClientFactory
.getClient("3")
.then((client: MSGraphClientV3): void => {
client.api(query).post(content, (error, response) => {
if (error) {
reject(error);
return;
}
resolve(response);
});
});
});
}
private static PATCH(query: string, content: string) {
return new Promise<any>((resolve, reject) => {
this._context.msGraphClientFactory
.getClient("3")
.then((client: MSGraphClientV3): void => {
client.api(query).patch(content, (error, response, rawResponse) => {
if (error) {
reject(error);
return;
}
resolve(rawResponse);
});
});
});
}
// private static DELETE(query: string) {
// return new Promise<any>((resolve, reject) => {
// this._context.msGraphClientFactory
// .getClient("3")
// .then((client: MSGraphClientV3): void => {
// client.api(query).delete((error, response, rawResponse) => {
// if (error) {
// reject(error);
// }
// resolve(rawResponse);
// });
// });
// });
// }
}
export default GraphService;

View File

@ -0,0 +1,82 @@
import { SPFI } from "@pnp/sp";
import { LogHelper } from "../helpers/LogHelper";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/taxonomy";
import { ITermInfo } from "@pnp/sp/taxonomy";
import "@pnp/sp/items/get-all";
import "@pnp/sp/search";
import { ISearchQuery, SearchResults } from "@pnp/sp/search";
class SPService {
private static _sp: SPFI;
public static Init(sp: SPFI): void {
this._sp = sp;
LogHelper.info("SPService", "constructor", "PnP SP context initialised");
}
public static getListItemsAsync = async (listName: string): Promise<any> => {
try {
const items: any = await this._sp.web.lists
.getByTitle(listName)
.items.select("*", "ID", "Title")
.getAll();
return items;
} catch (err) {
LogHelper.error("SPService", "getListItemsAsync", err);
return null;
}
};
public static getAllTermsByTermSet = async (
termSetGuid: string
): Promise<any> => {
try {
// list all the terms available in this term set by term set id
const terms: ITermInfo[] = await this._sp.termStore.sets
.getById(termSetGuid)
.terms();
return terms;
} catch (err) {
LogHelper.error("SPService", "getAllTermsByTermSet", err);
return null;
}
};
public static getSearchResults = async (
queryTemplate?: string
): Promise<any> => {
try {
// define a search query object matching the ISearchQuery interface
const results2: SearchResults = await this._sp.search(<ISearchQuery>{
QueryTemplate: queryTemplate,
Querytext: "",
RowLimit: 10,
EnableInterleaving: true,
SelectProperties: [
"O3CTax1",
"Description",
"DocId",
"Author",
"AuthorOWSUSER",
"Path",
"NormUniqueID",
"PictureThumbnailURL",
"PromotedState",
"O3CSortableTitle",
"Title",
],
});
console.log(results2.ElapsedTime);
console.log(results2.RowCount);
console.log(results2.PrimarySearchResults);
return results2.PrimarySearchResults;
} catch (err) {
LogHelper.error("SPService", "getSearchResults", err);
return null;
}
};
}
export default SPService;

View File

@ -0,0 +1,15 @@
import { atom, selector } from "recoil";
import { ITerm } from "../webparts/preferences/types/Component.Types";
export const tagsListAtom = atom({
key: "tagList",
default: [] as ITerm[],
});
export const tagSelectedSelector = selector({
key: "tagSelected",
get: ({ get }) => {
const tagList = get(tagsListAtom);
return tagList;
},
});

View File

@ -0,0 +1,41 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "beaf7844-e605-4f9a-85b5-1834aafe1349",
"alias": "CuratedNewsWebPart",
"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": "[O365Clinic] Targted News"
},
"description": {
"default": "[O365Clinic] Targted News description"
},
"officeFabricIconFontName": "News",
"properties": {
"extensionName": "",
"title": "Targeted Global News",
"managedPropertyName": "owstaxIdO3CTaxDepartments",
"newsPageLink": "See all"
}
}
]
}

View File

@ -0,0 +1,171 @@
import * as React from "react";
import * as ReactDom from "react-dom";
import { Version } from "@microsoft/sp-core-library";
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneToggle,
} from "@microsoft/sp-property-pane";
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IReadonlyTheme } from "@microsoft/sp-component-base";
import * as strings from "CuratedNewsWebPartStrings";
import { ICuratedNewsProps } from "./components/ICuratedNewsProps";
import "antd/dist/antd.css";
import SPService from "../../services/SPService";
import { SPFx, spfi } from "@pnp/sp";
import { ConsoleListener, Logger } from "@pnp/logging";
import { CuratedNews } from "./components/CuratedNews";
import GraphService from "../../services/GraphService";
import CachingService from "../../services/CachingService";
export interface ICuratedNewsWebPartProps {
title: string;
extensionName: string;
managedPropertyName: string;
newsPageLink: string;
enableCaching: boolean;
}
const LOG_SOURCE: string = "CuratedNewsWebPart";
export default class CuratedNewsWebPart extends BaseClientSideWebPart<ICuratedNewsWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = "";
public render(): void {
const element: React.ReactElement<ICuratedNewsProps> = React.createElement(
CuratedNews,
{
title: this.properties.title,
extensionName: this.properties.extensionName,
managedPropertyName: this.properties.managedPropertyName,
newsPageLink: this.properties.newsPageLink,
enableCaching: this.properties.enableCaching,
context: this.context,
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
loginName: this.context.pageContext.user.loginName,
}
);
ReactDom.render(element, this.domElement);
}
protected async onInit(): Promise<void> {
// this._getEnvironmentMessage().then((message) => {
// this._environmentMessage = message;
// });
this._environmentMessage = await this._getEnvironmentMessage();
// subscribe a listener
Logger.subscribe(
ConsoleListener(LOG_SOURCE, { warning: "#e36c0b", error: "#a80000" })
);
//Init SharePoint Service
const sp = spfi().using(SPFx(this.context));
SPService.Init(sp);
GraphService.Init(this.context);
CachingService.Init();
}
private _getEnvironmentMessage(): Promise<string> {
if (!!this.context.sdks.microsoftTeams) {
// running in Teams, office.com or Outlook
return this.context.sdks.microsoftTeams.teamsJs.app
.getContext()
.then((context) => {
let environmentMessage: string = "";
switch (context.app.host.name) {
case "Office": // running in Office
environmentMessage = this.context.isServedFromLocalhost
? strings.AppLocalEnvironmentOffice
: strings.AppOfficeEnvironment;
break;
case "Outlook": // running in Outlook
environmentMessage = this.context.isServedFromLocalhost
? strings.AppLocalEnvironmentOutlook
: strings.AppOutlookEnvironment;
break;
case "Teams": // running in Teams
environmentMessage = this.context.isServedFromLocalhost
? strings.AppLocalEnvironmentTeams
: strings.AppTeamsTabEnvironment;
break;
default:
throw new Error("Unknown host");
}
return environmentMessage;
});
}
return Promise.resolve(
this.context.isServedFromLocalhost
? strings.AppLocalEnvironmentSharePoint
: strings.AppSharePointEnvironment
);
}
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("title", {
label: "Title",
}),
PropertyPaneTextField("extensionName", {
label: strings.ExtensionNameFieldLabel,
}),
PropertyPaneTextField("managedPropertyName", {
label: "Managed Property Name",
}),
PropertyPaneTextField("newsPageLink", {
label: "All News Page Link",
}),
PropertyPaneToggle("enableCaching", {
label: "Enable Caching",
}),
],
},
],
},
],
};
}
}

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,51 @@
@import "~@fluentui/react/dist/sass/References.scss";
.curatedNews {
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
.news-container {
padding: 30px;
background: #ececec;
.description {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
}
.welcome {
text-align: center;
}
.welcomeImage {
width: 100%;
max-width: 420px;
}
.links {
a {
text-decoration: none;
color: "[theme:link, default:#03787c]";
color: var(
--link
); // note: CSS Custom Properties support is limited to modern browsers only
&:hover {
text-decoration: underline;
color: "[theme:linkHovered, default: #014446]";
color: var(
--linkHovered
); // note: CSS Custom Properties support is limited to modern browsers only
}
}
}

View File

@ -0,0 +1,163 @@
import * as React from "react";
import styles from "./CuratedNews.module.scss";
import { ICuratedNewsProps } from "./ICuratedNewsProps";
import { Card, Col, Row, Space, Spin, Tag } from "antd";
import Meta from "antd/lib/card/Meta";
import SPService from "../../../services/SPService";
import { ISearchResult } from "@pnp/sp/search";
import GraphService from "../../../services/GraphService";
import CachingService from "../../../services/CachingService";
import { ITerm } from "../../preferences/types/Component.Types";
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
export const CuratedNews: React.FC<ICuratedNewsProps> = (props) => {
const {
extensionName,
loginName,
title,
managedPropertyName,
context,
newsPageLink,
enableCaching,
} = props;
const [data, setData] = React.useState<ISearchResult[]>([]);
const [loading, setLoading] = React.useState<boolean>(false);
const preferenceCacheKey = `CuratedNews-UserPreferences-${loginName}`;
// const personDetails = {
// displayName: "Ejaz Hussain",
// };
const onConfigure = () => {
// Context of the web part
context.propertyPane.open();
};
const getUserPreferences = async () => {
const cachedData = CachingService.get(preferenceCacheKey);
if (cachedData !== null) {
return cachedData;
}
const result = await GraphService.GetPreferences(extensionName);
if (result && result.Tags && result.Tags.length > 0 && enableCaching) {
CachingService.set(preferenceCacheKey, result.Tags);
}
return result.Tags || [];
};
const fetchData = React.useCallback(async () => {
setLoading(true);
const tags = await getUserPreferences();
console.log(tags);
const queryTemplate = composeQueryTemplate(tags);
const result = await SPService.getSearchResults(queryTemplate);
return result;
}, []);
React.useEffect(() => {
fetchData()
.then((data) => {
setData(data);
setLoading(false);
})
.catch((error) => console.log(error));
}, [fetchData]);
if (!extensionName || !managedPropertyName || !newsPageLink) {
return (
<Placeholder
iconName="Edit"
iconText="Configure your web part"
description="Please provide the Microsoft Graph open extension name and managed property name."
buttonLabel="Configure"
onConfigure={onConfigure}
/>
);
}
return (
<section>
<div className={styles["news-container"]}>
<Spin spinning={loading} tip="Loading...">
<Card
title={title}
headStyle={{ fontSize: "2rem" }}
extra={<a href={newsPageLink}>See all</a>}
>
<Row gutter={16}>
{data.length > 0 &&
data.map((newsItem: any) => {
const tags: string[] = newsItem.O3CTax1
? newsItem.O3CTax1.split(";")
: [];
return (
<Col key={newsItem.DocId} span={6}>
<Card
hoverable
bordered={false}
cover={
<img
alt={newsItem.Title}
src={newsItem.PictureThumbnailURL}
/>
}
actions={[
<>
<Space size={[0, 8]} wrap key={newsItem.DocId}>
{tags.length > 0 &&
tags.map((tag, index) => {
return (
<Tag key={index} color="#108ee9">
{tag}
</Tag>
);
})}
</Space>
</>,
]}
>
<Meta
title={
<>
<span>{newsItem.Title}</span>
</>
}
description={
<>
<span className={styles.description}>
{newsItem.Description}
</span>
<div style={{ marginTop: 10 }}> </div>
</>
}
/>
</Card>
</Col>
);
})}
</Row>
</Card>
</Spin>
</div>
</section>
);
function composeQueryTemplate(tags: ITerm[]) {
let filterQuery = "";
if (!tags || tags.length === 0) {
filterQuery = "";
}
if (Array.isArray(tags) && tags.length > 0) {
const taxValues = `(${tags.map((tag) => tag.id).join(" OR ")})`;
filterQuery = `({|${managedPropertyName}:${taxValues}})`;
}
const queryTemplate = `{searchTerms} (ContentTypeId:0x0101009D1CB255DA76424F860D91F20E6C4118*) PromotedState=2 ${
filterQuery ? filterQuery : ""
} `;
return queryTemplate;
}
};

View File

@ -0,0 +1,14 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
export interface ICuratedNewsProps {
title: string;
extensionName: string;
managedPropertyName: string;
newsPageLink: string;
enableCaching: boolean;
context: WebPartContext;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
loginName: string;
}

View File

@ -0,0 +1,20 @@
define([], function () {
return {
PropertyPaneDescription: "Description",
ExtensionNameFieldLabel: "Graph Open Extension",
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",
};
});

View File

@ -0,0 +1,19 @@
declare interface ICuratedNewsWebPartStrings {
PropertyPaneDescription: string;
ExtensionNameFieldLabel: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppLocalEnvironmentOffice: string;
AppLocalEnvironmentOutlook: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
AppOfficeEnvironment: string;
AppOutlookEnvironment: string;
}
declare module "CuratedNewsWebPartStrings" {
const strings: ICuratedNewsWebPartStrings;
export = strings;
}

View File

@ -0,0 +1,35 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "7c937755-1d06-480c-a881-682efc96c038",
"alias": "PreferencesWebPart",
"componentType": "WebPart",
"version": "*",
"manifestVersion": 2,
"requiresCustomScript": false,
"supportedHosts": [
"SharePointWebPart",
"TeamsPersonalApp",
"TeamsTab",
"SharePointFullPage"
],
"supportsThemeVariants": true,
"preconfiguredEntries": [
{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70",
"group": {
"default": "Advanced"
},
"title": {
"default": "[O365Clinic] Preferences"
},
"description": {
"default": "Preferences description"
},
"officeFabricIconFontName": "FavoriteList",
"properties": {
"extensionName": "",
"title": "User Preferences"
}
}
]
}

View File

@ -0,0 +1,165 @@
import * as React from "react";
import * as ReactDom from "react-dom";
import { Version } from "@microsoft/sp-core-library";
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneToggle,
} from "@microsoft/sp-property-pane";
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IReadonlyTheme } from "@microsoft/sp-component-base";
import * as strings from "PreferencesWebPartStrings";
import { ConsoleListener, Logger } from "@pnp/logging";
import { SPFx, spfi } from "@pnp/sp";
import SPService from "../../services/SPService";
import GraphService from "../../services/GraphService";
import { Container, IContainerProps } from "./components/Container";
import CachingService from "../../services/CachingService";
export interface IPreferencesWebPartProps {
title: string;
extensionName: string;
termsetGuid: string;
enableCaching: boolean;
}
const LOG_SOURCE: string = "PreferencesWebPart";
export default class PreferencesWebPart extends BaseClientSideWebPart<IPreferencesWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = "";
public render(): void {
const element: React.ReactElement<IContainerProps> = React.createElement(
Container,
{
title: this.properties.title,
extensionName: this.properties.extensionName,
termsetGuid: this.properties.termsetGuid,
enableCaching: this.properties.enableCaching,
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
loginName: this.context.pageContext.user.loginName,
context: this.context,
}
);
ReactDom.render(element, this.domElement);
}
protected async onInit(): Promise<void> {
// this._getEnvironmentMessage().then((message) => {
// this._environmentMessage = message;
// });
this._environmentMessage = await this._getEnvironmentMessage();
// subscribe a listener
Logger.subscribe(
ConsoleListener(LOG_SOURCE, { warning: "#e36c0b", error: "#a80000" })
);
//Init SharePoint Service
const sp = spfi().using(SPFx(this.context));
SPService.Init(sp);
GraphService.Init(this.context);
CachingService.Init();
return super.onInit();
}
private _getEnvironmentMessage(): Promise<string> {
if (!!this.context.sdks.microsoftTeams) {
// running in Teams, office.com or Outlook
return this.context.sdks.microsoftTeams.teamsJs.app
.getContext()
.then((context) => {
let environmentMessage: string = "";
switch (context.app.host.name) {
case "Office": // running in Office
environmentMessage = this.context.isServedFromLocalhost
? strings.AppLocalEnvironmentOffice
: strings.AppOfficeEnvironment;
break;
case "Outlook": // running in Outlook
environmentMessage = this.context.isServedFromLocalhost
? strings.AppLocalEnvironmentOutlook
: strings.AppOutlookEnvironment;
break;
case "Teams": // running in Teams
environmentMessage = this.context.isServedFromLocalhost
? strings.AppLocalEnvironmentTeams
: strings.AppTeamsTabEnvironment;
break;
default:
throw new Error("Unknown host");
}
return environmentMessage;
});
}
return Promise.resolve(
this.context.isServedFromLocalhost
? strings.AppLocalEnvironmentSharePoint
: strings.AppSharePointEnvironment
);
}
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("title", {
label: "Title",
}),
PropertyPaneTextField("extensionName", {
label: strings.ExtensionNameFieldLabel,
}),
PropertyPaneTextField("termsetGuid", {
label: strings.TermSetIdFieldLabel,
}),
PropertyPaneToggle("enableCaching", {
label: "Enable Caching",
}),
],
},
],
},
],
};
}
}

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,32 @@
import * as React from "react";
import { Preferences } from "./Preferences";
import { RecoilRoot } from "recoil";
import { Divider, MantineProvider } from "@mantine/core";
import { WebPartContext } from "@microsoft/sp-webpart-base";
export interface IContainerProps {
title: string;
extensionName: string;
termsetGuid: string;
enableCaching: boolean;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
loginName: string;
context: WebPartContext;
}
export const Container: React.FC<IContainerProps> = (props) => {
return (
<MantineProvider
theme={{ fontFamily: "Segoe UI" }}
withGlobalStyles
withNormalizeCSS
>
<RecoilRoot>
<Divider my="xs" label="Preference" labelPosition="center" />
<Preferences {...props} />
</RecoilRoot>
</MantineProvider>
);
};

View File

@ -0,0 +1,13 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
export interface IPreferencesProps {
title: string;
extensionName: string;
termsetGuid: string;
enableCaching: boolean;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
loginName: string;
context: WebPartContext;
}

View File

@ -0,0 +1,216 @@
import * as React from "react";
import SPService from "../../../services/SPService";
import {
Chip,
Group,
Box,
Modal,
Button,
Flex,
Grid,
useMantineTheme,
ModalBaseStylesNames,
Styles,
Alert,
} from "@mantine/core";
import GraphService from "../../../services/GraphService";
import { ITerm } from "../types/Component.Types";
import { IconCheck } from "@tabler/icons-react";
import { useRecoilState } from "recoil";
import { tagsListAtom } from "../../../stores/appstore";
import CachingService from "../../../services/CachingService";
export interface IPickerProps {
extensionName: string;
termsetGuid: string;
opened: boolean;
close: () => void;
}
export const Picker: React.FC<IPickerProps> = (props) => {
const { extensionName, termsetGuid, opened, close } = props;
const [termsInfo, setTermsInfo] = React.useState<ITerm[]>([]);
const theme = useMantineTheme();
const [tags, setTags] = React.useState<string[]>([]);
const [tagList, setTagList] = useRecoilState(tagsListAtom);
const [loading, setLoading] = React.useState<boolean>(false);
const [submitted, setSubmitted] = React.useState<boolean>(false);
const dataCacheKey = `Preferences-taxonomy-${termsetGuid}`;
const getCachedTaxonomy = async () => {
// Check if the taxonomy data is available in the cache.
const cachedTaxonomy = await CachingService.get(dataCacheKey);
// If the taxonomy data is available in the cache, return it.
if (cachedTaxonomy) {
return cachedTaxonomy;
}
// Otherwise, make an API call to fetch the taxonomy data and cache it.
const taxonomy = await SPService.getAllTermsByTermSet(termsetGuid);
const termsResult = taxonomy.map((t: any) => {
const termId = t.id;
const termName = t.labels[0].name;
return { id: termId, title: termName } as ITerm;
});
// Cache the taxonomy data.
CachingService.set(dataCacheKey, termsResult);
// Return the taxonomy data.
return termsResult;
};
React.useEffect(() => {
async function fetchTaxonomy() {
const termsResult = await getCachedTaxonomy();
const ids = tagList.map((obj: ITerm) => obj.id);
setTags(ids);
setTermsInfo(termsResult);
}
fetchTaxonomy();
}, []);
// React.useEffect(() => {
// async function fetchTaxonomy() {
// const terms = await SPService.getAllTermsByTermSet(termsetGuid);
// const termsResult = terms.map((t: any) => {
// const termId = t.id;
// const termName = t.labels[0].name;
// return { id: termId, title: termName } as ITerm;
// });
// const ids = tagList.map((obj: ITerm) => obj.id);
// setTags(ids);
// setTermsInfo(termsResult);
// }
// fetchTaxonomy();
// }, []);
const onSavePreferences = async () => {
setLoading(true);
setSubmitted(false);
const extension = await GraphService.GetExtension(extensionName);
const selectedTags = [];
for (const guid of tags) {
const term = termsInfo.find((t: ITerm) => t.id === guid);
if (term) {
selectedTags.push(term);
}
}
const userSettings = {
"@odata.type": "microsoft.graph.openTypeExtension",
extensionName: extensionName,
Tags: selectedTags,
};
if (extension === null) {
//Create Extesion
const response = await GraphService.SavePreferences(userSettings);
if (response !== null && response.ok) {
console.log(response);
}
} else {
//update Extesion
const response = await GraphService.UpdatePreferences(
userSettings,
extensionName
);
if (response !== null) {
console.log(response);
setTagList(selectedTags);
setSubmitted(true);
}
}
setLoading(false);
};
const onTagChange = (selectedTags: string[]) => {
const ids = [...selectedTags];
setTags(ids);
//setTags((prevState) => [...prevState, ...selectedTags]);
};
console.log(tagList);
const modelHeaderStyles: Styles<ModalBaseStylesNames> = {
header: {
backgroundColor: "#d1d2d3ba",
h2: {
fontSize: "1.1rem",
},
},
};
return (
<div>
<Modal
styles={modelHeaderStyles}
size="lg"
opened={opened}
onClose={close}
title="Update preferences"
centered
overlayProps={{
color:
theme.colorScheme === "dark"
? theme.colors.dark[9]
: theme.colors.gray[2],
opacity: 0.55,
blur: 3,
}}
>
<Grid>
<Grid.Col span={12}>
{" "}
<Chip.Group multiple value={tags} onChange={onTagChange}>
<Group position="center" mt="md">
{termsInfo.length > 0 &&
termsInfo.map((t: ITerm, index: number) => {
const isSelected: boolean = tags.some((o) => o === t.id);
return (
<Chip
checked={isSelected}
variant="filled"
key={index}
value={t.id}
>
{t.title}
</Chip>
);
})}
</Group>
</Chip.Group>
</Grid.Col>
{!submitted && (
<Grid.Col span={12}>
{" "}
<Flex gap="md" justify="flex-end">
<Box w={200}>
<Button
loading={loading}
loaderPosition="left"
fullWidth
variant="gradient"
onClick={onSavePreferences}
>
Save
</Button>
</Box>
</Flex>
</Grid.Col>
)}
</Grid>
{submitted && (
<Alert
icon={<IconCheck size="1rem" />}
title="Success!"
color="green"
>
Your preferences have been successfully updated. You're good to go!
</Alert>
)}
</Modal>
</div>
);
};

View File

@ -0,0 +1,52 @@
@import "~@fluentui/react/dist/sass/References.scss";
.preferences {
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
.card {
transition: transform 150ms ease, box-shadow 150ms ease;
&:hover {
transform: scale(1.01);
box-shadow: var(--mantine-shadow-md);
}
}
.title {
font-family: "Greycliff CF", var(--mantine-font-family);
font-weight: bold;
}
.welcome {
text-align: center;
}
.welcomeImage {
width: 100%;
max-width: 420px;
}
.links {
a {
text-decoration: none;
color: "[theme:link, default:#03787c]";
color: var(
--link
); // note: CSS Custom Properties support is limited to modern browsers only
&:hover {
text-decoration: underline;
color: "[theme:linkHovered, default: #014446]";
color: var(
--linkHovered
); // note: CSS Custom Properties support is limited to modern browsers only
}
}
}

View File

@ -0,0 +1,156 @@
import * as React from "react";
//import styles from "./Preferences.module.scss";
import { IPreferencesProps } from "./IPreferencesProps";
//import SPService from "../../../services/SPService";
import {
Container,
Group,
createStyles,
ActionIcon,
Card,
Text,
} from "@mantine/core";
import { IconSettings } from "@tabler/icons-react";
import GraphService from "../../../services/GraphService";
import { Picker } from "./Picker";
import { ITerm } from "../types/Component.Types";
import { useRecoilState } from "recoil";
import { tagsListAtom } from "../../../stores/appstore";
import CachingService from "../../../services/CachingService";
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
const useStyles = createStyles((theme) => ({
tagWrapper: {
display: "flex",
flexDirection: "unset",
margin: "3px 1em 3px 0",
alignItems: "center",
flexWrap: "wrap",
justifyContent: "center",
gap: "1rem",
},
tag: {
color: "white",
backgroundColor: "rgb(34, 139, 230)",
padding: "0 0.625rem",
border: "0.0625rem solid transparent",
borderRadius: "2rem",
height: "1.75rem",
fontSize: "0.875rem",
lineHeight: "calc(1.625rem)",
whiteSpace: "nowrap",
transition: "background-color 100ms ease 0s",
},
}));
export const Preferences: React.FC<IPreferencesProps> = (props) => {
const {
extensionName,
termsetGuid,
loginName,
title,
context,
enableCaching,
} = props;
const { classes } = useStyles();
const [isPanelOpen, setIsPanelOpen] = React.useState<boolean>(false);
const [tagList, setTagList] = useRecoilState(tagsListAtom);
const dataCacheKey = `Preferences-${extensionName}-${loginName}`;
const onConfigure = () => {
// Context of the web part
context.propertyPane.open();
};
const getUserPreferences = async () => {
const cachedData = CachingService.get(dataCacheKey);
if (cachedData !== null) {
return cachedData;
}
const result = await GraphService.GetPreferences(extensionName);
if (result && result.Tags && Array.isArray(result.Tags) && enableCaching) {
CachingService.set(dataCacheKey, result.Tags);
}
return result.Tags || [];
};
const getPreferences = React.useCallback(async () => {
const result = await getUserPreferences();
return result;
}, []);
React.useEffect(() => {
getPreferences()
.then((data) => setTagList(data))
.catch((error) => console.log(error));
}, [getPreferences]);
const onViewPanelClick = (): void => {
setIsPanelOpen(true);
};
function onViewPanelDismiss(): void {
setIsPanelOpen(false);
}
if (!extensionName || !termsetGuid) {
return (
<Placeholder
iconName="Edit"
iconText="Configure your web part"
description="Please provide the Microsoft Graph open extension name and term set Id."
buttonLabel="Configure"
onConfigure={onConfigure}
/>
);
}
return (
<Container>
<Card withBorder shadow="sm" radius="md">
<Card.Section withBorder inheritPadding py="xs">
<Group position="apart">
<Text size={30} weight={500}>
{title}
</Text>
<ActionIcon
onClick={onViewPanelClick}
variant="outline"
color="indigo"
>
<IconSettings size="1rem" />
</ActionIcon>
</Group>
</Card.Section>
<Group position="apart" mt="md" mb="xs">
{isPanelOpen && (
<Picker
extensionName={extensionName}
termsetGuid={termsetGuid}
opened={isPanelOpen}
close={onViewPanelDismiss}
/>
)}
<div className={classes.tagWrapper}>
{tagList.length > 0 &&
tagList.map((t: ITerm, index) => {
return (
<div className={classes.tag} key={index}>
{t.title}
</div>
);
})}
</div>
</Group>
{/* <Button variant="light" color="blue" fullWidth mt="md" radius="md">
Book classic tour now
</Button> */}
</Card>
</Container>
);
};

View File

@ -0,0 +1,20 @@
define([], function () {
return {
PropertyPaneDescription: "Description",
BasicGroupName: "Group Name",
ExtensionNameFieldLabel: "Enter open extension name",
TermSetIdFieldLabel: "Enter term set guid",
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",
};
});

View File

@ -0,0 +1,19 @@
declare interface IPreferencesWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
ExtensionNameFieldLabel: string;
TermSetIdFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppLocalEnvironmentOffice: string;
AppLocalEnvironmentOutlook: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
AppOfficeEnvironment: string;
AppOutlookEnvironment: string;
}
declare module "PreferencesWebPartStrings" {
const strings: IPreferencesWebPartStrings;
export = strings;
}

View File

@ -0,0 +1,4 @@
export interface ITerm {
id: string;
title: string;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 B

View File

@ -0,0 +1,29 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.5/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",
"ES2017",
"es2019"
]
},
"include": ["src/**/*.ts", "src/**/*.tsx"]
}