Merge pull request #4829 from russgove/master

Master
This commit is contained in:
Hugo Bernier 2024-03-16 13:57:49 -04:00 committed by GitHub
commit da3e2efb16
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
62 changed files with 60336 additions and 882 deletions

View File

@ -1,39 +1,38 @@
// For more information on how to run this SPFx project in a VS Code Remote Container, please visit https://aka.ms/spfx-devcontainer
{
"name": "SPFx 1.0.0",
"image": "docker.io/m365pnp/spfx:ga",
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"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"
"name": "SPFx 1.17.1",
"image": "docker.io/m365pnp/spfx:1.17.1",
"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

@ -7,9 +7,11 @@ 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
cp ~/.gcb-serve-data/gcb-serve.cer ./spfx-dev-cert.cer
cp ~/.gcb-serve-data/gcb-serve.cer ./spfx-dev-cert.pem
# 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

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': 0,
// 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

@ -1,3 +1,6 @@
.heft
release
# Logs
logs
*.log

View File

@ -0,0 +1 @@
v16.20.0

View File

@ -1,7 +1,17 @@
{
"@microsoft/generator-sharepoint": {
"environment": "spo",
"componentType": "webpart",
"packageManager": "npm",
"isCreatingSolution": true,
"isDomainIsolated": false,
"sdkVersions": {
"@microsoft/teams-js": "2.9.1",
"@microsoft/microsoft-graph-client": "3.0.2"
},
"nodeVersion": "16.20.0",
"libraryName": "react-property-bag-editor",
"libraryId": "12dac38e-b255-44ce-9f06-050571b34d39",
"framework": "react"
"version": "1.17.1"
}
}

View File

@ -1,9 +1,9 @@
# Property Bag Navigation Webparts
# Property Bag Navigation Web parts
## Summary
A set of webparts that lets you set property bag settings on site collections and enable navigation using those properties.
[picture of the web part in action]
A set of web parts that lets you set property bag settings on site collections and enable navigation using those properties.
![PropertyBagEditorDisplay](./assets/PropertyBagEditorDisplay.PNG)
## Compatibility
@ -26,8 +26,6 @@ A set of webparts that lets you set property bag settings on site collections an
* [SharePoint Framework](https://blogs.office.com/2017/02/23/sharepoint-framework-reaches-general-availability-build-and-deploy-engaging-web-parts-today/)
* [Microsoft 365 tenant](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment)
## Prerequisites
> pnp-js-core
@ -41,49 +39,55 @@ A set of webparts that lets you set property bag settings on site collections an
Version|Date|Comments
-------|----|--------
1.0|march 19, 2017|Initial release
2.0|Feb 21, 2024|Upgraded to SPFX 1.17.1
## Minimal Path to Awesome
- Clone this repository
- in the command line run:
- `npm install`
- `gulp serve`
* Clone this repository
* This project uses the JSOM to interact with the property bag. Therefore in config/config.js you need to change the paths
on the externals `sp-init`,`microsoft-ajax`,`sp-runtime`, and SharePoint to point to your tenant.
* in the command line run:
* `npm install`
* `gulp serve`
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit https://aka.ms/spfx-devcontainer for further instructions.
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit <https://aka.ms/spfx-devcontainer> for further instructions.
> Include any additional steps as needed.
> Note that using the JSOM to updates the property bag of a site is not supported on 'NoScript' sites. You can enable scripts on all sites using the admin center or via PowerShell:
>
> ```powershell
> Set-PnPTenantSite -Identity {SiteUrl} -DenyAddAndCustomizePages:$false
> ```
## Features
This project consists of four webparts that can be used to manage the Property Bags for SharePoint sites and display navigational components from those Properties.
- PropertyBagEditor
This web part allows an administrator to edit selected items in a site&#39;s Property Bag. A sample display is shown below:
![PropertyBagEditorDisplay](./src/images/PropertyBagEditorDisplay.PNG)
This project consists of two web parts that can be used to manage the Property Bags for SharePoint sites and two web parts that can be used to display navigational components from those Properties.
* PropertyBagEditor
This web part allows a site owner/administrator to edit selected items in a site&#39;s Property Bag. It edits the properties of the current site. A sample display is shown below:
![PropertyBagEditorDisplay](./assets/PropertyBagEditorDisplay.PNG)
Selecting a Property and clicking the Edit button will bring up the Edit Panel:
![PropertyBagEditorEdur](./src/images/PropertyBagEditorEdit.PNG)
![PropertyBagEditorEdur](./assets/PropertyBagEditorEdit.PNG)
Here you can change the value of the property and specify if the property should be included in the search Index.
The Properties that can be edited are specified in the web part&#39;s Property Pane:
![PropertyBagEditorEdur](./src/images/PropertyBagEditorConfig.PNG)
![PropertyBagEditorEdur](./assets/PropertyBagEditorConfig.PNG)
The Properties set in the Property Pane of this web part are crawled properties, and should be mapped to managed properties so that can be used by the other webparts in this project.
The Properties set in the Property Pane of this web part are crawled properties, and should be mapped to managed properties so that can be used by the other web parts in this project.
The Site whose properties are to be edited can be passed in via a query parameter. While this web part can be added to any page, it would be most useful if added to a page in an infrastructure site collection in the tenant, and then linked to from all other sites via a link in the Site Settings page.
The following script shows how to add such a link to all sites &#39;Site Settings&#39; page using PNP Powershell. It will add a menu item named &#39;Edit Site Metadata &#39; to the Site Settings of each Team Site that links to the PropertBagEdcitor.aspx page on the tenants infrastructure site (this site is named 'cdn' in the example below).
The following script shows how to add such a link to all sites &#39;Site Settings&#39; page using PNP PowerShell. It will add a menu item named &#39;Edit Site Metadata &#39; to the Site Settings of each Team Site that links to the PropertyBagEditor.aspx page on the tenants infrastructure site (this site is named 'cdn' in the example below).
```
```powershell
$adminSiteUrl=&quot;https://tenant-admin.sharepoint.com&quot;
$customActionDescription=&quot;CUSTOM_\ ___Navigation__ \__Metadata&quot;
$pageUrl=&quot;https://tenant.sharepoint.com/sites/cdn/SitePages/PropertBagEdcitor.aspx?siteUrl={0}&quot;
$pageUrl=&quot;https://tenant.sharepoint.com/sites/cdn/SitePages/PropertyBagEditor.aspx?siteUrl={0}&quot;
$credentials=get-credential
@ -121,49 +125,47 @@ foreach($site in $sites){
}
```
- PropertyBagDisplay
* PropertyBagDisplay
The propertyBagDisplay web part can be used by an administrator to view and edit selected properties across sites in the tenant:
![PropertyBagDisplay](./src/images/PropertyBagDisplayDisplay.PNG)
![PropertyBagDisplay](./assets/PropertyBagDisplayDisplay.PNG)
In the Property Pane, an administrator must specify both the Crawled Property Name and the Managed Property name (separated by a pipe character) of the properties to be included in the web part:
![PropertyBagDisplayConfig](./src/images/PropertBagDisplayConfig.PNG)
![PropertyBagDisplayConfig](./assets/PropertBagDisplayConfig.PNG)
The administrator can also include a list of site templates to narrow down the list of sites to be included in the web part. When specifying site templates to include you can include just the Site Template Name (STS) and all sites within that template name will be included, or you can specify the Site Template Name and ID, separated by a &#39;#&quot; character (STS#1) to have only sites with that template name and ID included.
The web part displays the site template, Title and Url, plus the selected Managed Properties for all sites in the tenant with the selected site template. The Managed Properties are only displayed if they have been set as searchable, and a full crawl has been run. After selecting a Site, a user can click the edit button to edit the Crawled properties (i.e. the raw property bag values) for the selected site:
The web part displays the site template, Title and URL, plus the selected Managed Properties for all sites in the tenant with the selected site template. The Managed Properties are only displayed if they have been set as searchable, and a full crawl has been run. After selecting a Site, a user can click the edit button to edit the Crawled properties (i.e. the raw property bag values) for the selected site:
![PropertyBagDisplayEdit](./src/images/PropertyBagDisplayEdit.PNG)
![PropertyBagDisplayEdit](./assets/PropertyBagDisplayEdit.PNG)
On the edit panel one can specify a new value for each property as well as whether that property is to be included in the search index. Additionally one can specify that a full crawl of the site should be run once the properties are saved.
- PropertyBagFilteredSiteList
* PropertyBagFilteredSiteList
This web part displays a list of all sites that meet the criteria specified in the property pane by the administrator:
![PropertyBagFilteredSiteListDisplay](./src/images/PropertyBagFilteredSiteListDisplay.PNG)
![PropertyBagFilteredSiteListDisplay](./assets/PropertyBagFilteredSiteListDisplay.PNG)
Additionally, it lets the user narrow down the list of sites displayed by applying metadata filters that are set up by the administrator in the Property Pane( Business Unit and Continent in the example above):
![PropertyBagFilteredSiteListConfig](./src/images/PropertyBagFilteredSiteListConfigy.PNG)
![PropertyBagFilteredSiteListConfig](./assets/PropertyBagFilteredSiteListConfigy.PNG)
In the PropertyPane above, the 'Site Templates to Include' and 'Metadata Filters' are used to filter which site collections are retrieved from search. The 'User Filters' are used to allow the user to easily filter the results returned from search using the command bar on the top of the display.
- PropertyBagGlobalNav
* PropertyBagGlobalNav
This Web part builds a navigation menu based on the Managed Properties set up in the PropertyPane:
![propertyBagGlobalNavDisplay](./src/images/propertyBagGlobalNavDisplay.PNG)
![propertyBagGlobalNavDisplay](./assets/propertyBagGlobalNavDisplay.PNG)
In the PropertyPane, an administrator just needs to specify which Managed Properties are to be used to build the Navigation menu:
![PropertyBagGlobalNavConfig](./src/images/PropertyBagGlobalNavConfig.PNG)
![PropertyBagGlobalNavConfig](./assets/PropertyBagGlobalNavConfig.PNG)
If desired, the admin can also specify which site templates should be included in the menu, as wall as any additional filters. Additional Filters can be specified in the format 'ManagedPropertyName=value';
## 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-property-bag-editor" />

View File

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 8.1 KiB

View File

@ -2,14 +2,14 @@
{
"name": "pnp-sp-dev-spfx-web-parts-react-property-bag-editor",
"source": "pnp",
"title": "Property Bag Navigation Webparts",
"shortDescription": "A set of webparts that lets you set property bag settings on site collections and enable navigation using those properties.",
"title": "Property Bag Navigation Web parts",
"shortDescription": "A set of web parts that lets you set property bag settings on site collections and enable navigation using those properties.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-property-bag-editor",
"longDescription": [
"A set of webparts that lets you set property bag settings on site collections and enable navigation using those properties."
"A set of web parts that lets you set property bag settings on site collections and enable navigation using those properties."
],
"creationDateTime": "2017-03-19",
"updateDateTime": "2017-03-19",
"updateDateTime": "2024-02-21",
"products": [
"SharePoint"
],
@ -27,14 +27,13 @@
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-property-bag-editor/src/images/PropertyBagEditorDisplay.PNG",
"alt": "Property Bag Navigation Webparts"
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-property-bag-editor/assets/PropertyBagEditorDisplay.PNG",
"alt": "Property Bag Navigation Web parts"
}
],
"authors": [
{
"gitHubAccount": "russgove",
"company": "",
"pictureUrl": "https://github.com/russgove.png",
"name": "Russell Gove"
}

View File

@ -1,26 +1,6 @@
{
"entries": [
{
"entry": "./lib/webparts/propertyBagEditor/PropertyBagEditorWebPart.js",
"manifest": "./src/webparts/propertyBagEditor/PropertyBagEditorWebPart.manifest.json",
"outputPath": "./dist/property-bag-editor.bundle.js"
},
{
"entry": "./lib/webparts/propertyBagDisplay/PropertyBagDisplayWebPart.js",
"manifest": "./src/webparts/propertyBagDisplay/PropertyBagDisplayWebPart.manifest.json",
"outputPath": "./dist/property-bag-display.bundle.js"
},
{
"entry": "./lib/webparts/propertyBagFilteredSiteList/PropertyBagFilteredSiteListWebPart.js",
"manifest": "./src/webparts/propertyBagFilteredSiteList/PropertyBagFilteredSiteListWebPart.manifest.json",
"outputPath": "./dist/property-bag-filtered-site-list.bundle.js"
},
{
"entry": "./lib/webparts/propertyBagGlobalNav/PropertyBagGlobalNavWebPart.js",
"manifest": "./src/webparts/propertyBagGlobalNav/PropertyBagGlobalNavWebPart.manifest.json",
"outputPath": "./dist/property-bag-global-nav.bundle.js"
}
],
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"externals": {
"sp-pnp-js": "https://cdnjs.cloudflare.com/ajax/libs/sp-pnp-js/2.0.1/pnp.min.js",
"sp-init": {
@ -50,9 +30,43 @@
}
},
"localizedResources": {
"propertyBagEditorStrings": "webparts/propertyBagEditor/loc/{locale}.js",
"propertyBagDisplayStrings": "webparts/propertyBagDisplay/loc/{locale}.js",
"propertyBagFilteredSiteListStrings": "webparts/propertyBagFilteredSiteList/loc/{locale}.js",
"propertyBagGlobalNavStrings": "webparts/propertyBagGlobalNav/loc/{locale}.js"
"propertyBagEditorStrings": "lib/webparts/propertyBagEditor/loc/{locale}.js",
"propertyBagDisplayStrings": "lib/webparts/propertyBagDisplay/loc/{locale}.js",
"propertyBagFilteredSiteListStrings": "lib/webparts/propertyBagFilteredSiteList/loc/{locale}.js",
"propertyBagGlobalNavStrings": "lib/webparts/propertyBagGlobalNav/loc/{locale}.js"
},
"bundles": {
"property-bag-editor-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/propertyBagEditor/PropertyBagEditorWebPart.js",
"manifest": "./src/webparts/propertyBagEditor/PropertyBagEditorWebPart.manifest.json"
}
]
},
"property-bag-display-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/propertyBagDisplay/PropertyBagDisplayWebPart.js",
"manifest": "./src/webparts/propertyBagDisplay/PropertyBagDisplayWebPart.manifest.json"
}
]
},
"property-bag-filtered-site-list-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/propertyBagFilteredSiteList/PropertyBagFilteredSiteListWebPart.js",
"manifest": "./src/webparts/propertyBagFilteredSiteList/PropertyBagFilteredSiteListWebPart.manifest.json"
}
]
},
"property-bag-global-nav-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/propertyBagGlobalNav/PropertyBagGlobalNavWebPart.js",
"manifest": "./src/webparts/propertyBagGlobalNav/PropertyBagGlobalNavWebPart.manifest.json"
}
]
}
}
}

View File

@ -1,3 +0,0 @@
{
"deployCdnPath": "temp/deploy"
}

View File

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

View File

@ -1,5 +1,64 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"includeClientSideAssets": true,
"isDomainIsolated": false,
"developer": {
"name": "Russell Gove",
"privacyUrl": "",
"termsOfUseUrl": "",
"websiteUrl": "",
"mpnId": "Undefined-1.15.0"
},
"metadata": {
"shortDescription": {
"default": "react-property-bag-editor description"
},
"longDescription": {
"default": "react-property-bag-editor description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-property-bag-editor PropertyBagDisplayWebPart Feature",
"description": "The feature that activates PropertyBagDisplayWebPart from the react-property-bag-editor solution.",
"id": "fa63037d-d7bd-4d52-894a-b40127773283",
"version": "1.0.0.0",
"componentIds": [
"fa63037d-d7bd-4d52-894a-b40127773283"
]
},
{
"title": "react-property-bag-editor PropertyBagEditorWebPart Feature",
"description": "The feature that activates PropertyBagEditorWebPart from the react-property-bag-editor solution.",
"id": "f3ac8a07-2a9b-47a1-8a7e-a093cad63f98",
"version": "1.0.0.0",
"componentIds": [
"f3ac8a07-2a9b-47a1-8a7e-a093cad63f98"
]
},
{
"title": "react-property-bag-editor PropertyBagFilteredSiteListWebPart Feature",
"description": "The feature that activates PropertyBagFilteredSiteListWebPart from the react-property-bag-editor solution.",
"id": "b81a6789-e93b-4be5-baa7-59f34004694a",
"version": "1.0.0.0",
"componentIds": [
"b81a6789-e93b-4be5-baa7-59f34004694a"
]
},
{
"title": "react-property-bag-editor PropertyBagGlobalNavWebPart Feature",
"description": "The feature that activates PropertyBagGlobalNavWebPart from the react-property-bag-editor solution.",
"id": "8634e32b-eda4-483d-8fe9-5f2075339eb8",
"version": "1.0.0.0",
"componentIds": [
"8634e32b-eda4-483d-8fe9-5f2075339eb8"
]
}
],
"name": "react-property-bag-editor-client-side-solution",
"id": "12dac38e-b255-44ce-9f06-050571b34d39",
"version": "1.0.0.0"

View File

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

View File

@ -1,9 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"initialPage": "https://localhost:5432/workbench",
"https": true,
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
"initialPage": "https://rgove3.sharepoint.com/sites/ReactPropertyBagEditor",
"https": true
}

View File

@ -1,51 +0,0 @@
{
// Display errors as warnings
"displayAsWarning": true,
// The TSLint task may have been configured with several custom lint rules
// before this config file is read (for example lint rules from the tslint-microsoft-contrib
// project). If true, this flag will deactivate any of these rules.
"removeExistingRules": true,
// When true, the TSLint task is configured with some default TSLint "rules.":
"useDefaultConfigAsBase": false,
// Since removeExistingRules=true and useDefaultConfigAsBase=false, there will be no lint rules
// which are active, other than the list of rules below.
"lintConfig": {
// Opt-in to Lint rules which help to eliminate bugs in JavaScript
"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-case": true,
"no-unused-variable":"true",
"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-unused-imports": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"valid-typeof": true,
"variable-name": false,
"whitespace": false,
"prefer-const": true
}
}
}

View File

@ -1,3 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "https://rgove3.sharepoint.com/sites/cdn/spfxapps/propertybageditor"
}

View File

@ -2,5 +2,13 @@
const gulp = require('gulp');
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(gulp);

File diff suppressed because it is too large Load Diff

View File

@ -6,30 +6,36 @@
"node": ">=0.10.0"
},
"dependencies": {
"@microsoft/sp-client-base": "~1.0.0",
"@microsoft/sp-core-library": "~1.0.0",
"@microsoft/sp-webpart-base": "~1.0.0",
"@types/react": "0.14.46",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-test-utils": "0.14.15",
"@types/react-addons-update": "0.14.14",
"@types/react-dom": "0.14.18",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"@microsoft/sp-adaptive-card-extension-base": "1.17.1",
"@microsoft/sp-core-library": "1.17.1",
"@microsoft/sp-property-pane": "1.17.1",
"@microsoft/sp-webpart-base": "1.17.1",
"lodash": "^4.17.4",
"office-ui-fabric-react": "^0.69.0",
"react": "0.14.8",
"react-dom": "0.14.8",
"office-ui-fabric-react": "7.199.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"sp-pnp-js": "^2.0.1",
"typescript": "^2.1.5"
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.0.0",
"@microsoft/sp-module-interfaces": "~1.0.0",
"@microsoft/sp-webpart-workbench": "~1.0.0",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/mocha": ">=2.2.33 <2.6.0"
"@microsoft/eslint-config-spfx": "1.17.1",
"@microsoft/eslint-plugin-spfx": "1.17.1",
"@microsoft/rush-stack-compiler-4.5": "0.4.0",
"@microsoft/sp-build-web": "1.17.1",
"@microsoft/sp-module-interfaces": "1.17.1",
"@rushstack/eslint-config": "2.5.1",
"@types/es6-promise": "0.0.33",
"@types/microsoft-ajax": "^0.0.41",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/sharepoint": "^2016.1.14",
"@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",
"tslint-microsoft-contrib": "5.0.0",
"typescript": "4.5.5"
},
"scripts": {
"build": "gulp bundle",

View File

@ -0,0 +1,3 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler
console.log("test");

View File

@ -0,0 +1,2 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -1,22 +1,32 @@
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "fa63037d-d7bd-4d52-894a-b40127773283",
"alias": "PropertyBagDisplayWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"version": "*",
"manifestVersion": 2,
"preconfiguredEntries": [{
"groupId": "fa63037d-d7bd-4d52-894a-b40127773283",
"group": { "default": "Property Bag Navigation" },
"title": { "default": "Property Bag Display" },
"description": { "default": "Displays all Sites and selected properties, an lets you edit those propertiies" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "propertyBagDisplay",
"propertiesToDisplay":
"CUSTOMNAVAreaName|AreaName\nCUSTOMNAVBusinessUnit|BusinessUnit\nCUSTOMNAVContinent|Continent\nCUSTOMNAVLocation|Location",
"siteTemplatesToInclude":
"STS\nPUBLISHING"
}
}]
"supportedHosts": [
"SharePointWebPart"
],
"safeWithCustomScriptDisabled": false,
"preconfiguredEntries": [
{
"groupId": "fa63037d-d7bd-4d52-894a-b40127773283",
"group": {
"default": "Property Bag Navigation"
},
"title": {
"default": "Property Bag Display"
},
"description": {
"default": "Displays all Sites and selected properties, an lets you edit those propertiies"
},
"officeFabricIconFontName": "Page",
"properties": {
"description": "propertyBagDisplay",
"propertiesToDisplay": "CUSOMNAVAreaName|AreaName\nCUSOMNAVBusinessUnit|BusinessUnit\nCUSOMNAVContinent|Continent\nCUSOMNAVLocation|Location",
"siteTemplatesToInclude": "STS\nPUBLISHING"
}
}
]
}

View File

@ -2,17 +2,15 @@ import * as React from "react";
import pnp from "sp-pnp-js";
import * as ReactDom from "react-dom";
import { Version } from "@microsoft/sp-core-library";
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from "@microsoft/sp-webpart-base";
import * as strings from "propertyBagDisplayStrings";
import PropertyBagDisplay from "./components/PropertyBagDisplay";
import { IPropertyBagDisplayProps } from "./components/IPropertyBagDisplayProps";
import { IPropertyBagDisplayWebPartProps } from "./IPropertyBagDisplayWebPartProps";
import utils from "../shared/utils";
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IPropertyPaneConfiguration, PropertyPaneTextField } from "@microsoft/sp-property-pane";
export default class PropertyBagDisplayWebPart extends BaseClientSideWebPart<IPropertyBagDisplayWebPartProps> {
/**
@ -30,10 +28,11 @@ export default class PropertyBagDisplayWebPart extends BaseClientSideWebPart<IPr
{
description: this.properties.description,
propertiesToDisplay: utils.parseMultilineTextToArray(this.properties.propertiesToDisplay),
siteTemplatesToInclude:utils.parseMultilineTextToArray(this.properties.siteTemplatesToInclude)
siteTemplatesToInclude: utils.parseMultilineTextToArray(this.properties.siteTemplatesToInclude)
}
);
// eslint-disable-next-line @microsoft/spfx/pair-react-dom-render-unmount
ReactDom.render(element, this.domElement);
}
public onInit(): Promise<void> {
@ -56,7 +55,7 @@ export default class PropertyBagDisplayWebPart extends BaseClientSideWebPart<IPr
pages: [
{
header: {
description: strings.PropertyPaneDescription
description: "strings.PropertyPaneDescription"
},
groups: [
{

View File

@ -1,3 +1,5 @@
@import '~@fluentui/react/dist/sass/References.scss';
.helloWorld {
.container {

View File

@ -1,40 +1,33 @@
import * as React from "react";
import pnp from "sp-pnp-js";
import { Web } from "sp-pnp-js";
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import * as _ from "lodash";
import utils from "../../shared/utils";
import * as React from "react";
import pnp, { SearchQuery, SearchResults, Web } from "sp-pnp-js";
import DisplayProp from "../../shared/DisplayProp";
import { SearchQuery, SearchResults } from "sp-pnp-js";
import { css } from "office-ui-fabric-react";
import utils from "../../shared/utils";
//import styles from "./PropertyBagDisplay.module.scss";
import { IPropertyBagDisplayProps } from "./IPropertyBagDisplayProps";
import { DefaultButton, PrimaryButton } from "office-ui-fabric-react/lib/Button";
import { CommandBar } from "office-ui-fabric-react/lib/CommandBar";
import {
CheckboxVisibility,
DetailsList, DetailsListLayoutMode, IColumn,
SelectionMode
} from "office-ui-fabric-react/lib/DetailsList";
import { Label } from "office-ui-fabric-react/lib/Label";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import { Toggle } from "office-ui-fabric-react/lib/Toggle";
import { Button, ButtonType } from "office-ui-fabric-react/lib/Button";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar";
import * as md from "../../shared/MessageDisplay";
import MessageDisplay from "../../shared/MessageDisplay";
import {
DetailsList, DetailsListLayoutMode, IColumn, IGroupedList, SelectionMode, CheckboxVisibility, IGroup
} from "office-ui-fabric-react/lib/DetailsList";
import {
GroupedList
} from "office-ui-fabric-react/lib/GroupedList";
import {
IViewport
} from "office-ui-fabric-react/lib/utilities/decorators/withViewport";
import MessageDisplay, * as md from "../../shared/MessageDisplay";
import { IPropertyBagDisplayProps } from "./IPropertyBagDisplayProps";
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
import {
Panel, PanelType
} from "office-ui-fabric-react/lib/Panel";
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
export interface IPropertyBagDisplayState {
selectedIndex: number; // the currently selected site
managedToCrawedMapping?: Array<ManagedToCrawledMappingEntry>;// Determines which Carwled propeties are mapped to which Managed Properties
managedToCrawedMapping?: Array<ManagedToCrawledMappingEntry>;// Determines which Crawled properties are mapped to which Managed Properties
errorMessages: Array<md.Message>; // a list of error massages displayed on the page
isediting?: boolean; //Determines if the edit panel is displayed
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sites: Array<any>; // the list of sites displayed in the component
workingStorage?: DisplaySite;// A working copy of the site being edited
managedPropNames?: Array<string>; // the list of managed properties to be displayed
@ -99,7 +92,7 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
icon: "Edit",
}];
};
}
get ItemIsSelected(): boolean {
if (!this.state) { return false; }
return (this.state.selectedIndex !== -1);
@ -112,7 +105,7 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
public renderPopup() {
private renderPopup(): JSX.Element {
if (!this.state.workingStorage) {
return (<div />);
@ -127,7 +120,7 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
hideMessage={this.removePanelMessage.bind(this)} />
<div> <Label >Site Title</Label> {this.state.workingStorage.Title}</div>
<span> <Label label="" >Site Url</Label> {this.state.workingStorage.Url}</span>
<span> <Label >Site Url</Label> {this.state.workingStorage.Url}</span>
<table>
<thead>
<tr>
@ -141,21 +134,25 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
<tbody>
{this.state.workingStorage.DisplayProps.map((dp, i) => {
return (<tr>
return (<tr key={dp.managedPropertyName}>
<td>{dp.managedPropertyName}</td>
<td>{this.state.workingStorage[dp.managedPropertyName]}</td>
<td>{dp.crawledPropertyName}</td>
<td>
<TextField
data-crawledPropertyName={dp.crawledPropertyName}
value={dp.value}
onBlur={this.onPropertyValueChanged.bind(this)}
onChange={(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => {
debugger;
const ws = _.clone(this.state.workingStorage);
_.find(ws.DisplayProps, p => { return p.crawledPropertyName === dp.crawledPropertyName; }).value = newValue;
this.setState((current) => ({ ...current, workingStorage: ws }));
}}
/>
</td>
<td>
<Toggle label=""
checked={dp.searchable}
onChanged={this.createSearcheableOnChangedHandler(dp.crawledPropertyName)}
onChange={this.createSearcheableOnChangedHandler(dp.crawledPropertyName)}
/>
</td>
</tr>);
@ -164,10 +161,10 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
</table>
<Toggle label="Force Crawl"
checked={this.state.workingStorage.forceCrawl}
onChanged={this.onForceCrawlChange.bind(this)}
onChange={this.onForceCrawlChange.bind(this)}
/>
<Button default={true} icon="Save" buttonType={ButtonType.hero} value="Save" onClick={this.onSave.bind(this)} >Save</Button>
<Button icon="Cancel" buttonType={ButtonType.normal} value="Cancel" onClick={this.onCancel.bind(this)} >Cancel</Button>
<DefaultButton default={true} iconProps={{ iconName: "Save" }} value="Save" onClick={this.onSave.bind(this)} >Save</DefaultButton>
<PrimaryButton iconProps={{ iconName: "Cancel" }} value="Cancel" onClick={this.onCancel.bind(this)} >Cancel</PrimaryButton>
</Panel>
);
@ -176,25 +173,25 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
/**
* Removes a message from the MessageDIsplay when the user click the 'x'
*
* @param {Array<md.Message>} messageList The list to remove the masseg from (the 'main' window of the Panel)
* @param {string} messageId The Id of the massge to remove
* @param {Array<md.Message>} messageList The list to remove the message from (the 'main' window of the Panel)
* @param {string} messageId The Id of the message to remove
*
* @memberOf PropertyBagDisplay
*/
public removeMessage(messageList: Array<md.Message>, messageId: string) {
private removeMessage(messageList: Array<md.Message>, messageId: string): void {
_.remove(messageList, {
Id: messageId
});
this.setState(this.state);
this.setState((current) => ({ ...current, errorMessages: messageList }));
}
/**
* Removes a massage from the main windo
* Removes a massage from the main window
*
* @param {string} messageId
*
* @memberOf PropertyBagDisplay
*/
public removeMainMessage(messageId: string) {
private removeMainMessage(messageId: string): void {
this.removeMessage(this.state.errorMessages, messageId);
}
/**
@ -204,7 +201,7 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
public removePanelMessage(messageId: string) {
private removePanelMessage(messageId: string): void {
this.removeMessage(this.state.workingStorage.errorMessages, messageId);
}
/**
@ -217,9 +214,10 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
public changeSearchable(siteUrl: string, propname: string, newValue: boolean): Promise<any> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private changeSearchable(siteUrl: string, propname: string, newValue: boolean): Promise<any> {
if (newValue) {//make prop searchable
if (_.indexOf(this.state.workingStorage.searchableProps, propname) === -1) {// wasa not searchable, mpw it is
if (_.indexOf(this.state.workingStorage.searchableProps, propname) === -1) {// was not searchable, now it is
console.log(propname + "was not searchable, now it is ");
this.state.workingStorage.searchableProps.push(propname);
return utils.saveSearchablePropertiesToSharePoint(siteUrl, this.state.workingStorage.searchableProps);
@ -229,8 +227,8 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
return Promise.resolve();
}
}
else { // make prop not searchablke
if (_.indexOf(this.state.workingStorage.searchableProps, propname) !== -1) {// wasa not searchable, mpw it is
else { // make prop not searchable
if (_.indexOf(this.state.workingStorage.searchableProps, propname) !== -1) {// was not searchable, now it is
console.log(propname + "was searchable, now it is not");
_.remove(this.state.workingStorage.searchableProps, p => { return p === propname; });
return utils.saveSearchablePropertiesToSharePoint(siteUrl, this.state.workingStorage.searchableProps);
@ -247,12 +245,15 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
public stopediting() {
this.state.isediting = false;
this.setState(this.state);
private stopediting(): void {
this.setState((current) => ({
...current,
isediting: false,
}));
}
/**
* Caled by the Details list to render a column as a URL rather than text
* Called by the Details list to render a column as a URL rather than text
*
* @private
* @param {*} [item]
@ -262,13 +263,16 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
private renderSiteUrl(item?: any, index?: number, column?: IColumn): any {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private renderSiteUrl(item?: any, index?: number, column?: IColumn): JSX.Element {
return (<a href={item[column.fieldName]}>{item[column.fieldName]} </a>);
}
/**
* Sets the columns to be displayed in the list.
* These are SiteTemplate, Title and Url, plus any properties specified in
* the propertypane
* the property pane
*
* @private
* @returns {Array<IColumn>}
@ -321,26 +325,31 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
}
/** react lifecycle */
/**
* Called when the componet loads.
* Builds the query to search sharepoint for the list of sites to display and formates
* Called when the component loads.
* Builds the query to search sharepoint for the list of sites to display and formats
* the results to be displayed in the list
*
*
* @memberOf PropertyBagDisplay
*/
public componentWillMount() {
this.state.columns = this.setupColumns();
this.state.managedToCrawedMapping = [];
this.state.managedPropNames = [];
public componentDidMount(): void {
const initState = {
columns: this.setupColumns(),
managedToCrawedMapping: [],
managedPropNames: [],
sites: [],
errorMessages: []
};
for (const prop of this.props.propertiesToDisplay) {
const names: Array<string> = prop.split('|');// crawledpropety/managed property
this.state.managedToCrawedMapping.push(new ManagedToCrawledMappingEntry(names[0], names[1]));
this.state.managedPropNames.push(names[1]);
const names: Array<string> = prop.split('|');// crawled property/managed property
initState.managedToCrawedMapping.push(new ManagedToCrawledMappingEntry(names[0], names[1]));
initState.managedPropNames.push(names[1]);
}
this.state.managedPropNames.unshift("Title");
this.state.managedPropNames.unshift("Url");
this.state.managedPropNames.unshift("SiteTemplate");
this.state.managedPropNames.unshift("SiteTemplateId");
initState.managedPropNames.unshift("Title");
initState.managedPropNames.unshift("Url");
initState.managedPropNames.unshift("SiteTemplate");
initState.managedPropNames.unshift("SiteTemplateId");
let querytext = "contentclass:STS_Site ";
if (this.props.siteTemplatesToInclude) {
if (this.props.siteTemplatesToInclude.length > 0) {
@ -353,8 +362,7 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
else {
querytext += "(SiteTemplate=" + siteTemplateParts[0] + " AND SiteTemplateId=" + siteTemplateParts[1] + ")";
}
if (this.props.siteTemplatesToInclude.indexOf(siteTemplate) !== this.props.siteTemplatesToInclude.length - 1)
{ querytext += " OR "; }
if (this.props.siteTemplatesToInclude.indexOf(siteTemplate) !== this.props.siteTemplatesToInclude.length - 1) { querytext += " OR "; }
}
querytext += " )";
}
@ -362,26 +370,26 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
console.log("Using Query " + querytext);
const q: SearchQuery = {
Querytext: querytext,
SelectProperties: this.state.managedPropNames,
SelectProperties: initState.managedPropNames,
RowLimit: 999,
TrimDuplicates: false
};
pnp.sp.search(q).then((results: SearchResults) => {
for (const r of results.PrimarySearchResults) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const obj: any = {};
for (const dp of this.state.managedPropNames) {
for (const dp of initState.managedPropNames) {
obj[dp] = r[dp];
}
obj.SiteTemplate = obj.SiteTemplate + "#" + obj.SiteTemplateId;
this.state.sites.push(obj);
initState.sites.push(obj);
}
debugger;
this.state.errorMessages.push(new md.Message("Items Recieved"));
this.setState(this.state);
this.setState({ ...initState });
}).catch(err => {
debugger;
this.state.errorMessages.push(new md.Message(err));
this.setState(this.state);
initState.errorMessages.push(new md.Message(err));
this.setState({ ...initState });
});
}
/** Event Handlers */
@ -393,9 +401,9 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
public onActiveItemChanged(item?: any, index?: number) {
this.state.selectedIndex = index;
this.setState(this.state);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private onActiveItemChanged(item?: any, index?: number): void {
this.setState((current) => ({ ...current, selectedIndex: index }));
}
/**
@ -405,29 +413,32 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
public onSave(e?: MouseEvent): void {
private onSave(e?: MouseEvent): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const promises: Array<Promise<any>> = [];
for (const prop of this.state.workingStorage.DisplayProps) {
const promise = utils.setSPProperty(prop.crawledPropertyName, prop.value, this.state.workingStorage.Url)
.then(value => {
this.changeSearchable(this.state.workingStorage.Url, prop.crawledPropertyName, prop.searchable);
return this.changeSearchable(this.state.workingStorage.Url, prop.crawledPropertyName, prop.searchable);
});
promises.push(promise);
}
Promise.all(promises)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.then((results: Array<any>) => {
if (this.state.workingStorage.forceCrawl) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
utils.forceCrawl(this.state.workingStorage.Url);
}
this.state.workingStorage = null;
this.state.isediting = false;
debugger;
this.setState((current) => ({ ...current, workingStorage: null, isediting: false }));
this.setState(this.state);
}).catch((err) => {
debugger;
this.state.workingStorage.errorMessages.push(new md.Message(err));
this.setState(this.state);
console.log(err);
const temp = _.clone(this.state.workingStorage);
temp.errorMessages.push(new md.Message(err));
this.setState(current => ({ ...current, workingStorage: temp }))
});
}
/**
@ -437,10 +448,8 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
public onCancel(e?: MouseEvent): void {
this.state.isediting = false;
this.state.workingStorage = null;
this.setState(this.state);
private onCancel(e?: MouseEvent): void {
this.setState((current) => ({ ...current, workingStorage: null, isediting: false }));
}
/**
* Set the ForceCrawl Value in working storage which can be used to force a crawl of the site
@ -451,25 +460,11 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
* @memberOf PropertyBagDisplay
*/
public onForceCrawlChange(newValue: boolean) {
this.state.workingStorage.forceCrawl = newValue;
this.setState(this.state);
private onForceCrawlChange(newValue: boolean): void {
this.setState(current => ({ ...current, workingStorage: ({ ...current.workingStorage, forceCrawl: newValue }) }));
}
/**
* Called when the value of a property i schanged in the display.
* Saves the new value in workingStarage,
*
* @param {React.FormEvent<HTMLInputElement>} event
*
* @memberOf PropertyBagDisplay
*/
public onPropertyValueChanged(event: React.FormEvent<HTMLInputElement>) {
const selectedProperty = event.currentTarget.attributes["data-crawledpropertyname"].value;
const dp: DisplayProp = _.find(this.state.workingStorage.DisplayProps, p => { return p.crawledPropertyName === selectedProperty; });
dp.value = event.currentTarget.value;
this.setState(this.state);
}
public createSearcheableOnChangedHandler = (managedPropertyName) => (value) => {
private createSearcheableOnChangedHandler = (managedPropertyName) => (value) => {
const dp: DisplayProp = _.find(this.state.workingStorage.DisplayProps, p => { return p.crawledPropertyName === managedPropertyName; });
dp.searchable = value;
this.setState(this.state);
@ -477,32 +472,39 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
/**
* Called when user wishes to edit an item.
* The List displayes the values from the search index.
* The List displays the values from the search index.
* This method gets the values from the actual PropertyBag so that they can be edited.
*
* @param {MouseEvent} [e]
*
* @memberOf PropertyBagDisplay
*/
public onEditItemClicked(e?: MouseEvent): void {
private onEditItemClicked(e?: MouseEvent): void {
debugger;
console.log("in onEditItemClicked");
const selectedSite = this.state.sites[this.state.selectedIndex];
const web = new Web(selectedSite.Url);
web.select("Title", "AllProperties").expand("AllProperties").get().then(r => {
// let context = this;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
web.select("Title", "AllProperties").expand("AllProperties").get().then((r) => {
const crawledProps: Array<string> = this.props.propertiesToDisplay.map(item => {
return item.split("|")[0];
});
this.state.workingStorage = _.clone(this.state.sites[this.state.selectedIndex]);
this.state.workingStorage.searchableProps = utils.decodeSearchableProps(r.AllProperties["vti_x005f_indexedpropertykeys"]);
this.state.workingStorage.DisplayProps = utils.SelectProperties(r.AllProperties, crawledProps, this.state.workingStorage.searchableProps);
this.state.workingStorage.errorMessages = new Array<md.Message>();
const temp = _.clone(selectedSite);
// eslint-disable-next-line dot-notation
temp.searchableProps = utils.decodeSearchableProps(r.AllProperties["vti_x005f_indexedpropertykeys"]);
temp.DisplayProps = utils.SelectProperties(r.AllProperties, crawledProps, temp.searchableProps);
temp.errorMessages = new Array<md.Message>();
// now add in the managed Prop
for (const dp of this.state.workingStorage.DisplayProps) {
for (const dp of temp.DisplayProps) {
dp.managedPropertyName =
_.find(this.state.managedToCrawedMapping, mtc => { return mtc.crawledPropertyName === dp.crawledPropertyName; }).managedPropertyName;
}
this.state.isediting = true;
this.setState(this.state);
this.setState((current) => ({
...current,
workingStorage: temp, isediting: true
}));
});
console.log("out onEditItemClicked");
}
@ -515,6 +517,7 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
*
* @memberOf PropertyBagDisplay
*/
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-explicit-any
private _onColumnClick(event: any, column: IColumn) {
column = _.find(this.state.columns, c => c.fieldName === column.fieldName);// find the object in state
// If we've sorted this column, flip it.
@ -526,15 +529,19 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
column.isSortedDescending = false;
}
// Sort the items.
this.state.sites = _.orderBy(this.state.sites, [(site, x, y, z) => {
const temp = _.orderBy(this.state.sites, (site) => {
if (site[column.fieldName]) {
return site[column.fieldName].toLowerCase();
}
else {
return "";
}
}], [column.isSortedDescending ? "desc" : "asc"]);
this.setState(this.state);
}, [column.isSortedDescending ? "desc" : "asc"]);
this.setState((current) => ({
...current,
sites: temp
}));
}
@ -563,8 +570,7 @@ export default class PropertyBagDisplay extends React.Component<IPropertyBagDisp
checkboxVisibility={CheckboxVisibility.hidden}
onActiveItemChanged={this.onActiveItemChanged.bind(this)
}
>
</DetailsList>
/>
{this.renderPopup.bind(this)()}
</div >
);

View File

@ -2,10 +2,9 @@ declare interface IPropertyBagDisplayStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
PropertiesToDisplayFieldLabel:string;
SiteTemplatesToIncludeFieldLabel:string;
PropertiesToDisplayFieldLabel: string;
SiteTemplatesToIncludeFieldLabel: string;
}
declare module 'propertyBagDisplayStrings' {
const strings: IPropertyBagDisplayStrings;
export = strings;

View File

@ -1,9 +1,9 @@
/// <reference types="mocha" />
// /// <reference types="mocha" />
import { assert } from 'chai';
// import { assert } from 'chai';
describe('PropertyBagDisplayWebPart', () => {
it('should do something', () => {
assert.ok(true);
});
});
// describe('PropertyBagDisplayWebPart', () => {
// it('should do something', () => {
// assert.ok(true);
// });
// });

View File

@ -1,22 +1,31 @@
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "f3ac8a07-2a9b-47a1-8a7e-a093cad63f98",
"alias": "PropertyBagEditorWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"version": "*",
"manifestVersion": 2,
"preconfiguredEntries": [{
"groupId": "f3ac8a07-2a9b-47a1-8a7e-a093cad63f98",
"group": { "default": "Property Bag Navigation" },
"title": { "default": "Property Bag Editor" },
"description": { "default": "Lets you edit the properties of an SPSite passed in as a query parameter" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "PropertyBagEditor",
"propertiesToEdit":
"CUSTOMNAVAreaName\nCUSTOMNAVBusinessUnit\nCUSTOMNAVContinent\nCUSTOMNAVLocation"
}
}]
"supportedHosts": [
"SharePointWebPart"
],
"safeWithCustomScriptDisabled": false,
"preconfiguredEntries": [
{
"groupId": "f3ac8a07-2a9b-47a1-8a7e-a093cad63f98",
"group": {
"default": "Property Bag Navigation"
},
"title": {
"default": "Property Bag Editor"
},
"description": {
"default": "Lets you edit the properties of an SPSite passed in as a query parameter"
},
"officeFabricIconFontName": "Page",
"properties": {
"description": "PropertyBagEditor",
"propertiesToEdit": "CUSOMNAVAreaName\nCUSOMNAVBusinessUnit\nCUSOMNAVContinent\nCUSOMNAVLocation"
}
}
]
}

View File

@ -2,12 +2,8 @@ import * as React from "react";
import * as ReactDom from "react-dom";
import { Version, UrlQueryParameterCollection } from "@microsoft/sp-core-library";
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from "@microsoft/sp-webpart-base";
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IPropertyPaneConfiguration, PropertyPaneTextField } from "@microsoft/sp-property-pane";
import * as strings from "propertyBagEditorStrings";
import PropertyBagEditor from "./components/PropertyBagEditor";
import { IPropertyBagEditorProps } from "./components/IPropertyBagEditorProps";
@ -50,6 +46,7 @@ export default class PropertyBagEditorWebPart extends BaseClientSideWebPart<IPro
props
);
// eslint-disable-next-line @microsoft/spfx/pair-react-dom-render-unmount
ReactDom.render(element, this.domElement);
}

View File

@ -1,3 +1,5 @@
@import '~@fluentui/react/dist/sass/References.scss';
.helloWorld {
.container {

View File

@ -1,24 +1,26 @@
import * as React from "react";
import { css } from "office-ui-fabric-react"; import { IPropertyBagEditorProps } from "./IPropertyBagEditorProps";
import { Web } from "sp-pnp-js";
/* eslint-disable react/no-deprecated */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import * as _ from "lodash";
import utils from "../../shared/utils";
require("sp-init");
require("microsoft-ajax");
require("sp-runtime");
require("sharepoint");
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
import { DefaultButton, PrimaryButton } from "office-ui-fabric-react/lib/Button";
import { CommandBar } from "office-ui-fabric-react/lib/CommandBar";
import { MessageBar } from "office-ui-fabric-react/lib/MessageBar";
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
import {
DetailsList, DetailsListLayoutMode, IColumn, SelectionMode, CheckboxVisibility,
CheckboxVisibility,
DetailsList, DetailsListLayoutMode, IColumn, SelectionMode,
} from "office-ui-fabric-react/lib/DetailsList";
import { Dialog, DialogType } from "office-ui-fabric-react/lib/Dialog";
import { Label } from "office-ui-fabric-react/lib/Label";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import { Toggle } from "office-ui-fabric-react/lib/Toggle";
import { Button, ButtonType } from "office-ui-fabric-react/lib/Button";
import * as React from "react";
import { Web } from "sp-pnp-js";
import DisplayProp from "../../shared/DisplayProp";
import utils from "../../shared/utils";
import { IPropertyBagEditorProps } from "./IPropertyBagEditorProps";
require("sp-init");
require("microsoft-ajax");
require("sp-runtime");
require("sharepoint");
export interface IPropertyBagEditorState {
displayProps: Array<DisplayProp>; // The list of properties displayed in the webpart
@ -31,7 +33,8 @@ export interface IPropertyBagEditorState {
export default class PropertyBagEditor extends React.Component<IPropertyBagEditorProps, IPropertyBagEditorState> {
public refs: {
[key: string]: React.ReactInstance;
list: DetailsList
// eslint-disable-next-line @typescript-eslint/no-explicit-any
list: any //DetailsList
};
public constructor(props: IPropertyBagEditorProps) {
super(props);
@ -58,7 +61,7 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
onClick: this.onEditItemClicked.bind(this),
icon: "Edit"
}];
};
}
/**
* Determines if an item is selected.
@ -69,30 +72,30 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
*/
get ItemIsSelected(): boolean {
if (!this.state) { return false; }
return (this.state.selectedIndex != -1);
return (this.state.selectedIndex !== -1);
}
/** react lifecycle */
public componentWillMount() {
const web = new Web(this.props.siteUrl);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
web.select("Title", "AllProperties").expand("AllProperties").get().then(r => {
const sp = utils.decodeSearchableProps(r.AllProperties["vti_x005f_indexedpropertykeys"]);
debugger;
const sp = utils.decodeSearchableProps(r.AllProperties.vti_x005f_indexedpropertykeys);
const dp = utils.SelectProperties(r.AllProperties, this.props.propertiesToEdit, sp);
this.state.searchableProps = sp;
this.state.displayProps = dp;
this.setState(this.state);
this.setState((current) => ({ ...current, searchableProps: sp, displayProps: dp }))
});
}
/** event hadlers */
public stopediting() {
this.state.isediting = false;
this.setState(this.state);
/** event handlers */
private stopediting() {
this.setState((current) => ({ ...current, isediting: false }))
}
public onActiveItemChanged(item?: any, index?: number) {
this.state.selectedIndex = index;
this.setState(this.state);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private onActiveItemChanged(item?: any, index?: number) {
this.setState((current) => ({ ...current, selectedIndex: index }))
}
/**
* Gets fired when the user changes the 'Searchable' value in the ui.
@ -102,9 +105,9 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
*
* @memberOf PropertyBagEditor
*/
public onSearchableValueChanged(newValue: boolean) {
this.state.workingStorage.searchable = newValue;
this.setState(this.state);
private onSearchableValueChanged(e: Event, newValue: boolean) {
debugger;
this.setState((current) => ({ ...current, workingStorage: ({ ...current.workingStorage, searchable: newValue }) }));
}
/**
* Gets fired when the user changes the proprty value in the ui
@ -114,9 +117,16 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
*
* @memberOf PropertyBagEditor
*/
public onPropertyValueChanged(event) {
this.state.workingStorage.value = event.target.value;
this.setState(this.state);
private onPropertyValueChanged(event) {
debugger;
this.setState((current) => ({
...current,
workingStorage: ({
...current.workingStorage,
value: event.target.value
})
}
));
}
/**
@ -126,10 +136,8 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
*
* @memberOf PropertyBagEditor
*/
public onEditItemClicked(e?: MouseEvent): void {
this.state.isediting = true;
this.state.workingStorage = _.clone(this.state.displayProps[this.state.selectedIndex]);
this.setState(this.state);
private onEditItemClicked(e?: MouseEvent): void {
this.setState((current) => ({ ...current, isediting: true, workingStorage: _.clone(current.displayProps[current.selectedIndex]) }))
}
/**
* Saves the item in workingStorage back to sharepoint, then clears workingStorage and stops editing.
@ -138,15 +146,17 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
*
* @memberOf PropertyBagEditor
*/
public onSave(e?: MouseEvent): void {
private onSave(e?: MouseEvent): void {
debugger;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
utils.setSPProperty(this.state.workingStorage.crawledPropertyName, this.state.workingStorage.value, this.props.siteUrl)
.then(value => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.changeSearchable(this.state.workingStorage.crawledPropertyName, this.state.workingStorage.searchable)
.then(s => {
this.state.displayProps[this.state.selectedIndex] = this.state.workingStorage;
this.state.workingStorage = null;
this.state.isediting = false;
this.setState(this.state);
const temp = _.clone(this.state.displayProps);// this.state.workingStorage = null;
temp[this.state.selectedIndex] = this.state.workingStorage;// this.state.isediting = false;
this.setState((current) => ({ ...current, isediting: false, workingStorage: null, displayProps: temp }))
});
});
}
@ -157,10 +167,8 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
*
* @memberOf PropertyBagEditor
*/
public onCancel(e?: MouseEvent): void {
this.state.isediting = false;
this.state.workingStorage = null;
this.setState(this.state);
private onCancel(e?: MouseEvent): void {
this.setState((current) => ({ ...current, isediting: false, workingStorage: null }))
}
@ -173,11 +181,14 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
*
* @memberOf PropertyBagEditor
*/
public changeSearchable(propname: string, newValue: boolean): Promise<any> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private changeSearchable(propname: string, newValue: boolean): Promise<any> {
if (newValue) {//make prop searchable
if (_.indexOf(this.state.searchableProps, propname) === -1) {// wasa not searchable, mpw it is
this.state.searchableProps.push(propname);
return utils.saveSearchablePropertiesToSharePoint(this.props.siteUrl, this.state.searchableProps);
const temp = _.clone(this.state.searchableProps);
temp.push(propname);
this.setState(current => ({ ...current, searchableProps: temp }));
return utils.saveSearchablePropertiesToSharePoint(this.props.siteUrl, temp);
}
else {
return Promise.resolve();
@ -185,14 +196,18 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
}
else { // make prop not searchablke
if (_.indexOf(this.state.searchableProps, propname) !== -1) {// wasa not searchable, mpw it is
_.remove(this.state.searchableProps, p => { return p === propname; });
return utils.saveSearchablePropertiesToSharePoint(this.props.siteUrl, this.state.searchableProps);
const temp = _.clone(this.state.searchableProps);
_.remove(temp, p => { return p === propname; });
this.setState(current => ({ ...current, searchableProps: temp }));
return utils.saveSearchablePropertiesToSharePoint(this.props.siteUrl, temp);
}
else {
return Promise.resolve();
}
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private RenderBoolean(item?: any, index?: number, column?: IColumn): any {
if (item[column.fieldName]) {
return (<div>Yes</div>);
@ -213,7 +228,7 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
{ isResizable: true, key: "value", name: "Propert Value", fieldName: "value", minWidth: 150 },
{ key: "searchable", name: "searchable", fieldName: "searchable", minWidth: 150, onRender: this.RenderBoolean },
];
debugger;
return (
<div>
<CommandBar items={this.CommandItems} />
@ -223,10 +238,9 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
checkboxVisibility={CheckboxVisibility.hidden}
items={this.state.displayProps}
onActiveItemChanged={this.onActiveItemChanged.bind(this)}
>
</DetailsList>
/>
<Dialog
isOpen={this.state.isediting} type={DialogType.close}
hidden={!this.state.isediting} type={DialogType.close}
onDismiss={this.stopediting.bind(this)}
title={(this.state.workingStorage) ? this.state.workingStorage.crawledPropertyName : ""} >
@ -234,19 +248,19 @@ export default class PropertyBagEditor extends React.Component<IPropertyBagEdito
<TextField
value={(this.state.workingStorage) ? this.state.workingStorage.value : ""}
onBlur={this.onPropertyValueChanged.bind(this)}
onChange={this.onPropertyValueChanged.bind(this)}
/>
<Toggle label="Searchable"
checked={(this.state.workingStorage) ? this.state.workingStorage.searchable : undefined}
onChanged={this.onSearchableValueChanged.bind(this)}
onChange={this.onSearchableValueChanged.bind(this)}
/>
<Button default={true} icon="Save" buttonType={ButtonType.icon} value="Save" onClick={this.onSave.bind(this)} >Save</Button>
<Button icon="Cancel" buttonType={ButtonType.icon} value="Cancel" onClick={this.onCancel.bind(this)} >Cancel</Button>
<DefaultButton default={true} iconProps={{ iconName: "Save" }} value="Save" onClick={this.onSave.bind(this)} >Save</DefaultButton>
<PrimaryButton iconProps={{ iconName: "Cancel" }} value="Cancel" onClick={this.onCancel.bind(this)} >Cancel</PrimaryButton>
</Dialog>

View File

@ -2,7 +2,7 @@ declare interface IPropertyBagEditorStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
PropertiesToEditFieldLabel:string;
PropertiesToEditFieldLabel: string;
}
declare module 'propertyBagEditorStrings' {

View File

@ -1,9 +1,9 @@
/// <reference types="mocha" />
// /// <reference types="mocha" />
import { assert } from 'chai';
// import { assert } from 'chai';
describe('PropertyBagEditorWebPart', () => {
it('should do something', () => {
assert.ok(true);
});
});
// describe('PropertyBagEditorWebPart', () => {
// it('should do something', () => {
// assert.ok(true);
// });
// });

View File

@ -1,15 +1,23 @@
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "b81a6789-e93b-4be5-baa7-59f34004694a",
"alias": "PropertyBagFilteredSiteListWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"version": "*",
"manifestVersion": 2,
"supportedHosts": [
"SharePointWebPart"
],
"safeWithCustomScriptDisabled": false,
"preconfiguredEntries": [
{
"groupId": "b81a6789-e93b-4be5-baa7-59f34004694a",
"group": { "default": "Property Bag Navigation" },
"title": { "default": "Property Bag Site List" },
"group": {
"default": "Property Bag Navigation"
},
"title": {
"default": "Property Bag Site List"
},
"description": {
"default": "Displays a list of sites with the selected properties"
},

View File

@ -1,20 +1,20 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneToggle, PropertyPaneChoiceGroup
} from '@microsoft/sp-webpart-base';
// import {
// BaseClientSideWebPart,
// IPropertyPaneConfiguration,
// PropertyPaneTextField,
// PropertyPaneToggle, PropertyPaneChoiceGroup
// } from '@microsoft/sp-webpart-base';
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IPropertyPaneConfiguration, PropertyPaneTextField, PropertyPaneToggle, PropertyPaneChoiceGroup } from "@microsoft/sp-property-pane";
import * as strings from 'propertyBagFilteredSiteListStrings';
import PropertyBagFilteredSiteList from './components/PropertyBagFilteredSiteList';
import { IPropertyBagFilteredSiteListProps } from './components/IPropertyBagFilteredSiteListProps';
import { IPropertyBagFilteredSiteListWebPartProps } from './IPropertyBagFilteredSiteListWebPartProps';
import utils from "../shared/utils";
export default class PropertyBagFilteredSiteListWebPart extends BaseClientSideWebPart<IPropertyBagFilteredSiteListWebPartProps> {
/**
* Renders the component.
*
@ -39,6 +39,7 @@ export default class PropertyBagFilteredSiteListWebPart extends BaseClientSideWe
showQueryText: this.properties.showQueryText
}
);
// eslint-disable-next-line @microsoft/spfx/pair-react-dom-render-unmount
ReactDom.render(element, this.domElement);
}
@ -59,7 +60,7 @@ export default class PropertyBagFilteredSiteListWebPart extends BaseClientSideWe
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
}),
})
,
PropertyPaneTextField("filters", {
label: strings.FiltersFieldLabel,

View File

@ -1,3 +1,5 @@
@import '~@fluentui/react/dist/sass/References.scss';
.helloWorld {
.container {

View File

@ -1,36 +1,16 @@
import * as React from "react";
import pnp from "sp-pnp-js";
import { SortDirection } from "sp-pnp-js";
/* eslint-disable dot-notation */
import * as _ from "lodash";
import * as React from "react";
import pnp, { SearchQuery, SearchResults } from "sp-pnp-js";
import DisplayProp from "../../shared/DisplayProp";
import { SearchQuery, SearchResults } from "sp-pnp-js";
import { css } from "office-ui-fabric-react";
//import styles from "./PropertyBagFilteredSiteList.module.scss";
import { IPropertyBagFilteredSiteListProps } from "./IPropertyBagFilteredSiteListProps";
import { CommandBar } from "office-ui-fabric-react/lib/CommandBar";
import { Label } from "office-ui-fabric-react/lib/Label";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import { Link } from "office-ui-fabric-react/lib/Link";
import { List } from "office-ui-fabric-react/lib/List";
import { Button, ButtonType } from "office-ui-fabric-react/lib/Button";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar";
import * as md from "../../shared/MessageDisplay";
import MessageDisplay, * as md from "../../shared/MessageDisplay";
import utils from "../../shared/utils";
import MessageDisplay from "../../shared/MessageDisplay";
import { CommandBar, ICommandBarProps } from "office-ui-fabric-react/lib/CommandBar";
import {
DetailsList, DetailsListLayoutMode, IColumn, IGroupedList, SelectionMode, CheckboxVisibility, IGroup
} from "office-ui-fabric-react/lib/DetailsList";
import {
GroupedList
} from "office-ui-fabric-react/lib/GroupedList";
import {
IViewport
} from "office-ui-fabric-react/lib/utilities/decorators/withViewport";
import {
Panel, PanelType
} from "office-ui-fabric-react/lib/Panel";
import { IPropertyBagFilteredSiteListProps } from "./IPropertyBagFilteredSiteListProps";
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
export interface IPropertyBagFilteredSiteListState {
errorMessages: Array<md.Message>;
sites: Array<Site>;
@ -71,8 +51,7 @@ export class AppliedUserFilter {
*/
public constructor(
public managedPropertyName: string,
public value: string)
{ }
public value: string) { }
}
export class UserFilter {
@ -91,7 +70,7 @@ export class UserFilter {
}
export default class PropertyBagFilteredSiteList extends React.Component<IPropertyBagFilteredSiteListProps, IPropertyBagFilteredSiteListState> {
public constructor(props) {
console.log(JSON.stringify("in constructor"));
super(props);
this.state = { sites: [], filteredSites: [], errorMessages: [], userFilters: [], appliedUserFilters: [] };
}
@ -103,28 +82,15 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
*
* @memberOf PropertyBagFilteredSiteList
*/
public removeMessage(messageId: string) {
_.remove(this.state.errorMessages, {
private removeMessage(messageId: string): void {
const messages = this.state.errorMessages;
_.remove(messages, {
Id: messageId
});
this.setState(this.state);
this.setState((current) => ({ ...current, errorMessages: messages }));
}
/**
* Initializes the list of user filters.
* A user filter is created for each UserFilter name specified in the props.
*
* @param {Array<string>} userFilterNames
*
* @memberOf PropertyBagFilteredSiteList
*/
public setupUserFilters(userFilterNames: Array<string>) {
console.log(JSON.stringify("in extractUserFilterValues"));
this.state.userFilters = [];
for (const userFilterName of userFilterNames) {
this.state.userFilters.push(new UserFilter(userFilterName));
}
}
/**
* Adds values to All the UserFilters for a given SearchResults.
@ -133,15 +99,17 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
*
* @memberOf PropertyBagFilteredSiteList
*/
public extractUserFilterValues(r) {
console.log(JSON.stringify("in extractUserFilterValues"));
for (const userFilter of this.state.userFilters) {
const value = r[userFilter.managedPropertyName].trim();
if (_.find(userFilter.values, v => { return v === value; })) {
// already there
}
else {
userFilter.values.push(value);
private extractUserFilterValues(userFilters: Array<UserFilter>, r): void {
for (const userFilter of userFilters) {
if (r[userFilter.managedPropertyName]) {
const value = r[userFilter.managedPropertyName].trim();
if (_.find(userFilter.values, v => { return v === value; })) {
// already there
}
else {
userFilter.values.push(value);
}
}
}
@ -157,13 +125,13 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
*
* @memberOf PropertyBagFilteredSiteList
*/
public getSites(siteTemplatesToInclude: Array<string>, filters:Array<string>, showQueryText: boolean, userFilters: Array<string>, showSiteDescriptions: boolean) {
console.log(JSON.stringify("in getSites"));
private getSites(siteTemplatesToInclude: Array<string>, filters: Array<string>, showQueryText: boolean, userFilters: Array<string>, showSiteDescriptions: boolean): void {
const userFilterNameArray = [];
if (userFilters) {
for (const userFilter of userFilters) {
userFilterNameArray.push(userFilter);
userFilterNameArray.push(userFilter);
}
}
@ -201,23 +169,30 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
};
pnp.sp.search(q).then((results: SearchResults) => {
this.state.sites = [];
const sites = [];
debugger;
this.setupUserFilters(userFilterNameArray);
const userFilters: UserFilter[] = [];
for (const userFilterName of this.props.userFilters) {
userFilters.push(new UserFilter(userFilterName));
}
// this.setupUserFilters(userFilterNameArray);
for (const r of results.PrimarySearchResults) {
const index = this.state.sites.push(new Site(r.Title, r.Description, r.SPSiteUrl));
const index = sites.push(new Site(r.Title, r.Description, r["SPSiteUrl"]));
for (const mp of this.props.userFilters) {
this.state.sites[index-1][mp] = r[mp];
sites[index - 1][mp] = r[mp];
}
this.extractUserFilterValues(r);
this.extractUserFilterValues(userFilters, r);
}
this.filterSites();
this.setState(this.state);
debugger;
const filteredSites = this.filterSites([], sites);// need to pass sites iun here and return the filtered array!!!
this.setState((current) => ({ ...current, filteredSites: filteredSites, sites: sites, userFilters: userFilters }));
}).catch(err => {
debugger;
this.state.errorMessages.push(new md.Message(err));
this.setState(this.state);
const errorMessages = this.state.errorMessages;
errorMessages.push(new md.Message(err));
this.setState((current => ({ ...current, errorMessages: errorMessages })));
});
}
/** react lifecycle */
@ -227,26 +202,14 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
*
* @memberOf PropertyBagFilteredSiteList
*/
public componentWillMount() {
console.log(JSON.stringify("in componentWillMount"));
public componentDidMount(): void {
this.getSites(this.props.siteTemplatesToInclude, this.props.filters, this.props.showQueryText, this.props.userFilters, this.props.showSiteDescriptions);
}
/**
* Called whe Properties are changed in the PropertyPane
* Gets the sites and builds the userFilters using the new Properties
*
* @param {IPropertyBagFilteredSiteListProps} nextProps
* @param {*} nextContext
*
* @memberOf PropertyBagFilteredSiteList
*/
public componentWillReceiveProps(nextProps: IPropertyBagFilteredSiteListProps, nextContext: any) {
console.log(JSON.stringify("in componentWillReceiveProps"));
this.getSites(nextProps.siteTemplatesToInclude, nextProps.filters, nextProps.showQueryText, nextProps.userFilters, nextProps.showSiteDescriptions);
}
/**
* Called by the Render method.
* Displayes the Site Description if requested in the PropertyPane.
* Displays the Site Description if requested in the PropertyPane.
* Otherwise displays an empty Div
*
* @param {Site} site
@ -254,8 +217,7 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
*
* @memberOf PropertyBagFilteredSiteList
*/
public conditionallyRenderDescription(site: Site) {
console.log(JSON.stringify("in conditionallyRenderDescription"));
private conditionallyRenderDescription(site: Site): JSX.Element {
if (this.props.showSiteDescriptions) {
return (<Label>{site.description}</Label>);
}
@ -273,25 +235,26 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
* @memberOf PropertyBagFilteredSiteList
*/
private SetupFilters(): Array<IContextualMenuItem> {
console.log(JSON.stringify("in SetupFilters"));
const items = new Array<IContextualMenuItem>();
for (const uf of this.state.userFilters) {
const item: IContextualMenuItem = {
key: uf.managedPropertyName,
name: uf.managedPropertyName,
title: uf.managedPropertyName,
href:null,
href: null,
}
item.items = [];
item.subMenuProps = { items: [] };
for (const value of uf.values) {
item.items.push({
item.subMenuProps.items.push({
key: value,
data: {
managedPropertyName: uf.managedPropertyName,
value: value
},
checked: this.AppliedFilterExists(uf.managedPropertyName, value),
checked: this.AppliedFilterExists(this.state.appliedUserFilters, uf.managedPropertyName, value),
canCheck: true,
name: value,
title: value,
onClick: this.filterOnMetadata.bind(this)
@ -310,17 +273,16 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
*
* @memberOf PropertyBagFilteredSiteList
*/
public AppliedFilterExists(managedPropertyName: string, value: string): boolean {
console.log(JSON.stringify("in AppliedFilterExists"));
const selectedFilter = _.find(this.state.appliedUserFilters, af => {
private AppliedFilterExists(appliedUserFilters: AppliedUserFilter[], managedPropertyName: string, value: string): boolean {
debugger;
const selectedFilter = _.find(appliedUserFilters, af => {
return (af.managedPropertyName === managedPropertyName && af.value === value);
});
if (selectedFilter) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
@ -330,15 +292,15 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
*
* @memberOf PropertyBagFilteredSiteList
*/
public ToggleAppliedUserFilter(item: IContextualMenuItem) {
console.log(JSON.stringify("in ToggleAppliedUserFilter"));
if (this.AppliedFilterExists(item.data.managedPropertyName, item.data.value)) {
this.state.appliedUserFilters = this.state.appliedUserFilters.filter(af => {
private ToggleAppliedUserFilter(appliedUserFilters: AppliedUserFilter[], item: IContextualMenuItem): AppliedUserFilter[] {
if (this.AppliedFilterExists(appliedUserFilters, item.data.managedPropertyName, item.data.value)) {
return appliedUserFilters.filter(af => {
return (af.managedPropertyName !== item.data.managedPropertyName || af.value !== item.data.value);
});
})
}
else {
this.state.appliedUserFilters.push(new AppliedUserFilter(item.data.managedPropertyName, item.data.value));
return [...appliedUserFilters, new AppliedUserFilter(item.data.managedPropertyName, item.data.value)]
}
}
@ -351,22 +313,23 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
*
* @memberOf PropertyBagFilteredSiteList
*/
public filterSites() {
console.log(JSON.stringify("in filterSites"));
if (this.state.appliedUserFilters.length === 0) {
this.state.filteredSites = this.state.sites;
private filterSites(appliedUserFilters: AppliedUserFilter[], sites: Site[]): Site[] {
if (appliedUserFilters.length === 0) {
return sites;
}
else {
debugger;
const filteredSites = sites.filter(site => {
this.state.filteredSites = this.state.sites.filter(site => {
debugger;
for (const auf of this.state.appliedUserFilters) {
if (site[auf.managedPropertyName] !== auf.value) {
return false;
for (const auf of appliedUserFilters) {
if (site[auf.managedPropertyName] === auf.value) {
return true;
}
}
return true;
return false;
});
return filteredSites;
}
}
/**
@ -375,47 +338,41 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
* Applies the new Filters.
* re-deiplays the list
*
* @param {React.MouseEvent<HTMLElement>} [ev]
* @param {React.MouseEvent<HTMLElement>} [_ev]
* @param {IContextualMenuItem} [item]
*
* @memberOf PropertyBagFilteredSiteList
*/
public filterOnMetadata(ev?: React.MouseEvent<HTMLElement>, item?: IContextualMenuItem) {
console.log(JSON.stringify("in filterOnMetadata"));
this.ToggleAppliedUserFilter(item);
this.filterSites();
this.setState(this.state);
}
public doNothing(ev?: React.MouseEvent<HTMLElement>, item?: IContextualMenuItem) {
console.log(JSON.stringify("in doNothing"));
ev.stopPropagation();
return false;
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
private filterOnMetadata(_ev?: React.MouseEvent<HTMLElement>, item?: IContextualMenuItem) {
const newFilters = this.ToggleAppliedUserFilter(this.state.appliedUserFilters, item);
this.setState((current) => ({ ...current, appliedUserFilters: newFilters, filteredSites: this.filterSites(newFilters, current.sites) }));
}
/**
* Renders the list of sites in this.state.filteredSites.
*
* @returns {React.ReactElement<IPropertyBagFilteredSiteListProps>}
*
* @memberOf PropertyBagFilteredSiteList
*/
* Renders the list of sites in this.state.filteredSites.
*
* @returns {React.ReactElement<IPropertyBagFilteredSiteListProps>}
*
* @memberOf PropertyBagFilteredSiteList
*/
public render(): React.ReactElement<IPropertyBagFilteredSiteListProps> {
debugger;
const listItems = this.state.filteredSites.map((site) =>
<li >
<a href={site.url} target={this.props.linkTarget}>{site.title}</a>
// eslint-disable-next-line react/jsx-key
<li>
<a href={site.url} target={this.props.linkTarget}>{site.title} --{site["AreaName"]} --{site["Continent"]} </a>
{this.conditionallyRenderDescription(site)}
</li>
);
const commandItems: Array<IContextualMenuItem> = this.SetupFilters();
console.log(JSON.stringify("commandItems follow"));
console.log(JSON.stringify(commandItems));
return (
<div >
<Label>{this.props.description}</Label>
<Label>Sites:{this.state.sites.length}</Label>
<Label>FoltererdSites:{this.state.filteredSites.length}</Label>
<CommandBar items={commandItems} />
<MessageDisplay
messages={this.state.errorMessages}
@ -433,8 +390,8 @@ export default class PropertyBagFilteredSiteList extends React.Component<IProper
);
}}
>
</List>*/}
</List>
<DetailsList items={this.state.appliedUserFilters} />*/}
</div >
);
}

View File

@ -16,7 +16,6 @@ declare interface IPropertyBagFilteredSiteListStrings {
TargetParentDescription: string;
TargetTopDescription: string;
}
declare module 'propertyBagFilteredSiteListStrings' {
const strings: IPropertyBagFilteredSiteListStrings;
export = strings;

View File

@ -1,9 +1,9 @@
/// <reference types="mocha" />
// /// <reference types="mocha" />
import { assert } from 'chai';
// import { assert } from 'chai';
describe('PropertyBagFilteredSiteListWebPart', () => {
it('should do something', () => {
assert.ok(true);
});
});
// describe('PropertyBagFilteredSiteListWebPart', () => {
// it('should do something', () => {
// assert.ok(true);
// });
// });

View File

@ -1,10 +1,14 @@
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "8634e32b-eda4-483d-8fe9-5f2075339eb8",
"alias": "PropertyBagGlobalNavWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"version": "*",
"manifestVersion": 2,
"supportedHosts": [
"SharePointWebPart"
],
"safeWithCustomScriptDisabled": false,
"preconfiguredEntries": [
{
"groupId": "8634e32b-eda4-483d-8fe9-5f2075339eb8",

View File

@ -1,11 +1,8 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IPropertyPaneConfiguration, PropertyPaneTextField } from "@microsoft/sp-property-pane";
import utils from "../shared/utils";
import * as strings from 'propertyBagGlobalNavStrings';
import PropertyBagGlobalNav from './components/PropertyBagGlobalNav';
@ -19,12 +16,13 @@ export default class PropertyBagGlobalNavWebPart extends BaseClientSideWebPart<I
PropertyBagGlobalNav,
{
description: this.properties.description,
managedProperties: utils.parseMultilineTextToArray( this.properties.managedProperties),
managedProperties: utils.parseMultilineTextToArray(this.properties.managedProperties),
siteTemplatesToInclude: utils.parseMultilineTextToArray(this.properties.siteTemplatesToInclude),
filters: utils.parseMultilineTextToArray(this.properties.filters),
}
);
// eslint-disable-next-line @microsoft/spfx/pair-react-dom-render-unmount
ReactDom.render(element, this.domElement);
}

View File

@ -1,6 +1,5 @@
export interface IPropertyBagGlobalNavProps {
description: string;
siteTemplatesToInclude: Array<string>; //STS#1 STS#2 leave off the #1 to get all STS
filters: Array<string>; // managedPropertyname=valiust separated by \n (new line)
managedProperties: Array<string>;// managed properties to build the menu from.

View File

@ -1,3 +1,5 @@
@import '~@fluentui/react/dist/sass/References.scss';
.helloWorld {
.container {
max-width: 700px;
@ -29,7 +31,7 @@
// Basic Button
outline: transparent;
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;
font-size: 14px;
font-weight: 400;

View File

@ -1,30 +1,12 @@
import * as React from 'react';
import { IPropertyBagGlobalNavProps } from './IPropertyBagGlobalNavProps';
import pnp from "sp-pnp-js";
import { SortDirection } from "sp-pnp-js";
import * as _ from "lodash";
import { SearchQuery, SearchResults } from "sp-pnp-js";
import { css } from "office-ui-fabric-react";
import * as React from 'react';
import pnp, { SearchQuery, SearchResults } from "sp-pnp-js";
import { IPropertyBagGlobalNavProps } from './IPropertyBagGlobalNavProps';
import { Label } from "office-ui-fabric-react/lib/Label";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import { Link } from "office-ui-fabric-react/lib/Link";
import { List } from "office-ui-fabric-react/lib/List";
import { Button, ButtonType } from "office-ui-fabric-react/lib/Button";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar";
import { CommandBar } from "office-ui-fabric-react/lib/CommandBar";
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
import * as md from "../../shared/MessageDisplay";
import utils from "../../shared/utils";
import { CommandBar, ICommandBarProps } from "office-ui-fabric-react/lib/CommandBar";
import {
DetailsList, DetailsListLayoutMode, IColumn, IGroupedList, SelectionMode, CheckboxVisibility, IGroup
} from "office-ui-fabric-react/lib/DetailsList";
import {
GroupedList
} from "office-ui-fabric-react/lib/GroupedList";
import {
IViewport
} from "office-ui-fabric-react/lib/utilities/decorators/withViewport";
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
export class PropertyBagGlobalNavState {
public menuitems: Array<IContextualMenuItem>; // The menuItems to display
public errorMessages: Array<md.Message>;// any error messages
@ -43,28 +25,30 @@ export default class PropertyBagGlobalNav extends React.Component<IPropertyBagGl
*
* @memberOf PropertyBagGlobalNav
*/
public addMenuItem(r: any): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private addMenuItem(items: Array<IContextualMenuItem>, r: any): Array<IContextualMenuItem> {
let currentItem: IContextualMenuItem;
let currentSet: Array<IContextualMenuItem> = this.state.menuitems;
debugger;
let currentSet: Array<IContextualMenuItem> = items;
for (const managedProperty of this.props.managedProperties) {
if (r[managedProperty]) {// if site does not have this property set
const value = r[managedProperty].trim();
currentItem = _.find(currentSet, i => { return i.key === value; });
if (!currentItem) {
const idx = currentSet.push({ key: value, name: value, items: [] });
const idx = currentSet.push({ key: value, name: value, subMenuProps: { items: [] } });
currentItem = currentSet[idx - 1];
}
currentSet = currentItem.items;
currentSet = currentItem.subMenuProps.items;
}
}
if (currentItem) { // should have it if site does have this property set
currentItem.items.push({
key: r['Title'],
name: r['Title'],
href: r['SPSiteUrl']
currentItem.subMenuProps.items.push({
key: r.Title,
name: r.Title,
href: r.SPSiteUrl
});
}
return items;
}
/**
* Gets the list of sites to be displayed in the Menu using the filters specified in
@ -76,7 +60,7 @@ export default class PropertyBagGlobalNav extends React.Component<IPropertyBagGl
*
* @memberOf PropertyBagGlobalNav
*/
public getSites(siteTemplatesToInclude: Array<string>, filters: Array<string>, managedProperties: Array<string>) {
private getSites(siteTemplatesToInclude: Array<string>, filters: Array<string>, managedProperties: Array<string>): void {
let querytext = "contentclass:STS_Site ";
if (siteTemplatesToInclude) {
@ -107,27 +91,32 @@ export default class PropertyBagGlobalNav extends React.Component<IPropertyBagGl
};
pnp.sp.search(q).then((results: SearchResults) => {
this.state.menuitems = [];
const menuitems = [];
for (const r of results.PrimarySearchResults) {
this.addMenuItem(r);
this.addMenuItem(menuitems, r);
}
debugger;
this.setState((current) => ({ ...current, menuitems: menuitems }));
this.setState(this.state);
}).catch(err => {
debugger;
this.state.errorMessages.push(new md.Message(err));
this.setState(this.state);
const em = this.state.errorMessages;
em.push(new md.Message(err));
this.setState(current => ({ ...current, errorMessages: em }));
});
}
/** react lifecycle */
public componentWillMount() {
public componentDidMount(): void {
this.getSites(this.props.siteTemplatesToInclude, this.props.filters, this.props.managedProperties);
}
public componentWillReceiveProps(nextProps: IPropertyBagGlobalNavProps, nextContext: any) {
// public componentDidUpdate(nextProps: IPropertyBagGlobalNavProps, nextContext: any): void {
this.getSites(nextProps.siteTemplatesToInclude, nextProps.filters, nextProps.managedProperties);
}
// this.getSites(nextProps.siteTemplatesToInclude, nextProps.filters, nextProps.managedProperties);
// }
public render(): React.ReactElement<IPropertyBagGlobalNavProps> {
return (
<CommandBar items={this.state.menuitems} />

View File

@ -9,7 +9,6 @@ declare interface IPropertyBagGlobalNavStrings {
ManagedPropertiesFieldLabel: string;
ManagedPropertiesFieldDescription: string;
}
declare module 'propertyBagGlobalNavStrings' {
const strings: IPropertyBagGlobalNavStrings;
export = strings;

View File

@ -1,9 +1,9 @@
/// <reference types="mocha" />
// /// <reference types="mocha" />
import { assert } from 'chai';
// import { assert } from 'chai';
describe('PropertyBagGlobalNavWebPart', () => {
it('should do something', () => {
assert.ok(true);
});
});
// describe('PropertyBagGlobalNavWebPart', () => {
// it('should do something', () => {
// assert.ok(true);
// });
// });

View File

@ -10,8 +10,8 @@ import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBa
* @class Message
*/
export class Message {
public Id: string;
public text: string;
public Id: string;
public text: string;
public constructor(msg: string) {
this.text = msg;
this.Id = Guid.newGuid().toString();
@ -29,6 +29,7 @@ export interface IMessageDisplayProps {
* @class MessageDisplay
* @extends {React.Component<IMessageDisplayProps, any>}
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default class MessageDisplay extends React.Component<IMessageDisplayProps, any> {
/**
*
@ -36,16 +37,19 @@ export default class MessageDisplay extends React.Component<IMessageDisplayProps
*
* @memberOf MessageDisplay
*/
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
public createDismissHandler = (messageId) => (vale) => {
this.props.hideMessage(messageId);
this.props.hideMessage(messageId);
}
public render(): React.ReactElement<IMessageDisplayProps> {
return (
return (
<div>
{this.props.messages.map((message, y, z) => {
return (
<MessageBar
messageBarType={MessageBarType.remove}
key={message.Id}
messageBarType={MessageBarType.error}
isMultiline={true}
onDismiss={this.createDismissHandler(message.Id)}>
{message.text}

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as _ from "lodash";
import { Web } from "sp-pnp-js";
require("sp-init");
@ -7,7 +8,7 @@ require("sharepoint");
import DisplayProp from "./DisplayProp";
/**
* Various utilitty functions used by the React-ProprtyBag* Webparts
* Various utility functions used by the React-PropertyBag* Web parts
*
* @export
* @class utils
@ -26,13 +27,13 @@ export default class utils {
*
* @memberOf utils
*/
public static EncodePropertyKey(propKey) {
var bytes = [];
for (var i = 0; i < propKey.length; ++i) {
public static EncodePropertyKey(propKey): string {
const bytes = [];
for (let i = 0; i < propKey.length; ++i) {
bytes.push(propKey.charCodeAt(i));
bytes.push(0);
}
var b64encoded = window.btoa(String.fromCharCode.apply(null, bytes));
const b64encoded = window.btoa(String.fromCharCode.apply(null, bytes));
return b64encoded;
}
@ -46,7 +47,7 @@ export default class utils {
*
* @memberOf utils
*/
public static DecodePropertyKey(propKey) {
public static DecodePropertyKey(propKey): string {
const encoded = window.atob(propKey);
let decoded = "";
for (let x = 0; x < encoded.length; x = x + 2) {
@ -74,9 +75,9 @@ export default class utils {
return searchableprops;
}
/**
* AllProperties- the resullsts from web.select("Title", "AllProperties").expand("AllProperties").get()
* propertiesToSelect- The properties you waant to select out of AllProperties
* searchableProperties-- and araay of properties which are known to be searchjable
* AllProperties- the results from web.select("Title", "AllProperties").expand("AllProperties").get()
* propertiesToSelect- The properties you want to select out of AllProperties
* searchableProperties-- and array of properties which are known to be searchable
*
*/
/**
@ -85,7 +86,7 @@ export default class utils {
* @static
* @param {*} AllProperties
* @param {Array<string>} propertiesToSelect The Properties to Select from AllProperties
* @param {Array<string>} searchableProperties An Array of Searchable Properties. These will be marked as seartchable in the results
* @param {Array<string>} searchableProperties An Array of Searchable Properties. These will be marked as searchable in the results
* @param {boolean} [addMissingProps] Indicates if the method should add a empty property if it is in propertiesToSelect but not in AllProperties
* @returns {Array<DisplayProp>}
*
@ -122,7 +123,7 @@ export default class utils {
*
* @memberOf utils
*/
public static setSPProperty(name: string, value: string, siteUrl: string) {
public static setSPProperty(name: string, value: string, siteUrl: string): Promise<any> {
return new Promise((resolve, reject) => {
let webProps;
const clientContext = new SP.ClientContext(siteUrl);
@ -134,7 +135,7 @@ export default class utils {
clientContext.load(web);
clientContext.load(webProps);
clientContext.executeQueryAsync(
(sender, args) => { resolve(); },
(sender, args) => { resolve(webProps); },
(sender, args) => { reject(args.get_message()); }
);
@ -153,7 +154,7 @@ export default class utils {
public static saveSearchablePropertiesToSharePoint(siteUrl: string, propnames: Array<string>): Promise<any> {
const encodedPropNames: Array<string> = [];
for (const propname of propnames) {
if (propname != "") {
if (propname !== "") {
encodedPropNames.push(this.EncodePropertyKey(propname));
}
}
@ -169,14 +170,18 @@ export default class utils {
*
* @memberOf utils
*/
public static forceCrawl(siteUrl: string): Promise<any> {
public static forceCrawl(siteUrl: string): Promise<void> {
const web = new Web(siteUrl);
return web.select("Title", "AllProperties").expand("AllProperties").get().then(r => {
let version: number = r.AllProperties["vti_x005f_searchversion"];
//let version: number = r.AllProperties["vti_x005f_searchversion"];
let version: number = r.AllProperties.vti_x005f_searchversion;
if (version) {
version++;
this.setSPProperty("AllProperties", version.toString(), siteUrl);
return this.setSPProperty("vti_searchversion", version.toString(), siteUrl);
}
else {
return this.setSPProperty("vti_searchversion", "1", siteUrl);
}
});
}
@ -251,6 +256,6 @@ export default class utils {
if (!value) {
return [];
}
return value.split('\n').filter(val => { return val.trim() != ""; });
return value.split('\n').filter(val => { return val.trim() !== ""; });
}
}

View File

@ -1,13 +1,35 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.5/includes/tsconfig-web.json",
"compilerOptions": {
"skipLibCheck": true,
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": true,
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"noImplicitAny": false,
"experimentalDecorators": true,
"types": [
"webpack-env"
"webpack-env",
"microsoft-ajax",
"sharepoint"
],
"lib": [
"es2015",
"dom"
],
"outDir": "lib",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
]
}
},
"exclude": [
"node_modules"
],
}

View File

@ -1,3 +0,0 @@
{
"rulesDirectory": "./config"
}

View File

@ -1,5 +0,0 @@
// Type definitions for Microsoft ODSP projects
// Project: ODSP
/* Global definition for UNIT_TEST builds */
declare const UNIT_TEST: boolean;

View File

@ -1,4 +0,0 @@
/// <reference path="@ms/odsp.d.ts" />
/// <reference path="assertion-error/assertion-error.d.ts" />
/// <reference path="knockout/knockout.d.ts" />
/// <referehce path="SP/SP.d.ts />