Merge pull request #4679 from techienickb/react-pages-hieracrchy-spfx1.18.2-update

This commit is contained in:
Hugo Bernier 2024-01-20 09:33:49 -08:00 committed by GitHub
commit d6b9df3d40
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
32 changed files with 26175 additions and 20661 deletions

View File

@ -1,7 +1,7 @@
// 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.14.0",
"image": "docker.io/m365pnp/spfx:1.14.0",
"name": "SPFx 1.18.2",
"image": "docker.io/m365pnp/spfx:1.18.2",
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.

View File

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

View File

@ -35,3 +35,5 @@ release# .CER Certificates
*.cer
# .PEM Certificates
*.pem
#heft
.heft

View File

@ -0,0 +1 @@
v18.18.0

View File

@ -2,11 +2,16 @@
"@microsoft/generator-sharepoint": {
"isCreatingSolution": true,
"environment": "spo",
"version": "1.14.0",
"version": "1.18.2",
"libraryName": "react-pages-hierarchy",
"libraryId": "89758fb6-85e2-4e2b-ac88-4f4e7e5f60cb",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart"
"componentType": "webpart",
"sdkVersions": {
"@microsoft/teams-js": "2.12.0",
"@microsoft/microsoft-graph-client": "3.0.2"
},
"nodeVersion": "18.19.0"
}
}

View File

@ -15,8 +15,8 @@ This web part allows users to create a faux page hierarchy in their pages librar
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
![SPFx 1.14](https://img.shields.io/badge/SPFx-1.14.0-green.svg)
![Node.js v14](https://img.shields.io/badge/Node.js-v14-green.svg)
![SPFx 1.18.2](https://img.shields.io/badge/SPFx-1.18.2.0-green.svg)
![Node.js v18](https://img.shields.io/badge/Node.js-v18-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg)
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
@ -50,7 +50,8 @@ Version|Date|Comments
1.3|March 31, 2022|Added a Tree View
1.4|July 29, 2022|Updated Tree View Functionality
1.5|March 29, 2023|Added support for non-English SitePages library paths
1.6|May 11, Uses treeFrom/expandTo web part properties
1.6|May 11,2023|Uses treeFrom/expandTo web part properties
1.7|January 08|Updated to SPFX 1.18.2 + Node 18
## Minimal path to awesome

View File

@ -9,7 +9,7 @@
"This web part allows users to create a faux page hierarchy in their pages library and use it for page-to-page navigation."
],
"creationDateTime": "2020-04-30",
"updateDateTime": "2023-05-11",
"updateDateTime": "2024-01-11",
"products": [
"SharePoint"
],
@ -20,7 +20,7 @@
},
{
"key": "SPFX-VERSION",
"value": "1.14.0"
"value": "1.18.2"
},
{
"key": "SPFX-SUPPORTSTHEMEVARIANTS",

View File

@ -4,7 +4,7 @@
"name": "react-pages-hierarchy",
"id": "89758fb6-85e2-4e2b-ac88-4f4e7e5f60cb",
"title": "Pages Hierarchy",
"version": "1.0.3.2",
"version": "1.0.7.0",
"includeClientSideAssets": true,
"isDomainIsolated": false,
"developer": {
@ -12,7 +12,7 @@
"privacyUrl": "",
"termsOfUseUrl": "",
"websiteUrl": "https://github.com/bogeorge",
"mpnId": "Undefined-1.14.0"
"mpnId": "Undefined-1.18.2"
},
"metadata": {
"shortDescription": {

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -3,40 +3,45 @@
"version": "1.0.2",
"private": true,
"main": "lib/index.js",
"engines": {
"node": ">=16.13.0 <17.0.0 || >=18.17.1 <19.0.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/rush-stack-compiler-4.2": "^0.1.2",
"@microsoft/sp-core-library": "1.14.0",
"@microsoft/sp-lodash-subset": "1.14.0",
"@microsoft/sp-office-ui-fabric-core": "1.14.0",
"@microsoft/sp-property-pane": "1.14.0",
"@microsoft/sp-webpart-base": "1.14.0",
"@pnp/sp": "^3.1.0",
"@pnp/spfx-controls-react": "^3.7.2",
"@pnp/spfx-property-controls": "^3.6.0",
"office-ui-fabric-react": "7.174.1",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-resize-detector": "^4.2.1"
},
"resolutions": {
"@types/react": "16.8.8"
"@pnp/sp": "^3.21.0",
"@pnp/spfx-controls-react": "^3.16.1",
"@pnp/spfx-property-controls": "^3.15.1",
"@fluentui/react": "8.85.1",
"@microsoft/sp-component-base": "1.18.2",
"@microsoft/sp-core-library": "1.18.2",
"@microsoft/sp-lodash-subset": "1.18.2",
"@microsoft/sp-office-ui-fabric-core": "1.18.2",
"@microsoft/sp-property-pane": "1.18.2",
"@microsoft/sp-webpart-base": "1.18.2",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-resize-detector": "^9.1.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/sp-build-web": "1.18.0",
"@microsoft/sp-module-interfaces": "1.14.0",
"@microsoft/sp-tslint-rules": "1.14.0",
"@microsoft/sp-webpart-workbench": "^1.12.1",
"@types/es6-promise": "0.0.33",
"@types/react": "16.9.51",
"@types/react-dom": "16.9.8",
"@types/webpack-env": "^1.16.3",
"ajv": "~5.2.2",
"gulp": "^4.0.2",
"run-sequence": "^2.2.1"
"@microsoft/eslint-config-spfx": "1.18.2",
"@microsoft/eslint-plugin-spfx": "1.18.2",
"@microsoft/rush-stack-compiler-4.7": "0.1.0",
"@microsoft/sp-build-web": "1.18.2",
"@microsoft/sp-module-interfaces": "1.18.2",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"run-sequence": "^2.2.1",
"ajv": "^6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.7.4"
}
}

View File

@ -5,7 +5,7 @@ import { Action } from "./action";
import { GetRequest } from './getRequest';
import { IPage } from '@src/models/IPage';
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { INavLink } from 'office-ui-fabric-react';
import { INavLink } from '@fluentui/react';
// state that we track
interface PagesState {
@ -13,7 +13,7 @@ interface PagesState {
userCanManagePages: boolean;
ancestorPages: IPage[];
childrenPages: IPage[];
tree: INavLink | null;
tree?: INavLink;
getRequest: GetRequest;
}
@ -54,7 +54,8 @@ function pagesReducer(state: PagesState, action: Action): PagesState {
case ActionTypes.GET_PAGES_LOADING:
return { ...state, getRequest: { isLoading: true, hasError: false, errorMessage: "" } };
case ActionTypes.GET_PAGES:
var arrayAction: PageTreePayloadAction = action as PageTreePayloadAction;
// eslint-disable-next-line no-case-declarations
const arrayAction: PageTreePayloadAction = action as PageTreePayloadAction;
return {
...state,
childrenPages: arrayAction.payload.childgrenPages,
@ -72,16 +73,14 @@ function pagesReducer(state: PagesState, action: Action): PagesState {
}
};
case ActionTypes.PARENT_PAGE_COLUMN_EXISTS:
var parentPageColumnExistAction: ParentPageColumnExistAction = action as ParentPageColumnExistAction;
return {
...state,
parentPageColumnExists: parentPageColumnExistAction.payload
parentPageColumnExists: (action as ParentPageColumnExistAction).payload
};
case ActionTypes.CAN_USER_MANAGE_PAGES:
var canUserManagePagesAction: CanUserManagePagesAction = action as CanUserManagePagesAction;
return {
...state,
userCanManagePages: canUserManagePagesAction.payload
userCanManagePages: (action as CanUserManagePagesAction).payload
};
default:
throw new Error();
@ -92,7 +91,9 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
const [pagesState, pagesDispatch] = useReducer(pagesReducer, {
parentPageColumnExists: true,
userCanManagePages: false,
// eslint-disable-next-line no-empty-pattern
ancestorPages: [] = [],
// eslint-disable-next-line no-empty-pattern
childrenPages: [] = [],
getRequest: { isLoading: false, hasError: false, errorMessage: "" },
tree: null
@ -106,13 +107,13 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
LogHelper.verbose('usePageApi', 'useEffect', `[currentPageId, ${currentPageId}, pageEditFinished: ${pageEditFinished} ]`);
if (currentPageId && !!spLibGuid) {
checkIfParentPageExists();
getPagesAsync();
checkIfParentPageExists().catch(console.error);
getPagesAsync().catch(console.error);
}
}, [currentPageId, pageEditFinished, spLibGuid]);
async function getSitePagesLibraryGuid() {
async function getSitePagesLibraryGuid(): Promise<void> {
LogHelper.verbose('usePageApi', 'getSitePagesLibrary', ``);
const lib = await sp.web.lists.ensureSitePagesLibrary();
@ -120,7 +121,7 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
await setSpLibGuid(libData.Id);
}
async function getPagesAsync() {
async function getPagesAsync(): Promise<void> {
LogHelper.verbose('usePageApi', 'getPagesAsync', ``);
// check local storage first and return these and then refresh it in the background
@ -129,8 +130,8 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
pagesDispatch({ type: ActionTypes.GET_PAGES_LOADING });
// add select and order by later. Order by ID?
let pages: IPage[] = [];
let items = await sp.web.lists.getById(spLibGuid).items
const pages: IPage[] = [];
const items = await sp.web.lists.getById(spLibGuid).items
.select(
PageFields.ID,
PageFields.TITLE,
@ -150,7 +151,7 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
});
if (items) {
for (let item of items) {
for (const item of items) {
pages.push(mapPage(item));
}
}
@ -166,10 +167,10 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
} as PageTreePayloadAction);
}
async function checkIfParentPageExists() {
async function checkIfParentPageExists(): Promise<void> {
LogHelper.verbose('usePageApi', 'parentPageExists', ``);
let parentPage = await sp.web.lists.getById(spLibGuid).fields
const parentPage = await sp.web.lists.getById(spLibGuid).fields
.getByInternalNameOrTitle(PageFields.PARENTPAGELOOKUP)()
.catch(e => {
// swallow the exception we'll handle below
@ -180,14 +181,14 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
pagesDispatch({ type: ActionTypes.PARENT_PAGE_COLUMN_EXISTS, payload: true } as ParentPageColumnExistAction);
}
else {
canCurrentUserManageSitePages();
canCurrentUserManageSitePages().catch(console.error);
// dispatch the action
pagesDispatch({ type: ActionTypes.PARENT_PAGE_COLUMN_EXISTS, payload: false } as ParentPageColumnExistAction);
}
}
async function canCurrentUserManageSitePages(): Promise<void> {
let canManagePages = await sp.web.lists.getById(spLibGuid)
const canManagePages = await sp.web.lists.getById(spLibGuid)
.currentUserHasPermissions(PermissionKind.ManageLists)
.catch(e => {
ErrorHelper.handleHttpError('canUserUpdateSitePages', e);
@ -201,9 +202,9 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
async function addParentPageFieldToSitePages(): Promise<void> {
LogHelper.verbose('usePageApi', 'addParentPageFieldToSitePages', ``);
let list = await sp.web.lists.getById(spLibGuid)();
const list = await sp.web.lists.getById(spLibGuid)();
let lookup = sp.web.lists.getById(spLibGuid).fields
const lookup = sp.web.lists.getById(spLibGuid).fields
.addLookup(PageFields.PARENTPAGELOOKUP, { LookupListId: list.Id, LookupFieldName: PageFields.TITLE })
.catch(e => {
return null;
@ -224,8 +225,9 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
}
// map a SharePoint List Item to an IPage
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function mapPage(item: any): IPage {
let page: IPage = {
const page: IPage = {
id: item.ID,
title: item.Title,
etag: item['odata.etag'] ? item['odata.etag'] : new Date().toISOString(),
@ -264,9 +266,9 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
function buildHierarchy(allPages: IPage[], pageId: number): INavLink {
function recurse(id: number, l: number, ancestorPages: IPage[]): INavLink {
var item: IPage = allPages.filter(i => i.id === id)[0];
const item: IPage = allPages.filter(i => i.id === id)[0];
var links: INavLink[] = [];
let links: INavLink[] = [];
links = links.concat(allPages.filter(i => i.parentPageId === id).map(it => recurse(it.id, l ? l + 1 : l, ancestorPages)));
return { name: item.title, url: item.url, key: item.id.toString(), links: links, isExpanded: treeExpandTo ? (treeExpandTo >= l) : (ancestorPages.find(f => f.id === id) ? true : false) };
@ -277,12 +279,12 @@ export function usePageApi(currentPageId: number, pageEditFinished: boolean, con
return recurse(treeTop ? treeTop : ancestorPages[0].id, treeExpandTo ? 1 : treeExpandTo, ancestorPages);
}
const addParentPageField = () => {
addParentPageFieldToSitePages();
const addParentPageField = (): void => {
addParentPageFieldToSitePages().catch(console.error);
};
useEffect(() => {
getSitePagesLibraryGuid();
getSitePagesLibraryGuid().catch(console.error);
}, []);
return {

View File

@ -39,13 +39,14 @@ export class FilterParser {
substringof: /^substringof[(](.*),(.*)[)]/
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public parse(filterString: string): any {
// LoggingService.getLogger(this.constructor.name).info(`parse - filter=[${filterString}]`);
if (!filterString || filterString === '') {
return null;
}
let filter = filterString.trim();
const filter = filterString.trim();
let obj = {};
if (filter.length > 0) {
obj = this.parseFragment(filter);
@ -53,18 +54,19 @@ export class FilterParser {
return obj;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private parseFragment(filter): any {
// LoggingService.getLogger(this.constructor.name).info(`parseFragment - filter=[${filter}]`);
let found: boolean = false;
let obj: Predicate = new Predicate();
// tslint:disable-next-line:forin
for (let key in this.REGEX) {
let regex = this.REGEX[key];
// eslint-disable-next-line guard-for-in
for (const key in this.REGEX) {
const regex = this.REGEX[key];
if (found) {
break;
}
let match = filter.match(regex);
const match = filter.match(regex);
if (match) {
switch (regex) {
case this.REGEX.parenthesis:
@ -84,15 +86,16 @@ export class FilterParser {
break;
case this.REGEX.lookupop:
case this.REGEX.op:
let property = match[1].split('/');
// eslint-disable-next-line no-case-declarations
const property = match[1].split('/');
obj = {
property: property,
operator: match[2],
value: (match[3].indexOf('\'') === -1) ? +match[3] : match[3]
};
if (typeof obj.value === 'string') {
let quoted = obj.value.match(/^'(.*)'$/);
let m = obj.value.match(/^datetimeoffset'(.*)'$/);
const quoted = obj.value.match(/^'(.*)'$/);
const m = obj.value.match(/^datetimeoffset'(.*)'$/);
if (quoted && quoted.length > 1) {
obj.value = quoted[1];
} else if (m && m.length > 1) {
@ -124,7 +127,7 @@ export class FilterParser {
}
private buildLike(match, key): Predicate {
let right = (key === 'startsWith') ? match[2] + '*' : (key === 'endsWith') ? '*' + match[2] : '*' + match[2] + '*';
const right = (key === 'startsWith') ? match[2] + '*' : (key === 'endsWith') ? '*' + match[2] : '*' + match[2] + '*';
return {
property: match[1],
operator: FilterParser.Operators.LIKE,

View File

@ -6,6 +6,7 @@ export class PagesList implements BaseList {
public lookups = [
{ itemProperty: PageFields.PARENTPAGELOOKUP, itemKey: PageFields.PARENTPAGELOOKUPID, lookupListTitle: ListTitles.SITEPAGES },
];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public items: any[] = [
{
ID: 1,

View File

@ -8,6 +8,7 @@ import { BaseList } from '../mocklistfactory';
*/
export class UsersInformationList implements BaseList {
public listTitle = ListTitles.USERS_INFORMATION;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public items: any[] = [
{
ID: 1,

View File

@ -7,13 +7,14 @@ export class MockListFactory {
new UsersInformationList()
];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public getListItems(listTitle: string): any[] {
listTitle = decodeURI(listTitle);
LogHelper.verbose(this.constructor.name, 'getListItems', listTitle);
let items = this.getItemsForMockList(listTitle);
let list = this.listMap.filter(l => l.listTitle === listTitle)[0];
const list = this.listMap.filter(l => l.listTitle === listTitle)[0];
if (list) {
items = this.getStoredItems(list.listTitle, list.items);
@ -23,10 +24,10 @@ export class MockListFactory {
}
if (list && list.lookups !== undefined) {
for (let lookup of list.lookups) {
let lookupListItems = this.getItemsForMockList(lookup.lookupListTitle);
for (const lookup of list.lookups) {
const lookupListItems = this.getItemsForMockList(lookup.lookupListTitle);
for (let item of items) {
for (const item of items) {
if (lookup.isMulti !== true) {
item[lookup.itemProperty] = this.getLookup(item, lookup.itemKey, lookupListItems);
}
@ -40,31 +41,35 @@ export class MockListFactory {
return items;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public saveListItems(listTitle: string, items: any[]): void {
LogHelper.verbose(this.constructor.name, 'saveListItems', listTitle);
let storageKey = listTitle.split(' ').join('');
const storageKey = listTitle.split(' ').join('');
this.storeItems(storageKey, items);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getItemsForMockList(listTitle: string): any[] {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let items: any[] = [];
let list = this.listMap.filter(l => l.listTitle === listTitle)[0];
const list = this.listMap.filter(l => l.listTitle === listTitle)[0];
if (list != null) {
if (list !== null) {
items = this.getStoredItems(list.listTitle, list.items);
}
return items;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getStoredItems(listTitle: string, defaultItems: any[]): any[] {
let storageKey = listTitle.split(' ').join('');
const storageKey = listTitle.split(' ').join('');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let items: any[] = [];
let storedData: string | null;
storedData = localStorage.getItem(storageKey);
const storedData: string | null = localStorage.getItem(storageKey);
if (storedData !== null) {
items = JSON.parse(storedData);
}
@ -75,11 +80,13 @@ export class MockListFactory {
return items;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private storeItems(storageKey: string, items: any[]): void {
let storedData = JSON.stringify(items);
const storedData = JSON.stringify(items);
localStorage.setItem(storageKey, storedData);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getLookup(item: any, lookupIdProperty: string, lookupListItems: any[]): any {
if (item[lookupIdProperty] !== undefined) {
return lookupListItems.filter(i => i.ID === item[lookupIdProperty])[0];
@ -89,11 +96,13 @@ export class MockListFactory {
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getMultiLookup(item: any, lookupIdProperty: string, lookupListItems: any[]): any {
if (item[lookupIdProperty] !== undefined && item[lookupIdProperty].results !== undefined && item[lookupIdProperty].results instanceof Array) {
let results: any[] = [];
for (let id of item[lookupIdProperty].results) {
let lookupItem = lookupListItems.filter(i => i.ID === id)[0];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const results: any[] = [];
for (const id of item[lookupIdProperty].results) {
const lookupItem = lookupListItems.filter(i => i.ID === id)[0];
if (lookupItem) {
results.push(lookupItem);
}
@ -108,6 +117,7 @@ export class MockListFactory {
export interface BaseList {
listTitle: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
items: any[];
lookups?: Lookup[];
}

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { IItemUpdateResult } from '@pnp/sp/presets/all';
import { IContextInfo } from '@pnp/sp/context-info';
import { IFetchOptions } from '@pnp/common';
@ -20,62 +21,62 @@ export class MockResponse {
this.listTitle = this.getListTitleFromUrl(url);
this.currentUser = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION)[0];
if (options.method!.toUpperCase() === 'GET' && url.toLowerCase().indexOf('_api/web/currentuser') !== -1) {
if (options.method?.toUpperCase() === 'GET' && url.toLowerCase().indexOf('_api/web/currentuser') !== -1) {
response = this.getCurrentUser(url);
}
else if (options!.method!.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/_api/web/siteusers(@v)?') !== -1) {
else if (options?.method?.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/_api/web/siteusers(@v)?') !== -1) {
response = this.getSiteUser(url);
}
else if (options!.method!.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/_api/web/siteusers/getbyid') !== -1) {
else if (options?.method?.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/_api/web/siteusers/getbyid') !== -1) {
response = this.getSiteUserById(url);
}
else if (options!.method!.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/_api/web/siteusers/getbyemail') !== -1) {
else if (options?.method?.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/_api/web/siteusers/getbyemail') !== -1) {
response = this.getSiteUserByEmail(url);
}
else if (options!.method!.toUpperCase() === 'GET' && this.endsWith(url, '/_api/web')) {
else if (options?.method?.toUpperCase() === 'GET' && this.endsWith(url, '/_api/web')) {
response = this.getWeb(url);
}
else if (options!.method!.toUpperCase() === 'GET' && this.endsWith(url, '/attachmentfiles')) {
else if (options?.method?.toUpperCase() === 'GET' && this.endsWith(url, '/attachmentfiles')) {
response = this.getAttachments(url);
}
else if (options!.method!.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/_api/web/getfilebyserverrelativeurl') !== -1) {
else if (options?.method?.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/_api/web/getfilebyserverrelativeurl') !== -1) {
response = await this.getFileByServerRelativeUrl(url);
}
else if (options!.method!.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/items') === -1) {
else if (options?.method?.toUpperCase() === 'GET' && url.toLowerCase().indexOf('/items') === -1) {
response = this.getListProperties(url);
}
else if (options!.method!.toUpperCase() === 'GET') {
else if (options?.method?.toUpperCase() === 'GET') {
response = this.getListItems(url);
}
else if (options!.method!.toUpperCase() === 'POST' && this.endsWith(url, '_api/contextinfo')) {
else if (options?.method?.toUpperCase() === 'POST' && this.endsWith(url, '_api/contextinfo')) {
response = this.getContextInfo();
}
else if (options!.method!.toUpperCase() === 'POST' && this.endsWith(url, '_api/$batch')) {
else if (options?.method?.toUpperCase() === 'POST' && this.endsWith(url, '_api/$batch')) {
response = await this.processBatch(url, options);
}
else if (options!.method!.toLocaleUpperCase() === 'POST' && this.endsWith(url, '/_api/sp.utilities.utility.searchprincipalsusingcontextweb')) {
else if (options?.method?.toLocaleUpperCase() === 'POST' && this.endsWith(url, '/_api/sp.utilities.utility.searchprincipalsusingcontextweb')) {
response = this.searchPrincipals(url, options);
}
else if (options!.method!.toLocaleUpperCase() === 'POST' && this.endsWith(url, '/_api/sp.ui.applicationpages.clientpeoplepickerwebserviceinterface.clientpeoplepickersearchuser')) {
else if (options?.method?.toLocaleUpperCase() === 'POST' && this.endsWith(url, '/_api/sp.ui.applicationpages.clientpeoplepickerwebserviceinterface.clientpeoplepickersearchuser')) {
response = this.clientPeoplePickerSearchUser(url, options);
}
else if (options!.method!.toLocaleUpperCase() === 'POST' && this.endsWith(url, '/_api/sp.utilities.utility.sendemail')) {
else if (options?.method?.toLocaleUpperCase() === 'POST' && this.endsWith(url, '/_api/sp.utilities.utility.sendemail')) {
response = this.sendEmail(url, options);
}
else if (options!.method!.toUpperCase() === 'POST' && this.endsWith(url, '_api/web/ensureuser')) {
else if (options?.method?.toUpperCase() === 'POST' && this.endsWith(url, '_api/web/ensureuser')) {
response = this.ensureUser(url, options);
}
else if (options!.method!.toUpperCase() === 'POST' && url.toLowerCase().indexOf('/attachmentfiles') !== -1) {
else if (options?.method?.toUpperCase() === 'POST' && url.toLowerCase().indexOf('/attachmentfiles') !== -1) {
// add, updates and deletes
response = this.saveAttachmentChanges(url, options);
}
else if (options!.method!.toUpperCase() === 'POST' && url.toLowerCase().indexOf('_api/web/sitegroups/') !== -1) {
else if (options?.method?.toUpperCase() === 'POST' && url.toLowerCase().indexOf('_api/web/sitegroups/') !== -1) {
response = new Response('', { status: 200 });
}
else if (options!.method!.toUpperCase() === 'POST' && this.endsWith(url, '/getitems')) {
else if (options?.method?.toUpperCase() === 'POST' && this.endsWith(url, '/getitems')) {
response = this.getListItemsCamlQuery(url, options);
}
else if (options!.method!.toUpperCase() === 'POST' && url.toLowerCase().indexOf('/files/add') !== -1) {
else if (options?.method?.toUpperCase() === 'POST' && url.toLowerCase().indexOf('/files/add') !== -1) {
// add, updates and deletes
response = this.saveFile(url, options);
}
@ -96,7 +97,7 @@ export class MockResponse {
private getListItems(urlString: string): Response {
LogHelper.verbose(this.constructor.name, 'getListItems', urlString);
let url = parse(urlString, true, true);
const url = parse(urlString, true, true);
let body: string | undefined;
let totalItemsCount: number = 0;
@ -117,7 +118,7 @@ export class MockResponse {
// revisit to figure out how the source is telling us to page
if (items.length < totalItemsCount) {
let skipParts = urlString.split('&$skip=');
const skipParts = urlString.split('&$skip=');
let nextUrl = '';
if (skipParts.length === 1) {
nextUrl = `${urlString}"&$skip=${items.length}`;
@ -126,7 +127,7 @@ export class MockResponse {
nextUrl = `${urlString}"&$skip=${+skipParts[1] + items.length}`;
}
let result = {
const result = {
'd': {
'results': items,
'__next': nextUrl
@ -137,10 +138,10 @@ export class MockResponse {
}
}
else if (url.pathname.endsWith(')')) {
let index = url.pathname.lastIndexOf('(');
let id = url.pathname.slice(index + 1, url.pathname.length - 1);
const index = url.pathname.lastIndexOf('(');
const id = url.pathname.slice(index + 1, url.pathname.length - 1);
let item = items.filter(i => i.ID === +id)[0];
const item = items.filter(i => i.ID === +id)[0];
body = JSON.stringify(item);
}
else {
@ -153,7 +154,7 @@ export class MockResponse {
private getListProperties(urlString: string): Response {
LogHelper.verbose(this.constructor.name, 'getListProperties', urlString);
let body = {
const body = {
'RootFolder': {
'ServerRelativeUrl': `/${this.listTitle}`
},
@ -170,7 +171,7 @@ export class MockResponse {
private getListItemsCamlQuery(urlString: string, options: IFetchOptions): Response {
LogHelper.verbose(this.constructor.name, 'getListItemsCamlQuery', urlString);
let url = parse(urlString, true, true);
const url = parse(urlString, true, true);
let body: string | undefined;
// try to get the data from local storage and then from mock data
@ -178,29 +179,29 @@ export class MockResponse {
// tslint:disable-next-line:max-line-length
// {"query":{"__metadata":{"type":"SP.CamlQuery"},"ViewXml":"<View><ViewFields><FieldRef Name='Group1'/><FieldRef Name='ProductGroup'/>...</ViewFields><Query><Where><Eq><FieldRef Name='AppliesTo'/><Value Type='Choice'>Cost</Value></Eq></Where></Query><RowLimit>1000</RowLimit></View>"}}
let camlQuery = JSON.parse(options.body);
const camlQuery = JSON.parse(options.body);
let viewXml: string = camlQuery.query.ViewXml;
let viewFieldsStart = viewXml.indexOf('<ViewFields>') + 12;
let viewFieldsEnd = viewXml.indexOf('</ViewFields>');
let queryStart = viewXml.indexOf('<Query>') + 7;
let queryEnd = viewXml.indexOf('</Query>');
let rowLimitStart = viewXml.indexOf('<RowLimit>') + 10;
let rowLimitEnd = viewXml.indexOf('</RowLimit>');
const viewXml: string = camlQuery.query.ViewXml;
const viewFieldsStart = viewXml.indexOf('<ViewFields>') + 12;
const viewFieldsEnd = viewXml.indexOf('</ViewFields>');
const queryStart = viewXml.indexOf('<Query>') + 7;
const queryEnd = viewXml.indexOf('</Query>');
const rowLimitStart = viewXml.indexOf('<RowLimit>') + 10;
const rowLimitEnd = viewXml.indexOf('</RowLimit>');
let viewFields = viewXml.substring(viewFieldsStart, viewFieldsEnd);
let query = viewXml.substring(queryStart, queryEnd); // <Where><Eq><FieldRef Name='AppliesTo'/><Value Type='Choice'>Cost</Value></Eq></Where>
let rowLimit = viewXml.substring(rowLimitStart, rowLimitEnd);
const viewFields = viewXml.substring(viewFieldsStart, viewFieldsEnd);
const query = viewXml.substring(queryStart, queryEnd); // <Where><Eq><FieldRef Name='AppliesTo'/><Value Type='Choice'>Cost</Value></Eq></Where>
const rowLimit = viewXml.substring(rowLimitStart, rowLimitEnd);
let select = viewFields.split(`<FieldRef Name='`).join('').split(`'/>`).join(',');
const select = viewFields.split(`<FieldRef Name='`).join('').split(`'/>`).join(',');
// WARNING - currently this assumes only one clause with an Eq
let whereStart = query.indexOf('<Where>') + 7;
let whereEnd = query.indexOf('</Where>');
const whereStart = query.indexOf('<Where>') + 7;
const whereEnd = query.indexOf('</Where>');
let where = query.substring(whereStart, whereEnd); // <Eq><FieldRef Name='AppliesTo'/><Value Type='Choice'>Cost</Value></Eq>
let compare = where.startsWith('<Eq>') ? 'eq' : null; // add other checks for future compares
const compare = where.startsWith('<Eq>') ? 'eq' : null; // add other checks for future compares
where = where.split('<Eq>').join('').split('</Eq>').join(''); // <FieldRef Name='AppliesTo'/><Value Type='Choice'>Cost</Value>
let filter = where.split(`<FieldRef Name='`).join('').split(`'/>`).join(` ${compare} `)
const filter = where.split(`<FieldRef Name='`).join('').split(`'/>`).join(` ${compare} `)
.split(`<Value Type='Choice'>`).join(`'`).split('</Value>').join(`'`);
items = this.applyFilter(items, filter);
@ -211,10 +212,10 @@ export class MockResponse {
body = JSON.stringify(items);
}
else if (url.pathname.endsWith(')')) {
let index = url.pathname.lastIndexOf('(');
let id = url.pathname.slice(index + 1, url.pathname.length - 1);
const index = url.pathname.lastIndexOf('(');
const id = url.pathname.slice(index + 1, url.pathname.length - 1);
let item = items.filter(i => i.ID === +id)[0];
const item = items.filter(i => i.ID === +id)[0];
body = JSON.stringify(item);
}
else {
@ -227,17 +228,17 @@ export class MockResponse {
private getAttachments(urlString: string): Response {
LogHelper.verbose(this.constructor.name, 'getAttachments', urlString);
let url = parse(urlString, true, true);
const url = parse(urlString, true, true);
let body: string;
// try to get the data from local storage and then from mock data
let items = this.mockListFactory.getListItems(this.listTitle);
const items = this.mockListFactory.getListItems(this.listTitle);
// _api/web/lists/getByTitle([list name])/items([id])/AttachmentFiles
let index = url.pathname.lastIndexOf('(');
let id = url.pathname.slice(index + 1, url.pathname.length - 17);
const index = url.pathname.lastIndexOf('(');
const id = url.pathname.slice(index + 1, url.pathname.length - 17);
let item = items.filter(i => i.ID === +id)[0];
const item = items.filter(i => i.ID === +id)[0];
if (item.AttachmentFiles !== undefined) {
body = JSON.stringify(item.AttachmentFiles);
@ -255,10 +256,10 @@ export class MockResponse {
return new Promise((resolve) => {
let response;
let startIndex = urlString.lastIndexOf(`(`) + 2;
let endIndex = urlString.lastIndexOf(`)`) - 1;
const startIndex = urlString.lastIndexOf(`(`) + 2;
const endIndex = urlString.lastIndexOf(`)`) - 1;
let filePath = urlString.substring(startIndex, endIndex);
const filePath = urlString.substring(startIndex, endIndex);
/* TODO Revisit
if (filePath.indexOf(ApplicationValues.Path) !== -1) {
filePath = filePath.split(ApplicationValues.Path)[1];
@ -267,7 +268,7 @@ export class MockResponse {
*/
if (this.endsWith(urlString, '$value')) {
let xmlhttp = new XMLHttpRequest();
const xmlhttp = new XMLHttpRequest();
xmlhttp.responseType = 'arraybuffer';
// tslint:disable-next-line:no-function-expression
xmlhttp.onreadystatechange = function () {
@ -287,8 +288,8 @@ export class MockResponse {
private getWeb(urlString: string): Response {
// only have a method for this stuff in case we need to do more mock stuff in the future
let url = parse(urlString, true, true);
let body = {
const url = parse(urlString, true, true);
const body = {
'Url': `${url.protocol}//${url.host}/`,
'ServerRelativeUrl': ''
};
@ -305,12 +306,12 @@ export class MockResponse {
private getSiteUser(urlString: string): Response {
LogHelper.verbose(this.constructor.name, 'getSiteUser', urlString);
let url = parse(urlString, true, true);
let search = decodeURIComponent(url.search);
let loginName = search.substring(5, search.length - 1);
const url = parse(urlString, true, true);
const search = decodeURIComponent(url.search);
const loginName = search.substring(5, search.length - 1);
let users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
let user = users.filter(i => {
const users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
const user = users.filter(i => {
return (i.LoginName && i.LoginName.toLowerCase().indexOf(loginName.toLowerCase()) !== -1);
})[0];
@ -321,12 +322,12 @@ export class MockResponse {
private getSiteUserById(urlString: string): Response {
LogHelper.verbose(this.constructor.name, 'getSiteUserById', urlString);
let url = parse(urlString, true, true);
let index = url.pathname.lastIndexOf('(');
let id = url.pathname.slice(index + 1, url.pathname.length - 1);
const url = parse(urlString, true, true);
const index = url.pathname.lastIndexOf('(');
const id = url.pathname.slice(index + 1, url.pathname.length - 1);
let users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
let user = users.filter(i => {
const users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
const user = users.filter(i => {
return (i.ID === +id);
})[0];
@ -337,14 +338,15 @@ export class MockResponse {
private getSiteUserByEmail(urlString: string): Response {
LogHelper.verbose(this.constructor.name, 'getSiteUserByEmail', urlString);
let url = parse(urlString, true, true);
let pathName = decodeURIComponent(url.pathname); // get rid of encoded characters
let index = pathName.lastIndexOf(`('`);
let email = pathName.slice(index + 2, pathName.length - 2);
const url = parse(urlString, true, true);
const pathName = decodeURIComponent(url.pathname); // get rid of encoded characters
const index = pathName.lastIndexOf(`('`);
const email = pathName.slice(index + 2, pathName.length - 2);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let user: any;
if (email.length > 0) {
let users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
const users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
// To better work with SharePoint and mock data...
// User Profile uses "Email"
// User Information uses "EMail"
@ -360,21 +362,24 @@ export class MockResponse {
private saveListItemChanges(urlString: string, options: IFetchOptions): Response {
LogHelper.verbose(this.constructor.name, 'saveListItemChanges', urlString);
let url = parse(urlString, true, true);
const url = parse(urlString, true, true);
let body: string | undefined;
let items = this.mockListFactory.getListItems(this.listTitle);
if (url.pathname.endsWith('/items')) {
// add a new item
let item: any = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const item: any = {};
let storageKey = this.listTitle + '_ItemCount';
const storageKey = this.listTitle + '_ItemCount';
let maxId: number = 0;
if (localStorage.getItem(storageKey) !== null) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
maxId = +localStorage.getItem(storageKey)!;
if (maxId === NaN || maxId === 0) {
if (Number.isNaN(maxId) || maxId === 0) {
if (items.length > 0) {
// eslint-disable-next-line prefer-spread
maxId = Math.max.apply(Math, items.map(i => i.ID));
}
else {
@ -383,16 +388,17 @@ export class MockResponse {
}
maxId = maxId + 1;
item['ID'] = maxId;
item.ID = maxId;
}
let requestBody = JSON.parse(options.body);
const requestBody = JSON.parse(options.body);
Object.keys(requestBody).map(
// eslint-disable-next-line no-return-assign
(e) => item[e] = requestBody[e]
);
// Common to all SharePoint List Items
let now = new Date();
const now = new Date();
item.Created = now;
item.Modified = now;
item.AuthorId = this.currentUser.ID;
@ -406,24 +412,25 @@ export class MockResponse {
}
else if (url.pathname.endsWith(')')) {
// update
let index = url.pathname.lastIndexOf('(');
let id = url.pathname.slice(index + 1, url.pathname.length - 1);
const index = url.pathname.lastIndexOf('(');
const id = url.pathname.slice(index + 1, url.pathname.length - 1);
let item = items.filter(i => i.ID === +id)[0];
const item = items.filter(i => i.ID === +id)[0];
if (options.body !== undefined) {
// update an item
let requestBody = JSON.parse(options.body);
const requestBody = JSON.parse(options.body);
Object.keys(requestBody).map(
// eslint-disable-next-line no-return-assign
(e) => item[e] = requestBody[e]
);
// Common to all SharePoint List Items
let now = new Date();
const now = new Date();
item.Modified = now;
item.EditorId = this.currentUser.ID;
let result: IItemUpdateResult = {
const result: IItemUpdateResult = {
item: item,
data: { 'etag': '' }
};
@ -447,19 +454,19 @@ export class MockResponse {
private saveAttachmentChanges(urlString: string, options: IFetchOptions): Response {
LogHelper.verbose(this.constructor.name, 'saveAttachmentChanges', urlString);
let url = parse(urlString, true, true);
const url = parse(urlString, true, true);
let body: string | undefined;
let items = this.mockListFactory.getListItems(this.listTitle);
const items = this.mockListFactory.getListItems(this.listTitle);
// '/reqdocs/BR/4/attachments/_api/web/lists/getByTitle(%27Requirement%20Documents%27)/items(4)/AttachmentFiles/add(FileName=%27AA%20Template.docx%27)'
let decodedPath = decodeURI(url.pathname);
let index = decodedPath.lastIndexOf('(');
let fileName = decodedPath.slice(index + 2, decodedPath.length - 2);
let startIndex = decodedPath.lastIndexOf('/items(');
let endIndex = decodedPath.lastIndexOf(')/AttachmentFiles');
let id = decodedPath.slice(startIndex + 7, endIndex);
const decodedPath = decodeURI(url.pathname);
const index = decodedPath.lastIndexOf('(');
const fileName = decodedPath.slice(index + 2, decodedPath.length - 2);
const startIndex = decodedPath.lastIndexOf('/items(');
const endIndex = decodedPath.lastIndexOf(')/AttachmentFiles');
const id = decodedPath.slice(startIndex + 7, endIndex);
let item = items.filter(i => i.ID === +id)[0];
const item = items.filter(i => i.ID === +id)[0];
if (item.AttachmentFiles === undefined) {
item.AttachmentFiles = [];
}
@ -474,7 +481,8 @@ export class MockResponse {
});
*/
let fileReader = new FileReader();
const fileReader = new FileReader();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fileReader.onload = (evt: any) => {
this.fileLoaded(evt, items, item, options);
};
@ -496,29 +504,28 @@ export class MockResponse {
private saveFile(urlString: string, options: IFetchOptions): Response {
LogHelper.verbose(this.constructor.name, 'saveFile', urlString);
let url = parse(urlString, true, true);
let body: string;
const url = parse(urlString, true, true);
// /files/add(overwrite=true,url='Authorized%20Retail%20Pricing%20(effective%2004.27.18).xlsx')
let decodedPath = decodeURI(url.pathname);
let index = decodedPath.lastIndexOf('url=');
let fileName = decodedPath.slice(index + 5, decodedPath.length - 2);
const decodedPath = decodeURI(url.pathname);
const index = decodedPath.lastIndexOf('url=');
const fileName = decodedPath.slice(index + 5, decodedPath.length - 2);
// FileSaver.saveAs(options.body, fileName);
let result = {
const result = {
file: options.body,
ServerRelativeUrl: fileName
};
body = JSON.stringify(result);
const body = JSON.stringify(result);
return new Response(body, { status: 200 });
}
private fileLoaded(evt: any, items: any, item: any, options: any) {
let data = evt.target.result;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private fileLoaded(evt: any, items: any, item: any, options: any): void {
const data = evt.target.result;
item.AttachmentFiles.push({
FileName: options.body.name,
ServerRelativeUrl: data
@ -530,24 +537,23 @@ export class MockResponse {
private searchPrincipals(urlString: string, options: IFetchOptions): Response {
LogHelper.verbose(this.constructor.name, 'searchPrincipals', urlString);
let body: string;
let searchOptions = JSON.parse(options.body);
const searchOptions = JSON.parse(options.body);
let users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
let items = users.filter(i => {
const users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
const items = users.filter(i => {
return ((i.DisplayName && i.DisplayName.toLowerCase().indexOf(searchOptions.input.toLowerCase()) !== -1) ||
(i.LoginName && i.LoginName.toLowerCase().indexOf(searchOptions.input.toLowerCase()) !== -1) ||
(i.Email && i.Email.toLowerCase().indexOf(searchOptions.input.toLowerCase()) !== -1)
);
});
let result = {
const result = {
'SearchPrincipalsUsingContextWeb': {
'results': items
}
};
body = JSON.stringify(result);
const body = JSON.stringify(result);
return new Response(body, { status: 200 });
}
@ -555,20 +561,20 @@ export class MockResponse {
private clientPeoplePickerSearchUser(urlString: string, options: IFetchOptions): Response {
LogHelper.verbose(this.constructor.name, 'clientpeoplepickersearchuser', urlString);
let body: string;
let postBody = JSON.parse(options.body);
let query = postBody.queryParams.QueryString.toLowerCase();
const postBody = JSON.parse(options.body);
const query = postBody.queryParams.QueryString.toLowerCase();
let users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
let items = users.filter(i => {
const users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
const items = users.filter(i => {
return ((i.DisplayName && i.DisplayName.toLowerCase().indexOf(query) !== -1) ||
(i.LoginName && i.LoginName.toLowerCase().indexOf(query) !== -1) ||
(i.Email && i.Email.toLowerCase().indexOf(query) !== -1)
);
});
let results: any[] = [];
for (let item of items) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const results: any[] = [];
for (const item of items) {
results.push({
Key: item.Key,
Description: item.Title,
@ -588,13 +594,13 @@ export class MockResponse {
});
}
let result = {
const result = {
d: {
ClientPeoplePickerSearchUser: JSON.stringify(results)
}
};
body = JSON.stringify(result);
const body = JSON.stringify(result);
return new Response(body, { status: 200 });
}
@ -602,7 +608,6 @@ export class MockResponse {
private sendEmail(urlString: string, options: IFetchOptions): Response {
LogHelper.verbose(this.constructor.name, 'sendEmail', urlString);
let body: string;
/*
let emailOptions = JSON.parse(options.body);
@ -630,7 +635,7 @@ export class MockResponse {
FileSaver.saveAs(data, emailOptions.properties.Subject + '.eml');
*/
body = JSON.stringify('');
const body = JSON.stringify('');
return new Response(body, { status: 200 });
}
@ -638,43 +643,42 @@ export class MockResponse {
private ensureUser(urlString: string, options: IFetchOptions): Response {
LogHelper.verbose(this.constructor.name, 'ensureUser', urlString);
let url = parse(urlString, true, true);
let body: string;
let ensureOptions = JSON.parse(options.body);
const url = parse(urlString, true, true);
const ensureOptions = JSON.parse(options.body);
let users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
let user = users.filter(i => {
const users = this.mockListFactory.getListItems(ListTitles.USERS_INFORMATION);
const user = users.filter(i => {
return (i.LoginName && i.LoginName.toLowerCase().indexOf(ensureOptions.logonName.toLowerCase()) !== -1);
})[0];
user['__metadata'] = { id: `${url.protocol}${url.host}/_api/Web/GetUserById(${user.ID})` };
user.Id = user.ID; // because... SharePoint
let result = {
const result = {
'd': user
};
body = JSON.stringify(result);
const body = JSON.stringify(result);
return new Response(body, { status: 200 });
}
private getContextInfo(): Response {
let contexInfo: Partial<IContextInfo> = {
const contexInfo: Partial<IContextInfo> = {
FormDigestTimeoutSeconds: 100,
FormDigestValue: 100
};
let body = JSON.stringify({ d: { GetContextWebInformation: contexInfo } });
const body = JSON.stringify({ d: { GetContextWebInformation: contexInfo } });
return new Response(body, { status: 200 });
}
private async processBatch(urlString: string, options: IFetchOptions): Promise<Response> {
let linesInBody = options.body.split('\n');
let getRequests: string[] = [];
for (let line of linesInBody) {
const linesInBody = options.body.split('\n');
const getRequests: string[] = [];
for (const line of linesInBody) {
if (line.startsWith('GET')) {
let httpIndex = line.indexOf('http://');
let protocolIndex = line.indexOf('HTTP/1.1');
const httpIndex = line.indexOf('http://');
const protocolIndex = line.indexOf('HTTP/1.1');
let requestUrl = line.substring(httpIndex, protocolIndex);
requestUrl = requestUrl.split('/#/').join('/');
@ -684,9 +688,9 @@ export class MockResponse {
// Creating response lines to look like what should be processed here
// https://github.com/pnp/pnpjs/blob/dev/packages/sp/src/batch.ts
let responseLines: string[] = [];
for (let requestUrl of getRequests) {
let getResponse = await this.fetch(requestUrl, { method: 'GET' });
const responseLines: string[] = [];
for (const requestUrl of getRequests) {
const getResponse = await this.fetch(requestUrl, { method: 'GET' });
responseLines.push('--batchresponse_1234');
responseLines.push('Content-Type: application/http');
@ -695,7 +699,7 @@ export class MockResponse {
responseLines.push('HTTP/1.1 200 OK');
responseLines.push('CONTENT-TYPE: application/json;odata=verbose;charset=utf-8');
responseLines.push('');
let text = await getResponse.text();
const text = await getResponse.text();
// TODO - Revisit this as it assumes we are only batching a set of results
responseLines.push(`{"d":{"results":${text}}}`);
}
@ -703,17 +707,18 @@ export class MockResponse {
responseLines.push('--batchresponse_1234--');
responseLines.push('');
let r = responseLines.join('\n');
const r = responseLines.join('\n');
return new Response(r, { status: 200 });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private applyOrderBy(items: any[], orderby: string): any[] {
// Logger.write(`applyOrderBy`);
let sortKey: string;
let sortOrder: string;
if (orderby != null && orderby !== undefined && orderby.length > 0) {
let keys = orderby.split(' ');
if (orderby !== null && orderby !== undefined && orderby.length > 0) {
const keys = orderby.split(' ');
sortKey = keys[0];
sortOrder = keys[1].toLocaleLowerCase();
// https://medium.com/@pagalvin/sort-arrays-using-typescript-592fa6e77f1
@ -728,19 +733,21 @@ export class MockResponse {
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private applySelect(items: any[], select: string): any[] {
// Logger.write(`applySelect`);
let newItems: any[] = [];
if (select != null && select.length > 0) {
let keys = select.split(',');
for (let item of items) {
let newItem = {};
for (let key of keys) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const newItems: any[] = [];
if (select !== null && select.length > 0) {
const keys = select.split(',');
for (const item of items) {
const newItem = {};
for (const key of keys) {
if (key.indexOf('/') === -1) {
newItem[key] = item[key];
}
else {
let partKeys = key.split('/');
const partKeys = key.split('/');
this.expandedSelect(item, newItem, partKeys);
}
}
@ -753,9 +760,10 @@ export class MockResponse {
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private applySkip(items: any[], skip: string): any[] {
// Logger.write(`applySkip`);
if (skip != null && +skip !== NaN) {
if (skip !== null && !Number.isNaN(+skip)) {
return items.slice(+skip);
}
else {
@ -763,9 +771,10 @@ export class MockResponse {
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private applyTop(items: any[], top: string): any[] {
// Logger.write(`applyTop`);
if (top != null && +top !== NaN) {
if (top !== null && !Number.isNaN(+top)) {
return items.slice(0, +top);
}
else {
@ -777,11 +786,12 @@ export class MockResponse {
This is intended for lookups but is a little 'hokey' and the moment since it really grabs the whole lookup object
rather than just the requested properties of the lookup. To be revisited.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private expandedSelect(parentItem: any, parentNewItem: any, partKeys: string[]): any {
// Logger.write(`expandedSelect [${partKeys}]`);
try {
if (partKeys.length === 0) { return; }
let partKey = partKeys.shift();
const partKey = partKeys.shift();
if (parentNewItem && partKey) {
parentNewItem[partKey] = parentItem[partKey];
this.expandedSelect(parentItem[partKey], parentNewItem[partKey], partKeys);
@ -792,14 +802,16 @@ export class MockResponse {
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private applyFilter(items: any[], filter: string): any[] {
// Logger.write(`applyFilter`);
let newItems: any[] = [];
if (filter != null && filter.length > 0) {
let parseResult = new FilterParser().parse(filter);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const newItems: any[] = [];
if (filter !== null && filter.length > 0) {
const parseResult = new FilterParser().parse(filter);
for (let item of items) {
let match: boolean = this.getMatchResult(item, parseResult);
for (const item of items) {
const match: boolean = this.getMatchResult(item, parseResult);
if (match) {
newItems.push(item);
}
@ -811,6 +823,7 @@ export class MockResponse {
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getMatchResult(item: any, parseResult: any): boolean {
switch (parseResult.operator.toLowerCase()) {
case FilterParser.Operators.EQUALS:
@ -828,9 +841,10 @@ export class MockResponse {
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getMatchResult_EQUALS(item: any, parseResult: any): boolean {
let propertyValue = item;
for (let property of parseResult.property) {
for (const property of parseResult.property) {
propertyValue = propertyValue[property];
// if our property is undefined or null no reason to keep looping into it
@ -839,15 +853,16 @@ export class MockResponse {
}
// hack that for multi
if (propertyValue['results'] !== undefined) {
if (propertyValue.results !== undefined) {
LogHelper.verbose(this.constructor.name, 'ensureUser', `getMatchResult_EQUALS ${property} - hack based on assumption this is a multiLookup`);
// if (property.toLowerCase().indexOf('multilookup') !== -1) {
// take the results collection and map to a single array of just the property we are matching on
propertyValue = propertyValue['results'].map(r => r[parseResult.property[1]]);
propertyValue = propertyValue.results.map(r => r[parseResult.property[1]]);
break;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let filterValue: any;
if (typeof (propertyValue) === 'number') {
filterValue = +parseResult.value;
@ -871,12 +886,14 @@ export class MockResponse {
return false;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getMatchResult_NOTEQUALS(item: any, parseResult: any): boolean {
let propertyValue = item;
for (let property of parseResult.property) {
for (const property of parseResult.property) {
propertyValue = propertyValue[property];
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let filterValue: any;
if (typeof (propertyValue) === 'number') {
filterValue = +parseResult.value;
@ -900,12 +917,14 @@ export class MockResponse {
return false;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getMatchResult_SUBSTRINGOF(item: any, parseResult: any): boolean {
let propertyValue = item;
for (let property of parseResult.property) {
for (const property of parseResult.property) {
propertyValue = propertyValue[property];
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let filterValue: any;
if (typeof (propertyValue) === 'number') {
filterValue = +parseResult.value;
@ -922,9 +941,10 @@ export class MockResponse {
}
// This assumes just one 'AND'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getMatchResult_AND(item: any, parseResult: any): boolean {
let parseResult1 = this.getMatchResult(item, parseResult.property);
let parseResult2 = this.getMatchResult(item, parseResult.value);
const parseResult1 = this.getMatchResult(item, parseResult.property);
const parseResult2 = this.getMatchResult(item, parseResult.value);
if (parseResult1 === true && parseResult2 === true) {
return true;
@ -935,9 +955,10 @@ export class MockResponse {
}
// This assumes just one 'OR'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getMatchResult_OR(item: any, parseResult: any): boolean {
let parseResult1 = this.getMatchResult(item, parseResult.property);
let parseResult2 = this.getMatchResult(item, parseResult.value);
const parseResult1 = this.getMatchResult(item, parseResult.property);
const parseResult2 = this.getMatchResult(item, parseResult.value);
if (parseResult1 === true || parseResult2 === true) {
return true;

View File

@ -1,7 +1,7 @@
export interface IPage {
id: number;
title: string;
etag?: string | null;
etag?: string;
url: string;
parentPageId?: number;
}

View File

@ -8,10 +8,11 @@ export class ErrorHelper {
this.logError(methodName, error);
}
public static logError(methodName: string, error: Error) {
public static logError(methodName: string, error: Error): void {
LogHelper.exception(this.constructor.name, methodName, error);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public static logPnpError(methodName: string, error: HttpRequestError | any): string | undefined {
let msg: string | undefined;
if (error instanceof HttpRequestError) {
@ -23,10 +24,10 @@ export class ErrorHelper {
LogHelper.exception(this.constructor.name, methodName, error);
}
}
else if (error.data != null && error.data.responseBody && error.data.responseBody.error && error.data.responseBody.error.message) {
else if (error.data !== null && error.data.responseBody && error.data.responseBody.error && error.data.responseBody.error.message) {
// for email exceptions they weren't coming in as "instanceof HttpRequestError"
msg = error.data.responseBody.error.message.value;
LogHelper.error(this.constructor.name, methodName, msg!);
LogHelper.error(this.constructor.name, methodName, msg);
}
else if (error instanceof Error) {
if (error.message.indexOf('[412] Precondition Failed') !== -1) {

View File

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

View File

@ -1,17 +1,9 @@
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { Logger, ConsoleListener, LogLevel } from "@pnp/logging";
import { CustomFetchClient } from '@src/mocks/customfetchclient';
export default class BaseWebPart<TProperties> extends BaseClientSideWebPart<TProperties> {
protected async onInit(): Promise<void> {
let isUsingSharePoint = true;
if (Environment.type === EnvironmentType.Local || Environment.type === EnvironmentType.Test) {
isUsingSharePoint = false;
}
return super.onInit().then(_ => {
// subscribe a listener
Logger.subscribe(new ConsoleListener());
@ -23,5 +15,6 @@ export default class BaseWebPart<TProperties> extends BaseClientSideWebPart<TPro
}
public render(): void {
Logger.write("Render");
}
}

View File

@ -3,7 +3,6 @@ import * as ReactDom from 'react-dom';
import { ThemeProvider, IReadonlyTheme, ThemeChangedEventArgs } from '@microsoft/sp-component-base';
import { Version, DisplayMode } from '@microsoft/sp-core-library';
import { IPropertyPaneConfiguration, IPropertyPaneGroup, PropertyPaneChoiceGroup, PropertyPaneLabel } from '@microsoft/sp-property-pane';
import { UrlQueryParameterCollection } from '@microsoft/sp-core-library';
import { PropertyFieldNumber } from '@pnp/spfx-property-controls/lib/PropertyFieldNumber';
import BaseWebPart from '@src/webparts/BaseWebPart';
import { Parameters, PagesToDisplay, LogHelper } from '@src/utilities';
@ -80,9 +79,9 @@ export default class PageHierarchyWebPart extends BaseWebPart<IPageHierarchyWebP
We'll allow user to test with a property and also using mock data allow them to navigate when on local host with a querystring
*/
private getDebugPageId(): number {
let queryParms = new UrlQueryParameterCollection(window.location.href);
const queryParms = new URLSearchParams(window.location.href);
let debugPageId = this.properties.debugPageId;
if (queryParms.getValue(Parameters.DEBUGPAGEID)) { debugPageId = Number(queryParms.getValue(Parameters.DEBUGPAGEID)); }
if (queryParms.get(Parameters.DEBUGPAGEID)) { debugPageId = Number(queryParms.get(Parameters.DEBUGPAGEID)); }
return debugPageId;
}
@ -90,7 +89,7 @@ export default class PageHierarchyWebPart extends BaseWebPart<IPageHierarchyWebP
when page edit goes from edit to read we start a timer so that we can wait for the save to occur
Things like the page title and page parent page property changing affect us
*/
protected onDisplayModeChanged(oldDisplayMode: DisplayMode) {
protected onDisplayModeChanged(oldDisplayMode: DisplayMode): void {
if (oldDisplayMode === DisplayMode.Edit) {
setTimeout(() => {
this.pageEditFinished = true;
@ -109,7 +108,7 @@ export default class PageHierarchyWebPart extends BaseWebPart<IPageHierarchyWebP
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
let propertyPaneGroups: IPropertyPaneGroup[] = [];
const propertyPaneGroups: IPropertyPaneGroup[] = [];
// If this webpart isn't on a page, we don't have a list item so let us provide our own to debug
if (this.context.pageContext.listItem === undefined) {

View File

@ -1,4 +1,4 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
@import '~@fluentui/react/dist/sass/References.scss';
.defaultContainer {
.container {

View File

@ -39,18 +39,13 @@ export const Container: React.FunctionComponent<IContainerProps> = props => {
// if the parent page column was never created or it was deleted force them to recreate it
if (!pagesApi.state.parentPageColumnExists) {
var description = strings.ParentPageMissing_Placeholder_Description;
if(!pagesApi.state.userCanManagePages) {
description = strings.ParentPageMissing_Placeholder_Description_NoPermissions;
}
controlToRender =
<div>
<Placeholder
iconName='FieldRequired'
hideButton={!pagesApi.state.userCanManagePages}
iconText={strings.ParentPageMissing_Placeholder_IconText}
description={description}
description={!pagesApi.state.userCanManagePages ? strings.ParentPageMissing_Placeholder_Description_NoPermissions : strings.ParentPageMissing_Placeholder_Description}
buttonLabel={strings.ParentPageMissing_Placeholder_ButtonLabel}
onConfigure={pagesApi.addParentPageField} />
</div>;

View File

@ -1,9 +1,9 @@
import * as React from 'react';
import { useState } from 'react';
import styles from './Layouts.module.scss';
import { RenderDirection, LogHelper } from '@src/utilities';
import { RenderDirection } from '@src/utilities';
import { IPage } from '@src/models/IPage';
import { ActionButton, Icon } from 'office-ui-fabric-react';
import { ActionButton, Icon } from '@fluentui/react';
import { ILayoutProps } from './ILayoutProps';
import ReactResizeDetector from 'react-resize-detector';
import * as strings from 'PageHierarchyWebPartStrings';
@ -12,9 +12,9 @@ export const BreadcrumbLayout: React.FunctionComponent<ILayoutProps> = props =>
const [elementWidth, setElementWidth] = useState(props.domElement.getBoundingClientRect().width);
// 455 was chosen because that's the smallest break pointin 2 column before it wraps and stacks
let renderDirection = elementWidth > 455 ? RenderDirection.Horizontal : RenderDirection.Vertical;
const renderDirection = elementWidth > 455 ? RenderDirection.Horizontal : RenderDirection.Vertical;
const renderPageAsBreadcrumb = (page: IPage, index: number, pages: IPage[]) => {
const renderPageAsBreadcrumb = (page: IPage, index: number, pages: IPage[]): React.ReactElement => {
if (page) {
return (
<li key={page.id} className={styles.breadcrumbLayoutItem}>
@ -41,7 +41,7 @@ export const BreadcrumbLayout: React.FunctionComponent<ILayoutProps> = props =>
}
};
const renderPageAsStack = (page: IPage, index: number, pages: IPage[]) => {
const renderPageAsStack = (page: IPage, index: number, pages: IPage[]): React.ReactElement => {
if (page) {
return (
<li key={page.id} className={styles.breadcrumbLayoutItem}>
@ -63,7 +63,7 @@ export const BreadcrumbLayout: React.FunctionComponent<ILayoutProps> = props =>
}
};
const renderPages = (pages: IPage[], ) => {
const renderPages = (pages: IPage[], ): React.ReactElement[] => {
if (renderDirection === RenderDirection.Horizontal) {
return pages.map((value, index, array) => renderPageAsBreadcrumb(value, index, array));
}
@ -72,7 +72,7 @@ export const BreadcrumbLayout: React.FunctionComponent<ILayoutProps> = props =>
}
};
const onResize = () => {
const onResize = (): void => {
setElementWidth(props.domElement.getBoundingClientRect().width);
};

View File

@ -1,6 +1,6 @@
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { IPage } from '@src/models/IPage';
import { INavLink } from 'office-ui-fabric-react';
import { INavLink } from '@fluentui/react';
export interface ILayoutProps {
domElement: HTMLElement;

View File

@ -1,4 +1,4 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
@import '~@fluentui/react/dist/sass/References.scss';
.layouts {

View File

@ -2,12 +2,13 @@ import * as React from 'react';
import { useState } from 'react';
import styles from './Layouts.module.scss';
import { IPage } from '@src/models/IPage';
import { Icon, ActionButton } from 'office-ui-fabric-react';
import { ActionButton } from '@fluentui/react';
import { ILayoutProps } from './ILayoutProps';
import ReactResizeDetector from 'react-resize-detector';
import * as strings from 'PageHierarchyWebPartStrings';
export const ListLayout: React.FunctionComponent<ILayoutProps> = props => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [elementWidth, setElementWidth] = useState(props.domElement.getBoundingClientRect().width);
/*
@ -26,11 +27,7 @@ export const ListLayout: React.FunctionComponent<ILayoutProps> = props => {
Horizontal Stack - Wrapping - Advanced
*/
if (elementWidth < 380) {
}
const renderPage = (page: IPage, index: number, pages: IPage[]) => {
const renderPage = (page: IPage, index: number, pages: IPage[]): React.ReactElement => {
if (page) {
return (
<li className={styles.listLayoutItem}>
@ -53,11 +50,11 @@ export const ListLayout: React.FunctionComponent<ILayoutProps> = props => {
}
};
const renderPages = (pages: IPage[], ) => {
const renderPages = (pages: IPage[], ): React.ReactElement[] => {
return pages.map((value, index, array) => renderPage(value, index, array));
};
const onResize = () => {
const onResize = (): void => {
setElementWidth(props.domElement.getBoundingClientRect().width);
};

View File

@ -2,7 +2,7 @@ import * as React from 'react';
import styles from './Layouts.module.scss';
import { ILayoutProps } from './ILayoutProps';
import * as strings from 'PageHierarchyWebPartStrings';
import { Nav } from 'office-ui-fabric-react';
import { Nav } from '@fluentui/react';
export const TreeLayout: React.FunctionComponent<ILayoutProps> = props => {
return(

View File

@ -1,5 +1,5 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.2/includes/tsconfig-web.json",
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.7/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,

View File

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